babylon.no-module.max.js 4.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193
  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. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (!otherMesh.material) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers.slice();
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers ? samplers.slice() : [];
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. this._loadVertexShader(vertexSource, function (vertexCode) {
  216. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  217. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  218. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  219. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  220. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  221. if (baseName) {
  222. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  223. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  224. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  225. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  226. }
  227. else {
  228. _this._vertexSourceCode = migratedVertexCode;
  229. _this._fragmentSourceCode = migratedFragmentCode;
  230. }
  231. _this._prepareEffect();
  232. });
  233. });
  234. });
  235. });
  236. });
  237. });
  238. }
  239. Object.defineProperty(Effect.prototype, "key", {
  240. /**
  241. * Unique key for this effect
  242. */
  243. get: function () {
  244. return this._key;
  245. },
  246. enumerable: true,
  247. configurable: true
  248. });
  249. /**
  250. * If the effect has been compiled and prepared.
  251. * @returns if the effect is compiled and prepared.
  252. */
  253. Effect.prototype.isReady = function () {
  254. return this._isReady;
  255. };
  256. /**
  257. * The engine the effect was initialized with.
  258. * @returns the engine.
  259. */
  260. Effect.prototype.getEngine = function () {
  261. return this._engine;
  262. };
  263. /**
  264. * The compiled webGL program for the effect
  265. * @returns the webGL program.
  266. */
  267. Effect.prototype.getProgram = function () {
  268. return this._program;
  269. };
  270. /**
  271. * The set of names of attribute variables for the shader.
  272. * @returns An array of attribute names.
  273. */
  274. Effect.prototype.getAttributesNames = function () {
  275. return this._attributesNames;
  276. };
  277. /**
  278. * Returns the attribute at the given index.
  279. * @param index The index of the attribute.
  280. * @returns The location of the attribute.
  281. */
  282. Effect.prototype.getAttributeLocation = function (index) {
  283. return this._attributes[index];
  284. };
  285. /**
  286. * Returns the attribute based on the name of the variable.
  287. * @param name of the attribute to look up.
  288. * @returns the attribute location.
  289. */
  290. Effect.prototype.getAttributeLocationByName = function (name) {
  291. var index = this._attributesNames.indexOf(name);
  292. return this._attributes[index];
  293. };
  294. /**
  295. * The number of attributes.
  296. * @returns the numnber of attributes.
  297. */
  298. Effect.prototype.getAttributesCount = function () {
  299. return this._attributes.length;
  300. };
  301. /**
  302. * Gets the index of a uniform variable.
  303. * @param uniformName of the uniform to look up.
  304. * @returns the index.
  305. */
  306. Effect.prototype.getUniformIndex = function (uniformName) {
  307. return this._uniformsNames.indexOf(uniformName);
  308. };
  309. /**
  310. * Returns the attribute based on the name of the variable.
  311. * @param uniformName of the uniform to look up.
  312. * @returns the location of the uniform.
  313. */
  314. Effect.prototype.getUniform = function (uniformName) {
  315. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  316. };
  317. /**
  318. * Returns an array of sampler variable names
  319. * @returns The array of sampler variable neames.
  320. */
  321. Effect.prototype.getSamplers = function () {
  322. return this._samplers;
  323. };
  324. /**
  325. * The error from the last compilation.
  326. * @returns the error string.
  327. */
  328. Effect.prototype.getCompilationError = function () {
  329. return this._compilationError;
  330. };
  331. /**
  332. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  333. * @param func The callback to be used.
  334. */
  335. Effect.prototype.executeWhenCompiled = function (func) {
  336. if (this.isReady()) {
  337. func(this);
  338. return;
  339. }
  340. this.onCompileObservable.add(function (effect) {
  341. func(effect);
  342. });
  343. };
  344. /** @hidden */
  345. Effect.prototype._loadVertexShader = function (vertex, callback) {
  346. if (BABYLON.Tools.IsWindowObjectExist()) {
  347. // DOM element ?
  348. if (vertex instanceof HTMLElement) {
  349. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  350. callback(vertexCode);
  351. return;
  352. }
  353. }
  354. // Base64 encoded ?
  355. if (vertex.substr(0, 7) === "base64:") {
  356. var vertexBinary = window.atob(vertex.substr(7));
  357. callback(vertexBinary);
  358. return;
  359. }
  360. // Is in local store ?
  361. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  362. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  363. return;
  364. }
  365. var vertexShaderUrl;
  366. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  367. vertexShaderUrl = vertex;
  368. }
  369. else {
  370. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  371. }
  372. // Vertex shader
  373. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  374. };
  375. /** @hidden */
  376. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. callback(fragmentCode);
  382. return;
  383. }
  384. }
  385. // Base64 encoded ?
  386. if (fragment.substr(0, 7) === "base64:") {
  387. var fragmentBinary = window.atob(fragment.substr(7));
  388. callback(fragmentBinary);
  389. return;
  390. }
  391. // Is in local store ?
  392. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  393. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  394. return;
  395. }
  396. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  397. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  398. return;
  399. }
  400. var fragmentShaderUrl;
  401. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  402. fragmentShaderUrl = fragment;
  403. }
  404. else {
  405. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  406. }
  407. // Fragment shader
  408. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  409. };
  410. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  411. // Rebuild shaders source code
  412. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  413. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  414. vertexCode = prefix + vertexCode;
  415. fragmentCode = prefix + fragmentCode;
  416. // Number lines of shaders source code
  417. var i = 2;
  418. var regex = /\n/gm;
  419. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  420. i = 2;
  421. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  422. // Dump shaders name and formatted source code
  423. if (this.name.vertexElement) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  426. }
  427. else if (this.name.vertex) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  430. }
  431. else {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  434. }
  435. };
  436. ;
  437. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  438. var preparedSourceCode = this._processPrecision(sourceCode);
  439. if (this._engine.webGLVersion == 1) {
  440. callback(preparedSourceCode);
  441. return;
  442. }
  443. // Already converted
  444. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  445. callback(preparedSourceCode.replace("#version 300 es", ""));
  446. return;
  447. }
  448. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  449. // Remove extensions
  450. // #extension GL_OES_standard_derivatives : enable
  451. // #extension GL_EXT_shader_texture_lod : enable
  452. // #extension GL_EXT_frag_depth : enable
  453. // #extension GL_EXT_draw_buffers : require
  454. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  455. var result = preparedSourceCode.replace(regex, "");
  456. // Migrate to GLSL v300
  457. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  458. result = result.replace(/attribute[ \t]/g, "in ");
  459. result = result.replace(/[ \t]attribute/g, " in");
  460. if (isFragment) {
  461. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  462. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/texture2D\s*\(/g, "texture(");
  464. result = result.replace(/textureCube\s*\(/g, "texture(");
  465. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  466. result = result.replace(/gl_FragColor/g, "glFragColor");
  467. result = result.replace(/gl_FragData/g, "glFragData");
  468. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  469. }
  470. callback(result);
  471. };
  472. Effect.prototype._processIncludes = function (sourceCode, callback) {
  473. var _this = this;
  474. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  475. var match = regex.exec(sourceCode);
  476. var returnValue = new String(sourceCode);
  477. while (match != null) {
  478. var includeFile = match[1];
  479. // Uniform declaration
  480. if (includeFile.indexOf("__decl__") !== -1) {
  481. includeFile = includeFile.replace(/__decl__/, "");
  482. if (this._engine.supportsUniformBuffers) {
  483. includeFile = includeFile.replace(/Vertex/, "Ubo");
  484. includeFile = includeFile.replace(/Fragment/, "Ubo");
  485. }
  486. includeFile = includeFile + "Declaration";
  487. }
  488. if (Effect.IncludesShadersStore[includeFile]) {
  489. // Substitution
  490. var includeContent = Effect.IncludesShadersStore[includeFile];
  491. if (match[2]) {
  492. var splits = match[3].split(",");
  493. for (var index = 0; index < splits.length; index += 2) {
  494. var source = new RegExp(splits[index], "g");
  495. var dest = splits[index + 1];
  496. includeContent = includeContent.replace(source, dest);
  497. }
  498. }
  499. if (match[4]) {
  500. var indexString = match[5];
  501. if (indexString.indexOf("..") !== -1) {
  502. var indexSplits = indexString.split("..");
  503. var minIndex = parseInt(indexSplits[0]);
  504. var maxIndex = parseInt(indexSplits[1]);
  505. var sourceIncludeContent = includeContent.slice(0);
  506. includeContent = "";
  507. if (isNaN(maxIndex)) {
  508. maxIndex = this._indexParameters[indexSplits[1]];
  509. }
  510. for (var i = minIndex; i < maxIndex; i++) {
  511. if (!this._engine.supportsUniformBuffers) {
  512. // Ubo replacement
  513. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  514. return p1 + "{X}";
  515. });
  516. }
  517. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  518. }
  519. }
  520. else {
  521. if (!this._engine.supportsUniformBuffers) {
  522. // Ubo replacement
  523. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  524. return p1 + "{X}";
  525. });
  526. }
  527. includeContent = includeContent.replace(/\{X\}/g, indexString);
  528. }
  529. }
  530. // Replace
  531. returnValue = returnValue.replace(match[0], includeContent);
  532. }
  533. else {
  534. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  535. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  536. Effect.IncludesShadersStore[includeFile] = fileContent;
  537. _this._processIncludes(returnValue, callback);
  538. });
  539. return;
  540. }
  541. match = regex.exec(sourceCode);
  542. }
  543. callback(returnValue);
  544. };
  545. Effect.prototype._processPrecision = function (source) {
  546. if (source.indexOf("precision highp float") === -1) {
  547. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  548. source = "precision mediump float;\n" + source;
  549. }
  550. else {
  551. source = "precision highp float;\n" + source;
  552. }
  553. }
  554. else {
  555. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  556. source = source.replace("precision highp float", "precision mediump float");
  557. }
  558. }
  559. return source;
  560. };
  561. /**
  562. * Recompiles the webGL program
  563. * @param vertexSourceCode The source code for the vertex shader.
  564. * @param fragmentSourceCode The source code for the fragment shader.
  565. * @param onCompiled Callback called when completed.
  566. * @param onError Callback called on error.
  567. */
  568. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  569. var _this = this;
  570. this._isReady = false;
  571. this._vertexSourceCodeOverride = vertexSourceCode;
  572. this._fragmentSourceCodeOverride = fragmentSourceCode;
  573. this.onError = function (effect, error) {
  574. if (onError) {
  575. onError(error);
  576. }
  577. };
  578. this.onCompiled = function () {
  579. var scenes = _this.getEngine().scenes;
  580. for (var i = 0; i < scenes.length; i++) {
  581. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  582. }
  583. if (onCompiled) {
  584. onCompiled(_this._program);
  585. }
  586. };
  587. this._fallbacks = null;
  588. this._prepareEffect();
  589. };
  590. /**
  591. * Gets the uniform locations of the the specified variable names
  592. * @param names THe names of the variables to lookup.
  593. * @returns Array of locations in the same order as variable names.
  594. */
  595. Effect.prototype.getSpecificUniformLocations = function (names) {
  596. var engine = this._engine;
  597. return engine.getUniforms(this._program, names);
  598. };
  599. /**
  600. * Prepares the effect
  601. */
  602. Effect.prototype._prepareEffect = function () {
  603. var attributesNames = this._attributesNames;
  604. var defines = this.defines;
  605. var fallbacks = this._fallbacks;
  606. this._valueCache = {};
  607. var previousProgram = this._program;
  608. try {
  609. var engine = this._engine;
  610. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  611. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  612. }
  613. else {
  614. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  615. }
  616. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  617. if (engine.supportsUniformBuffers) {
  618. for (var name in this._uniformBuffersNames) {
  619. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  620. }
  621. }
  622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  623. this._attributes = engine.getAttributes(this._program, attributesNames);
  624. var index;
  625. for (index = 0; index < this._samplers.length; index++) {
  626. var sampler = this.getUniform(this._samplers[index]);
  627. if (sampler == null) {
  628. this._samplers.splice(index, 1);
  629. index--;
  630. }
  631. }
  632. engine.bindSamplers(this);
  633. this._compilationError = "";
  634. this._isReady = true;
  635. if (this.onCompiled) {
  636. this.onCompiled(this);
  637. }
  638. this.onCompileObservable.notifyObservers(this);
  639. this.onCompileObservable.clear();
  640. // Unbind mesh reference in fallbacks
  641. if (this._fallbacks) {
  642. this._fallbacks.unBindMesh();
  643. }
  644. if (previousProgram) {
  645. this.getEngine()._deleteProgram(previousProgram);
  646. }
  647. }
  648. catch (e) {
  649. this._compilationError = e.message;
  650. // Let's go through fallbacks then
  651. BABYLON.Tools.Error("Unable to compile effect:");
  652. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  653. return " " + uniform;
  654. }));
  655. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  656. return " " + attribute;
  657. }));
  658. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  659. BABYLON.Tools.Error("Error: " + this._compilationError);
  660. if (previousProgram) {
  661. this._program = previousProgram;
  662. this._isReady = true;
  663. if (this.onError) {
  664. this.onError(this, this._compilationError);
  665. }
  666. this.onErrorObservable.notifyObservers(this);
  667. }
  668. if (fallbacks && fallbacks.isMoreFallbacks) {
  669. BABYLON.Tools.Error("Trying next fallback.");
  670. this.defines = fallbacks.reduce(this.defines, this);
  671. this._prepareEffect();
  672. }
  673. else { // Sorry we did everything we can
  674. if (this.onError) {
  675. this.onError(this, this._compilationError);
  676. }
  677. this.onErrorObservable.notifyObservers(this);
  678. this.onErrorObservable.clear();
  679. // Unbind mesh reference in fallbacks
  680. if (this._fallbacks) {
  681. this._fallbacks.unBindMesh();
  682. }
  683. }
  684. }
  685. };
  686. Object.defineProperty(Effect.prototype, "isSupported", {
  687. /**
  688. * Checks if the effect is supported. (Must be called after compilation)
  689. */
  690. get: function () {
  691. return this._compilationError === "";
  692. },
  693. enumerable: true,
  694. configurable: true
  695. });
  696. /**
  697. * Binds a texture to the engine to be used as output of the shader.
  698. * @param channel Name of the output variable.
  699. * @param texture Texture to bind.
  700. */
  701. Effect.prototype._bindTexture = function (channel, texture) {
  702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  703. };
  704. /**
  705. * Sets a texture on the engine to be used in the shader.
  706. * @param channel Name of the sampler variable.
  707. * @param texture Texture to set.
  708. */
  709. Effect.prototype.setTexture = function (channel, texture) {
  710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  711. };
  712. /**
  713. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  714. * @param channel Name of the sampler variable.
  715. * @param texture Texture to set.
  716. */
  717. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  718. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  719. };
  720. /**
  721. * Sets an array of textures on the engine to be used in the shader.
  722. * @param channel Name of the variable.
  723. * @param textures Textures to set.
  724. */
  725. Effect.prototype.setTextureArray = function (channel, textures) {
  726. if (this._samplers.indexOf(channel + "Ex") === -1) {
  727. var initialPos = this._samplers.indexOf(channel);
  728. for (var index = 1; index < textures.length; index++) {
  729. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  730. }
  731. }
  732. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  733. };
  734. /**
  735. * 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)
  736. * @param channel Name of the sampler variable.
  737. * @param postProcess Post process to get the input texture from.
  738. */
  739. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  740. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  741. };
  742. /**
  743. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  744. * 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)
  745. * @param channel Name of the sampler variable.
  746. * @param postProcess Post process to get the output texture from.
  747. */
  748. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  749. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  750. };
  751. /** @hidden */
  752. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  753. var cache = this._valueCache[uniformName];
  754. var flag = matrix.updateFlag;
  755. if (cache !== undefined && cache === flag) {
  756. return false;
  757. }
  758. this._valueCache[uniformName] = flag;
  759. return true;
  760. };
  761. /** @hidden */
  762. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  763. var cache = this._valueCache[uniformName];
  764. if (!cache) {
  765. cache = [x, y];
  766. this._valueCache[uniformName] = cache;
  767. return true;
  768. }
  769. var changed = false;
  770. if (cache[0] !== x) {
  771. cache[0] = x;
  772. changed = true;
  773. }
  774. if (cache[1] !== y) {
  775. cache[1] = y;
  776. changed = true;
  777. }
  778. return changed;
  779. };
  780. /** @hidden */
  781. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  782. var cache = this._valueCache[uniformName];
  783. if (!cache) {
  784. cache = [x, y, z];
  785. this._valueCache[uniformName] = cache;
  786. return true;
  787. }
  788. var changed = false;
  789. if (cache[0] !== x) {
  790. cache[0] = x;
  791. changed = true;
  792. }
  793. if (cache[1] !== y) {
  794. cache[1] = y;
  795. changed = true;
  796. }
  797. if (cache[2] !== z) {
  798. cache[2] = z;
  799. changed = true;
  800. }
  801. return changed;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y, z, w];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. if (cache[2] !== z) {
  821. cache[2] = z;
  822. changed = true;
  823. }
  824. if (cache[3] !== w) {
  825. cache[3] = w;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /**
  831. * Binds a buffer to a uniform.
  832. * @param buffer Buffer to bind.
  833. * @param name Name of the uniform variable to bind to.
  834. */
  835. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  836. var bufferName = this._uniformBuffersNames[name];
  837. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  838. return;
  839. }
  840. Effect._baseCache[bufferName] = buffer;
  841. this._engine.bindUniformBufferBase(buffer, bufferName);
  842. };
  843. /**
  844. * Binds block to a uniform.
  845. * @param blockName Name of the block to bind.
  846. * @param index Index to bind.
  847. */
  848. Effect.prototype.bindUniformBlock = function (blockName, index) {
  849. this._engine.bindUniformBlock(this._program, blockName, index);
  850. };
  851. /**
  852. * Sets an interger value on a uniform variable.
  853. * @param uniformName Name of the variable.
  854. * @param value Value to be set.
  855. * @returns this effect.
  856. */
  857. Effect.prototype.setInt = function (uniformName, value) {
  858. var cache = this._valueCache[uniformName];
  859. if (cache !== undefined && cache === value)
  860. return this;
  861. this._valueCache[uniformName] = value;
  862. this._engine.setInt(this.getUniform(uniformName), value);
  863. return this;
  864. };
  865. /**
  866. * Sets an int array on a uniform variable.
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * 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)
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setIntArray2 = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setIntArray2(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * 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)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setIntArray3 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setIntArray3(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * 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)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setIntArray4 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setIntArray4(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * Sets an float array on a uniform variable.
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * 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)
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * 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)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * 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)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * Sets an array on a uniform variable.
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * 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)
  966. * @param uniformName Name of the variable.
  967. * @param array array to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setArray2 = function (uniformName, array) {
  971. this._valueCache[uniformName] = null;
  972. this._engine.setArray2(this.getUniform(uniformName), array);
  973. return this;
  974. };
  975. /**
  976. * 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)
  977. * @param uniformName Name of the variable.
  978. * @param array array to be set.
  979. * @returns this effect.
  980. */
  981. Effect.prototype.setArray3 = function (uniformName, array) {
  982. this._valueCache[uniformName] = null;
  983. this._engine.setArray3(this.getUniform(uniformName), array);
  984. return this;
  985. };
  986. /**
  987. * 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)
  988. * @param uniformName Name of the variable.
  989. * @param array array to be set.
  990. * @returns this effect.
  991. */
  992. Effect.prototype.setArray4 = function (uniformName, array) {
  993. this._valueCache[uniformName] = null;
  994. this._engine.setArray4(this.getUniform(uniformName), array);
  995. return this;
  996. };
  997. /**
  998. * Sets matrices on a uniform variable.
  999. * @param uniformName Name of the variable.
  1000. * @param matrices matrices to be set.
  1001. * @returns this effect.
  1002. */
  1003. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1004. if (!matrices) {
  1005. return this;
  1006. }
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1009. return this;
  1010. };
  1011. /**
  1012. * Sets matrix on a uniform variable.
  1013. * @param uniformName Name of the variable.
  1014. * @param matrix matrix to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1018. if (this._cacheMatrix(uniformName, matrix)) {
  1019. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1020. }
  1021. return this;
  1022. };
  1023. /**
  1024. * 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)
  1025. * @param uniformName Name of the variable.
  1026. * @param matrix matrix to be set.
  1027. * @returns this effect.
  1028. */
  1029. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1030. this._valueCache[uniformName] = null;
  1031. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1032. return this;
  1033. };
  1034. /**
  1035. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1036. * @param uniformName Name of the variable.
  1037. * @param matrix matrix to be set.
  1038. * @returns this effect.
  1039. */
  1040. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1041. this._valueCache[uniformName] = null;
  1042. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1043. return this;
  1044. };
  1045. /**
  1046. * Sets a float on a uniform variable.
  1047. * @param uniformName Name of the variable.
  1048. * @param value value to be set.
  1049. * @returns this effect.
  1050. */
  1051. Effect.prototype.setFloat = function (uniformName, value) {
  1052. var cache = this._valueCache[uniformName];
  1053. if (cache !== undefined && cache === value)
  1054. return this;
  1055. this._valueCache[uniformName] = value;
  1056. this._engine.setFloat(this.getUniform(uniformName), value);
  1057. return this;
  1058. };
  1059. /**
  1060. * Sets a boolean on a uniform variable.
  1061. * @param uniformName Name of the variable.
  1062. * @param bool value to be set.
  1063. * @returns this effect.
  1064. */
  1065. Effect.prototype.setBool = function (uniformName, bool) {
  1066. var cache = this._valueCache[uniformName];
  1067. if (cache !== undefined && cache === bool)
  1068. return this;
  1069. this._valueCache[uniformName] = bool;
  1070. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets a Vector2 on a uniform variable.
  1075. * @param uniformName Name of the variable.
  1076. * @param vector2 vector2 to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1080. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1081. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1082. }
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a float2 on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param x First float in float2.
  1089. * @param y Second float in float2.
  1090. * @returns this effect.
  1091. */
  1092. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1093. if (this._cacheFloat2(uniformName, x, y)) {
  1094. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1095. }
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a Vector3 on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param vector3 Value to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1105. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1106. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1107. }
  1108. return this;
  1109. };
  1110. /**
  1111. * Sets a float3 on a uniform variable.
  1112. * @param uniformName Name of the variable.
  1113. * @param x First float in float3.
  1114. * @param y Second float in float3.
  1115. * @param z Third float in float3.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1119. if (this._cacheFloat3(uniformName, x, y, z)) {
  1120. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1121. }
  1122. return this;
  1123. };
  1124. /**
  1125. * Sets a Vector4 on a uniform variable.
  1126. * @param uniformName Name of the variable.
  1127. * @param vector4 Value to be set.
  1128. * @returns this effect.
  1129. */
  1130. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1131. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1132. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1133. }
  1134. return this;
  1135. };
  1136. /**
  1137. * Sets a float4 on a uniform variable.
  1138. * @param uniformName Name of the variable.
  1139. * @param x First float in float4.
  1140. * @param y Second float in float4.
  1141. * @param z Third float in float4.
  1142. * @param w Fourth float in float4.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1146. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a Color3 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param color3 Value to be set.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setColor3 = function (uniformName, color3) {
  1158. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1159. this._engine.setColor3(this.getUniform(uniformName), color3);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a Color4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param color3 Value to be set.
  1167. * @param alpha Alpha value to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1171. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1172. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1173. }
  1174. return this;
  1175. };
  1176. /**
  1177. * Sets a Color4 on a uniform variable
  1178. * @param uniformName defines the name of the variable
  1179. * @param color4 defines the value to be set
  1180. * @returns this effect.
  1181. */
  1182. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1183. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1184. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1185. }
  1186. return this;
  1187. };
  1188. /**
  1189. * Resets the cache of effects.
  1190. */
  1191. Effect.ResetCache = function () {
  1192. Effect._baseCache = {};
  1193. };
  1194. Effect._uniqueIdSeed = 0;
  1195. Effect._baseCache = {};
  1196. /**
  1197. * Store of each shader (The can be looked up using effect.key)
  1198. */
  1199. Effect.ShadersStore = {};
  1200. /**
  1201. * Store of each included file for a shader (The can be looked up using effect.key)
  1202. */
  1203. Effect.IncludesShadersStore = {};
  1204. return Effect;
  1205. }());
  1206. BABYLON.Effect = Effect;
  1207. })(BABYLON || (BABYLON = {}));
  1208. //# sourceMappingURL=babylon.effect.js.map
  1209. //# sourceMappingURL=babylon.types.js.map
  1210. var BABYLON;
  1211. (function (BABYLON) {
  1212. var KeyboardEventTypes = /** @class */ (function () {
  1213. function KeyboardEventTypes() {
  1214. }
  1215. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1216. get: function () {
  1217. return KeyboardEventTypes._KEYDOWN;
  1218. },
  1219. enumerable: true,
  1220. configurable: true
  1221. });
  1222. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1223. get: function () {
  1224. return KeyboardEventTypes._KEYUP;
  1225. },
  1226. enumerable: true,
  1227. configurable: true
  1228. });
  1229. KeyboardEventTypes._KEYDOWN = 0x01;
  1230. KeyboardEventTypes._KEYUP = 0x02;
  1231. return KeyboardEventTypes;
  1232. }());
  1233. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1234. var KeyboardInfo = /** @class */ (function () {
  1235. function KeyboardInfo(type, event) {
  1236. this.type = type;
  1237. this.event = event;
  1238. }
  1239. return KeyboardInfo;
  1240. }());
  1241. BABYLON.KeyboardInfo = KeyboardInfo;
  1242. /**
  1243. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1244. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1245. */
  1246. var KeyboardInfoPre = /** @class */ (function (_super) {
  1247. __extends(KeyboardInfoPre, _super);
  1248. function KeyboardInfoPre(type, event) {
  1249. var _this = _super.call(this, type, event) || this;
  1250. _this.skipOnPointerObservable = false;
  1251. return _this;
  1252. }
  1253. return KeyboardInfoPre;
  1254. }(KeyboardInfo));
  1255. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1256. })(BABYLON || (BABYLON = {}));
  1257. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1258. var BABYLON;
  1259. (function (BABYLON) {
  1260. var PointerEventTypes = /** @class */ (function () {
  1261. function PointerEventTypes() {
  1262. }
  1263. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1264. get: function () {
  1265. return PointerEventTypes._POINTERDOWN;
  1266. },
  1267. enumerable: true,
  1268. configurable: true
  1269. });
  1270. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1271. get: function () {
  1272. return PointerEventTypes._POINTERUP;
  1273. },
  1274. enumerable: true,
  1275. configurable: true
  1276. });
  1277. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1278. get: function () {
  1279. return PointerEventTypes._POINTERMOVE;
  1280. },
  1281. enumerable: true,
  1282. configurable: true
  1283. });
  1284. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1285. get: function () {
  1286. return PointerEventTypes._POINTERWHEEL;
  1287. },
  1288. enumerable: true,
  1289. configurable: true
  1290. });
  1291. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1292. get: function () {
  1293. return PointerEventTypes._POINTERPICK;
  1294. },
  1295. enumerable: true,
  1296. configurable: true
  1297. });
  1298. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1299. get: function () {
  1300. return PointerEventTypes._POINTERTAP;
  1301. },
  1302. enumerable: true,
  1303. configurable: true
  1304. });
  1305. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1306. get: function () {
  1307. return PointerEventTypes._POINTERDOUBLETAP;
  1308. },
  1309. enumerable: true,
  1310. configurable: true
  1311. });
  1312. PointerEventTypes._POINTERDOWN = 0x01;
  1313. PointerEventTypes._POINTERUP = 0x02;
  1314. PointerEventTypes._POINTERMOVE = 0x04;
  1315. PointerEventTypes._POINTERWHEEL = 0x08;
  1316. PointerEventTypes._POINTERPICK = 0x10;
  1317. PointerEventTypes._POINTERTAP = 0x20;
  1318. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1319. return PointerEventTypes;
  1320. }());
  1321. BABYLON.PointerEventTypes = PointerEventTypes;
  1322. var PointerInfoBase = /** @class */ (function () {
  1323. function PointerInfoBase(type, event) {
  1324. this.type = type;
  1325. this.event = event;
  1326. }
  1327. return PointerInfoBase;
  1328. }());
  1329. BABYLON.PointerInfoBase = PointerInfoBase;
  1330. /**
  1331. * This class is used to store pointer related info for the onPrePointerObservable event.
  1332. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1333. */
  1334. var PointerInfoPre = /** @class */ (function (_super) {
  1335. __extends(PointerInfoPre, _super);
  1336. function PointerInfoPre(type, event, localX, localY) {
  1337. var _this = _super.call(this, type, event) || this;
  1338. _this.skipOnPointerObservable = false;
  1339. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1340. return _this;
  1341. }
  1342. return PointerInfoPre;
  1343. }(PointerInfoBase));
  1344. BABYLON.PointerInfoPre = PointerInfoPre;
  1345. /**
  1346. * This type contains all the data related to a pointer event in Babylon.js.
  1347. * 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.
  1348. */
  1349. var PointerInfo = /** @class */ (function (_super) {
  1350. __extends(PointerInfo, _super);
  1351. function PointerInfo(type, event, pickInfo) {
  1352. var _this = _super.call(this, type, event) || this;
  1353. _this.pickInfo = pickInfo;
  1354. return _this;
  1355. }
  1356. return PointerInfo;
  1357. }(PointerInfoBase));
  1358. BABYLON.PointerInfo = PointerInfo;
  1359. })(BABYLON || (BABYLON = {}));
  1360. //# sourceMappingURL=babylon.pointerEvents.js.map
  1361. var BABYLON;
  1362. (function (BABYLON) {
  1363. BABYLON.ToGammaSpace = 1 / 2.2;
  1364. BABYLON.ToLinearSpace = 2.2;
  1365. BABYLON.Epsilon = 0.001;
  1366. /**
  1367. * Class used to hold a RBG color
  1368. */
  1369. var Color3 = /** @class */ (function () {
  1370. /**
  1371. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1372. * @param r defines the red component (between 0 and 1, default is 0)
  1373. * @param g defines the green component (between 0 and 1, default is 0)
  1374. * @param b defines the blue component (between 0 and 1, default is 0)
  1375. */
  1376. function Color3(
  1377. /**
  1378. * Defines the red component (between 0 and 1, default is 0)
  1379. */
  1380. r,
  1381. /**
  1382. * Defines the green component (between 0 and 1, default is 0)
  1383. */
  1384. g,
  1385. /**
  1386. * Defines the blue component (between 0 and 1, default is 0)
  1387. */
  1388. b) {
  1389. if (r === void 0) { r = 0; }
  1390. if (g === void 0) { g = 0; }
  1391. if (b === void 0) { b = 0; }
  1392. this.r = r;
  1393. this.g = g;
  1394. this.b = b;
  1395. }
  1396. /**
  1397. * Creates a string with the Color3 current values
  1398. * @returns the string representation of the Color3 object
  1399. */
  1400. Color3.prototype.toString = function () {
  1401. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1402. };
  1403. /**
  1404. * Returns the string "Color3"
  1405. * @returns "Color3"
  1406. */
  1407. Color3.prototype.getClassName = function () {
  1408. return "Color3";
  1409. };
  1410. /**
  1411. * Compute the Color3 hash code
  1412. * @returns an unique number that can be used to hash Color3 objects
  1413. */
  1414. Color3.prototype.getHashCode = function () {
  1415. var hash = this.r || 0;
  1416. hash = (hash * 397) ^ (this.g || 0);
  1417. hash = (hash * 397) ^ (this.b || 0);
  1418. return hash;
  1419. };
  1420. // Operators
  1421. /**
  1422. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1423. * @param array defines the array where to store the r,g,b components
  1424. * @param index defines an optional index in the target array to define where to start storing values
  1425. * @returns the current Color3 object
  1426. */
  1427. Color3.prototype.toArray = function (array, index) {
  1428. if (index === undefined) {
  1429. index = 0;
  1430. }
  1431. array[index] = this.r;
  1432. array[index + 1] = this.g;
  1433. array[index + 2] = this.b;
  1434. return this;
  1435. };
  1436. /**
  1437. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1438. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1439. * @returns a new {BABYLON.Color4} object
  1440. */
  1441. Color3.prototype.toColor4 = function (alpha) {
  1442. if (alpha === void 0) { alpha = 1; }
  1443. return new Color4(this.r, this.g, this.b, alpha);
  1444. };
  1445. /**
  1446. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1447. * @returns the new array
  1448. */
  1449. Color3.prototype.asArray = function () {
  1450. var result = new Array();
  1451. this.toArray(result, 0);
  1452. return result;
  1453. };
  1454. /**
  1455. * Returns the luminance value
  1456. * @returns a float value
  1457. */
  1458. Color3.prototype.toLuminance = function () {
  1459. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1460. };
  1461. /**
  1462. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1463. * @param otherColor defines the second operand
  1464. * @returns the new Color3 object
  1465. */
  1466. Color3.prototype.multiply = function (otherColor) {
  1467. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1468. };
  1469. /**
  1470. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1471. * @param otherColor defines the second operand
  1472. * @param result defines the Color3 object where to store the result
  1473. * @returns the current Color3
  1474. */
  1475. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1476. result.r = this.r * otherColor.r;
  1477. result.g = this.g * otherColor.g;
  1478. result.b = this.b * otherColor.b;
  1479. return this;
  1480. };
  1481. /**
  1482. * Determines equality between Color3 objects
  1483. * @param otherColor defines the second operand
  1484. * @returns true if the rgb values are equal to the given ones
  1485. */
  1486. Color3.prototype.equals = function (otherColor) {
  1487. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1488. };
  1489. /**
  1490. * Determines equality between the current Color3 object and a set of r,b,g values
  1491. * @param r defines the red component to check
  1492. * @param g defines the green component to check
  1493. * @param b defines the blue component to check
  1494. * @returns true if the rgb values are equal to the given ones
  1495. */
  1496. Color3.prototype.equalsFloats = function (r, g, b) {
  1497. return this.r === r && this.g === g && this.b === b;
  1498. };
  1499. /**
  1500. * Multiplies in place each rgb value by scale
  1501. * @param scale defines the scaling factor
  1502. * @returns the updated Color3
  1503. */
  1504. Color3.prototype.scale = function (scale) {
  1505. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1506. };
  1507. /**
  1508. * Multiplies the rgb values by scale and stores the result into "result"
  1509. * @param scale defines the scaling factor
  1510. * @param result defines the Color3 object where to store the result
  1511. * @returns the unmodified current Color3
  1512. */
  1513. Color3.prototype.scaleToRef = function (scale, result) {
  1514. result.r = this.r * scale;
  1515. result.g = this.g * scale;
  1516. result.b = this.b * scale;
  1517. return this;
  1518. };
  1519. /**
  1520. * Scale the current Color3 values by a factor and add the result to a given Color3
  1521. * @param scale defines the scale factor
  1522. * @param result defines color to store the result into
  1523. * @returns the unmodified current Color3
  1524. */
  1525. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1526. result.r += this.r * scale;
  1527. result.g += this.g * scale;
  1528. result.b += this.b * scale;
  1529. return this;
  1530. };
  1531. /**
  1532. * Clamps the rgb values by the min and max values and stores the result into "result"
  1533. * @param min defines minimum clamping value (default is 0)
  1534. * @param max defines maximum clamping value (default is 1)
  1535. * @param result defines color to store the result into
  1536. * @returns the original Color3
  1537. */
  1538. Color3.prototype.clampToRef = function (min, max, result) {
  1539. if (min === void 0) { min = 0; }
  1540. if (max === void 0) { max = 1; }
  1541. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1542. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1543. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1544. return this;
  1545. };
  1546. /**
  1547. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1548. * @param otherColor defines the second operand
  1549. * @returns the new Color3
  1550. */
  1551. Color3.prototype.add = function (otherColor) {
  1552. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1553. };
  1554. /**
  1555. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1556. * @param otherColor defines the second operand
  1557. * @param result defines Color3 object to store the result into
  1558. * @returns the unmodified current Color3
  1559. */
  1560. Color3.prototype.addToRef = function (otherColor, result) {
  1561. result.r = this.r + otherColor.r;
  1562. result.g = this.g + otherColor.g;
  1563. result.b = this.b + otherColor.b;
  1564. return this;
  1565. };
  1566. /**
  1567. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1568. * @param otherColor defines the second operand
  1569. * @returns the new Color3
  1570. */
  1571. Color3.prototype.subtract = function (otherColor) {
  1572. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1573. };
  1574. /**
  1575. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1576. * @param otherColor defines the second operand
  1577. * @param result defines Color3 object to store the result into
  1578. * @returns the unmodified current Color3
  1579. */
  1580. Color3.prototype.subtractToRef = function (otherColor, result) {
  1581. result.r = this.r - otherColor.r;
  1582. result.g = this.g - otherColor.g;
  1583. result.b = this.b - otherColor.b;
  1584. return this;
  1585. };
  1586. /**
  1587. * Copy the current object
  1588. * @returns a new Color3 copied the current one
  1589. */
  1590. Color3.prototype.clone = function () {
  1591. return new Color3(this.r, this.g, this.b);
  1592. };
  1593. /**
  1594. * Copies the rgb values from the source in the current Color3
  1595. * @param source defines the source Color3 object
  1596. * @returns the updated Color3 object
  1597. */
  1598. Color3.prototype.copyFrom = function (source) {
  1599. this.r = source.r;
  1600. this.g = source.g;
  1601. this.b = source.b;
  1602. return this;
  1603. };
  1604. /**
  1605. * Updates the Color3 rgb values from the given floats
  1606. * @param r defines the red component to read from
  1607. * @param g defines the green component to read from
  1608. * @param b defines the blue component to read from
  1609. * @returns the current Color3 object
  1610. */
  1611. Color3.prototype.copyFromFloats = function (r, g, b) {
  1612. this.r = r;
  1613. this.g = g;
  1614. this.b = b;
  1615. return this;
  1616. };
  1617. /**
  1618. * Updates the Color3 rgb values from the given floats
  1619. * @param r defines the red component to read from
  1620. * @param g defines the green component to read from
  1621. * @param b defines the blue component to read from
  1622. * @returns the current Color3 object
  1623. */
  1624. Color3.prototype.set = function (r, g, b) {
  1625. return this.copyFromFloats(r, g, b);
  1626. };
  1627. /**
  1628. * Compute the Color3 hexadecimal code as a string
  1629. * @returns a string containing the hexadecimal representation of the Color3 object
  1630. */
  1631. Color3.prototype.toHexString = function () {
  1632. var intR = (this.r * 255) | 0;
  1633. var intG = (this.g * 255) | 0;
  1634. var intB = (this.b * 255) | 0;
  1635. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1636. };
  1637. /**
  1638. * Computes a new Color3 converted from the current one to linear space
  1639. * @returns a new Color3 object
  1640. */
  1641. Color3.prototype.toLinearSpace = function () {
  1642. var convertedColor = new Color3();
  1643. this.toLinearSpaceToRef(convertedColor);
  1644. return convertedColor;
  1645. };
  1646. /**
  1647. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1648. * @param convertedColor defines the Color3 object where to store the linear space version
  1649. * @returns the unmodified Color3
  1650. */
  1651. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1652. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1653. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1654. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1655. return this;
  1656. };
  1657. /**
  1658. * Computes a new Color3 converted from the current one to gamma space
  1659. * @returns a new Color3 object
  1660. */
  1661. Color3.prototype.toGammaSpace = function () {
  1662. var convertedColor = new Color3();
  1663. this.toGammaSpaceToRef(convertedColor);
  1664. return convertedColor;
  1665. };
  1666. /**
  1667. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1668. * @param convertedColor defines the Color3 object where to store the gamma space version
  1669. * @returns the unmodified Color3
  1670. */
  1671. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1672. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1673. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1674. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1675. return this;
  1676. };
  1677. // Statics
  1678. /**
  1679. * Creates a new Color3 from the string containing valid hexadecimal values
  1680. * @param hex defines a string containing valid hexadecimal values
  1681. * @returns a new Color3 object
  1682. */
  1683. Color3.FromHexString = function (hex) {
  1684. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1685. return new Color3(0, 0, 0);
  1686. }
  1687. var r = parseInt(hex.substring(1, 3), 16);
  1688. var g = parseInt(hex.substring(3, 5), 16);
  1689. var b = parseInt(hex.substring(5, 7), 16);
  1690. return Color3.FromInts(r, g, b);
  1691. };
  1692. /**
  1693. * Creates a new Vector3 from the starting index of the given array
  1694. * @param array defines the source array
  1695. * @param offset defines an offset in the source array
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.FromArray = function (array, offset) {
  1699. if (offset === void 0) { offset = 0; }
  1700. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1701. };
  1702. /**
  1703. * Creates a new Color3 from integer values (< 256)
  1704. * @param r defines the red component to read from (value between 0 and 255)
  1705. * @param g defines the green component to read from (value between 0 and 255)
  1706. * @param b defines the blue component to read from (value between 0 and 255)
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.FromInts = function (r, g, b) {
  1710. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1711. };
  1712. /**
  1713. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1714. * @param start defines the start Color3 value
  1715. * @param end defines the end Color3 value
  1716. * @param amount defines the gradient value between start and end
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Lerp = function (start, end, amount) {
  1720. var r = start.r + ((end.r - start.r) * amount);
  1721. var g = start.g + ((end.g - start.g) * amount);
  1722. var b = start.b + ((end.b - start.b) * amount);
  1723. return new Color3(r, g, b);
  1724. };
  1725. /**
  1726. * Returns a Color3 value containing a red color
  1727. * @returns a new Color3 object
  1728. */
  1729. Color3.Red = function () { return new Color3(1, 0, 0); };
  1730. /**
  1731. * Returns a Color3 value containing a green color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Green = function () { return new Color3(0, 1, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a blue color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1740. /**
  1741. * Returns a Color3 value containing a black color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Black = function () { return new Color3(0, 0, 0); };
  1745. /**
  1746. * Returns a Color3 value containing a white color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.White = function () { return new Color3(1, 1, 1); };
  1750. /**
  1751. * Returns a Color3 value containing a purple color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1755. /**
  1756. * Returns a Color3 value containing a magenta color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1760. /**
  1761. * Returns a Color3 value containing a yellow color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a gray color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1770. /**
  1771. * Returns a Color3 value containing a teal color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1775. /**
  1776. * Returns a Color3 value containing a random color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1780. return Color3;
  1781. }());
  1782. BABYLON.Color3 = Color3;
  1783. /**
  1784. * Class used to hold a RBGA color
  1785. */
  1786. var Color4 = /** @class */ (function () {
  1787. /**
  1788. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1789. * @param r defines the red component (between 0 and 1, default is 0)
  1790. * @param g defines the green component (between 0 and 1, default is 0)
  1791. * @param b defines the blue component (between 0 and 1, default is 0)
  1792. * @param a defines the alpha component (between 0 and 1, default is 1)
  1793. */
  1794. function Color4(
  1795. /**
  1796. * Defines the red component (between 0 and 1, default is 0)
  1797. */
  1798. r,
  1799. /**
  1800. * Defines the green component (between 0 and 1, default is 0)
  1801. */
  1802. g,
  1803. /**
  1804. * Defines the blue component (between 0 and 1, default is 0)
  1805. */
  1806. b,
  1807. /**
  1808. * Defines the alpha component (between 0 and 1, default is 1)
  1809. */
  1810. a) {
  1811. if (r === void 0) { r = 0; }
  1812. if (g === void 0) { g = 0; }
  1813. if (b === void 0) { b = 0; }
  1814. if (a === void 0) { a = 1; }
  1815. this.r = r;
  1816. this.g = g;
  1817. this.b = b;
  1818. this.a = a;
  1819. }
  1820. // Operators
  1821. /**
  1822. * Adds in place the given Color4 values to the current Color4 object
  1823. * @param right defines the second operand
  1824. * @returns the current updated Color4 object
  1825. */
  1826. Color4.prototype.addInPlace = function (right) {
  1827. this.r += right.r;
  1828. this.g += right.g;
  1829. this.b += right.b;
  1830. this.a += right.a;
  1831. return this;
  1832. };
  1833. /**
  1834. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1835. * @returns the new array
  1836. */
  1837. Color4.prototype.asArray = function () {
  1838. var result = new Array();
  1839. this.toArray(result, 0);
  1840. return result;
  1841. };
  1842. /**
  1843. * Stores from the starting index in the given array the Color4 successive values
  1844. * @param array defines the array where to store the r,g,b components
  1845. * @param index defines an optional index in the target array to define where to start storing values
  1846. * @returns the current Color4 object
  1847. */
  1848. Color4.prototype.toArray = function (array, index) {
  1849. if (index === undefined) {
  1850. index = 0;
  1851. }
  1852. array[index] = this.r;
  1853. array[index + 1] = this.g;
  1854. array[index + 2] = this.b;
  1855. array[index + 3] = this.a;
  1856. return this;
  1857. };
  1858. /**
  1859. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1860. * @param right defines the second operand
  1861. * @returns a new Color4 object
  1862. */
  1863. Color4.prototype.add = function (right) {
  1864. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1865. };
  1866. /**
  1867. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1868. * @param right defines the second operand
  1869. * @returns a new Color4 object
  1870. */
  1871. Color4.prototype.subtract = function (right) {
  1872. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1873. };
  1874. /**
  1875. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1876. * @param right defines the second operand
  1877. * @param result defines the Color4 object where to store the result
  1878. * @returns the current Color4 object
  1879. */
  1880. Color4.prototype.subtractToRef = function (right, result) {
  1881. result.r = this.r - right.r;
  1882. result.g = this.g - right.g;
  1883. result.b = this.b - right.b;
  1884. result.a = this.a - right.a;
  1885. return this;
  1886. };
  1887. /**
  1888. * Creates a new Color4 with the current Color4 values multiplied by scale
  1889. * @param scale defines the scaling factor to apply
  1890. * @returns a new Color4 object
  1891. */
  1892. Color4.prototype.scale = function (scale) {
  1893. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1894. };
  1895. /**
  1896. * Multiplies the current Color4 values by scale and stores the result in "result"
  1897. * @param scale defines the scaling factor to apply
  1898. * @param result defines the Color4 object where to store the result
  1899. * @returns the current unmodified Color4
  1900. */
  1901. Color4.prototype.scaleToRef = function (scale, result) {
  1902. result.r = this.r * scale;
  1903. result.g = this.g * scale;
  1904. result.b = this.b * scale;
  1905. result.a = this.a * scale;
  1906. return this;
  1907. };
  1908. /**
  1909. * Scale the current Color4 values by a factor and add the result to a given Color4
  1910. * @param scale defines the scale factor
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the unmodified current Color4
  1913. */
  1914. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1915. result.r += this.r * scale;
  1916. result.g += this.g * scale;
  1917. result.b += this.b * scale;
  1918. result.a += this.a * scale;
  1919. return this;
  1920. };
  1921. /**
  1922. * Clamps the rgb values by the min and max values and stores the result into "result"
  1923. * @param min defines minimum clamping value (default is 0)
  1924. * @param max defines maximum clamping value (default is 1)
  1925. * @param result defines color to store the result into.
  1926. * @returns the cuurent Color4
  1927. */
  1928. Color4.prototype.clampToRef = function (min, max, result) {
  1929. if (min === void 0) { min = 0; }
  1930. if (max === void 0) { max = 1; }
  1931. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1932. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1933. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1934. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1935. return this;
  1936. };
  1937. /**
  1938. * Multipy an Color4 value by another and return a new Color4 object
  1939. * @param color defines the Color4 value to multiply by
  1940. * @returns a new Color4 object
  1941. */
  1942. Color4.prototype.multiply = function (color) {
  1943. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1944. };
  1945. /**
  1946. * Multipy a Color4 value by another and push the result in a reference value
  1947. * @param color defines the Color4 value to multiply by
  1948. * @param result defines the Color4 to fill the result in
  1949. * @returns the result Color4
  1950. */
  1951. Color4.prototype.multiplyToRef = function (color, result) {
  1952. result.r = this.r * color.r;
  1953. result.g = this.g * color.g;
  1954. result.b = this.b * color.b;
  1955. result.a = this.a * color.a;
  1956. return result;
  1957. };
  1958. /**
  1959. * Creates a string with the Color4 current values
  1960. * @returns the string representation of the Color4 object
  1961. */
  1962. Color4.prototype.toString = function () {
  1963. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1964. };
  1965. /**
  1966. * Returns the string "Color4"
  1967. * @returns "Color4"
  1968. */
  1969. Color4.prototype.getClassName = function () {
  1970. return "Color4";
  1971. };
  1972. /**
  1973. * Compute the Color4 hash code
  1974. * @returns an unique number that can be used to hash Color4 objects
  1975. */
  1976. Color4.prototype.getHashCode = function () {
  1977. var hash = this.r || 0;
  1978. hash = (hash * 397) ^ (this.g || 0);
  1979. hash = (hash * 397) ^ (this.b || 0);
  1980. hash = (hash * 397) ^ (this.a || 0);
  1981. return hash;
  1982. };
  1983. /**
  1984. * Creates a new Color4 copied from the current one
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.clone = function () {
  1988. return new Color4(this.r, this.g, this.b, this.a);
  1989. };
  1990. /**
  1991. * Copies the given Color4 values into the current one
  1992. * @param source defines the source Color4 object
  1993. * @returns the current updated Color4 object
  1994. */
  1995. Color4.prototype.copyFrom = function (source) {
  1996. this.r = source.r;
  1997. this.g = source.g;
  1998. this.b = source.b;
  1999. this.a = source.a;
  2000. return this;
  2001. };
  2002. /**
  2003. * Copies the given float values into the current one
  2004. * @param r defines the red component to read from
  2005. * @param g defines the green component to read from
  2006. * @param b defines the blue component to read from
  2007. * @param a defines the alpha component to read from
  2008. * @returns the current updated Color4 object
  2009. */
  2010. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2011. this.r = r;
  2012. this.g = g;
  2013. this.b = b;
  2014. this.a = a;
  2015. return this;
  2016. };
  2017. /**
  2018. * Copies the given float values into the current one
  2019. * @param r defines the red component to read from
  2020. * @param g defines the green component to read from
  2021. * @param b defines the blue component to read from
  2022. * @param a defines the alpha component to read from
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.set = function (r, g, b, a) {
  2026. return this.copyFromFloats(r, g, b, a);
  2027. };
  2028. /**
  2029. * Compute the Color4 hexadecimal code as a string
  2030. * @returns a string containing the hexadecimal representation of the Color4 object
  2031. */
  2032. Color4.prototype.toHexString = function () {
  2033. var intR = (this.r * 255) | 0;
  2034. var intG = (this.g * 255) | 0;
  2035. var intB = (this.b * 255) | 0;
  2036. var intA = (this.a * 255) | 0;
  2037. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2038. };
  2039. /**
  2040. * Computes a new Color4 converted from the current one to linear space
  2041. * @returns a new Color4 object
  2042. */
  2043. Color4.prototype.toLinearSpace = function () {
  2044. var convertedColor = new Color4();
  2045. this.toLinearSpaceToRef(convertedColor);
  2046. return convertedColor;
  2047. };
  2048. /**
  2049. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2050. * @param convertedColor defines the Color4 object where to store the linear space version
  2051. * @returns the unmodified Color4
  2052. */
  2053. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2054. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2055. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2056. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2057. convertedColor.a = this.a;
  2058. return this;
  2059. };
  2060. /**
  2061. * Computes a new Color4 converted from the current one to gamma space
  2062. * @returns a new Color4 object
  2063. */
  2064. Color4.prototype.toGammaSpace = function () {
  2065. var convertedColor = new Color4();
  2066. this.toGammaSpaceToRef(convertedColor);
  2067. return convertedColor;
  2068. };
  2069. /**
  2070. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2071. * @param convertedColor defines the Color4 object where to store the gamma space version
  2072. * @returns the unmodified Color4
  2073. */
  2074. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2075. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2076. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2077. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2078. convertedColor.a = this.a;
  2079. return this;
  2080. };
  2081. // Statics
  2082. /**
  2083. * Creates a new Color4 from the string containing valid hexadecimal values
  2084. * @param hex defines a string containing valid hexadecimal values
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.FromHexString = function (hex) {
  2088. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2089. return new Color4(0.0, 0.0, 0.0, 0.0);
  2090. }
  2091. var r = parseInt(hex.substring(1, 3), 16);
  2092. var g = parseInt(hex.substring(3, 5), 16);
  2093. var b = parseInt(hex.substring(5, 7), 16);
  2094. var a = parseInt(hex.substring(7, 9), 16);
  2095. return Color4.FromInts(r, g, b, a);
  2096. };
  2097. /**
  2098. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2099. * @param left defines the start value
  2100. * @param right defines the end value
  2101. * @param amount defines the gradient factor
  2102. * @returns a new Color4 object
  2103. */
  2104. Color4.Lerp = function (left, right, amount) {
  2105. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2106. Color4.LerpToRef(left, right, amount, result);
  2107. return result;
  2108. };
  2109. /**
  2110. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2111. * @param left defines the start value
  2112. * @param right defines the end value
  2113. * @param amount defines the gradient factor
  2114. * @param result defines the Color4 object where to store data
  2115. */
  2116. Color4.LerpToRef = function (left, right, amount, result) {
  2117. result.r = left.r + (right.r - left.r) * amount;
  2118. result.g = left.g + (right.g - left.g) * amount;
  2119. result.b = left.b + (right.b - left.b) * amount;
  2120. result.a = left.a + (right.a - left.a) * amount;
  2121. };
  2122. /**
  2123. * Creates a new Color4 from the starting index element of the given array
  2124. * @param array defines the source array to read from
  2125. * @param offset defines the offset in the source array
  2126. * @returns a new Color4 object
  2127. */
  2128. Color4.FromArray = function (array, offset) {
  2129. if (offset === void 0) { offset = 0; }
  2130. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2131. };
  2132. /**
  2133. * Creates a new Color3 from integer values (< 256)
  2134. * @param r defines the red component to read from (value between 0 and 255)
  2135. * @param g defines the green component to read from (value between 0 and 255)
  2136. * @param b defines the blue component to read from (value between 0 and 255)
  2137. * @param a defines the alpha component to read from (value between 0 and 255)
  2138. * @returns a new Color3 object
  2139. */
  2140. Color4.FromInts = function (r, g, b, a) {
  2141. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2142. };
  2143. /**
  2144. * Check the content of a given array and convert it to an array containing RGBA data
  2145. * If the original array was already containing count * 4 values then it is returned directly
  2146. * @param colors defines the array to check
  2147. * @param count defines the number of RGBA data to expect
  2148. * @returns an array containing count * 4 values (RGBA)
  2149. */
  2150. Color4.CheckColors4 = function (colors, count) {
  2151. // Check if color3 was used
  2152. if (colors.length === count * 3) {
  2153. var colors4 = [];
  2154. for (var index = 0; index < colors.length; index += 3) {
  2155. var newIndex = (index / 3) * 4;
  2156. colors4[newIndex] = colors[index];
  2157. colors4[newIndex + 1] = colors[index + 1];
  2158. colors4[newIndex + 2] = colors[index + 2];
  2159. colors4[newIndex + 3] = 1.0;
  2160. }
  2161. return colors4;
  2162. }
  2163. return colors;
  2164. };
  2165. return Color4;
  2166. }());
  2167. BABYLON.Color4 = Color4;
  2168. /**
  2169. * Class representing a vector containing 2 coordinates
  2170. */
  2171. var Vector2 = /** @class */ (function () {
  2172. /**
  2173. * Creates a new Vector2 from the given x and y coordinates
  2174. * @param x defines the first coordinate
  2175. * @param y defines the second coordinate
  2176. */
  2177. function Vector2(
  2178. /** defines the first coordinate */
  2179. x,
  2180. /** defines the second coordinate */
  2181. y) {
  2182. this.x = x;
  2183. this.y = y;
  2184. }
  2185. /**
  2186. * Gets a string with the Vector2 coordinates
  2187. * @returns a string with the Vector2 coordinates
  2188. */
  2189. Vector2.prototype.toString = function () {
  2190. return "{X: " + this.x + " Y:" + this.y + "}";
  2191. };
  2192. /**
  2193. * Gets class name
  2194. * @returns the string "Vector2"
  2195. */
  2196. Vector2.prototype.getClassName = function () {
  2197. return "Vector2";
  2198. };
  2199. /**
  2200. * Gets current vector hash code
  2201. * @returns the Vector2 hash code as a number
  2202. */
  2203. Vector2.prototype.getHashCode = function () {
  2204. var hash = this.x || 0;
  2205. hash = (hash * 397) ^ (this.y || 0);
  2206. return hash;
  2207. };
  2208. // Operators
  2209. /**
  2210. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2211. * @param array defines the source array
  2212. * @param index defines the offset in source array
  2213. * @returns the current Vector2
  2214. */
  2215. Vector2.prototype.toArray = function (array, index) {
  2216. if (index === void 0) { index = 0; }
  2217. array[index] = this.x;
  2218. array[index + 1] = this.y;
  2219. return this;
  2220. };
  2221. /**
  2222. * Copy the current vector to an array
  2223. * @returns a new array with 2 elements: the Vector2 coordinates.
  2224. */
  2225. Vector2.prototype.asArray = function () {
  2226. var result = new Array();
  2227. this.toArray(result, 0);
  2228. return result;
  2229. };
  2230. /**
  2231. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2232. * @param source defines the source Vector2
  2233. * @returns the current updated Vector2
  2234. */
  2235. Vector2.prototype.copyFrom = function (source) {
  2236. this.x = source.x;
  2237. this.y = source.y;
  2238. return this;
  2239. };
  2240. /**
  2241. * Sets the Vector2 coordinates with the given floats
  2242. * @param x defines the first coordinate
  2243. * @param y defines the second coordinate
  2244. * @returns the current updated Vector2
  2245. */
  2246. Vector2.prototype.copyFromFloats = function (x, y) {
  2247. this.x = x;
  2248. this.y = y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Sets the Vector2 coordinates with the given floats
  2253. * @param x defines the first coordinate
  2254. * @param y defines the second coordinate
  2255. * @returns the current updated Vector2
  2256. */
  2257. Vector2.prototype.set = function (x, y) {
  2258. return this.copyFromFloats(x, y);
  2259. };
  2260. /**
  2261. * Add another vector with the current one
  2262. * @param otherVector defines the other vector
  2263. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2264. */
  2265. Vector2.prototype.add = function (otherVector) {
  2266. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2267. };
  2268. /**
  2269. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2270. * @param otherVector defines the other vector
  2271. * @param result defines the target vector
  2272. * @returns the unmodified current Vector2
  2273. */
  2274. Vector2.prototype.addToRef = function (otherVector, result) {
  2275. result.x = this.x + otherVector.x;
  2276. result.y = this.y + otherVector.y;
  2277. return this;
  2278. };
  2279. /**
  2280. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2281. * @param otherVector defines the other vector
  2282. * @returns the current updated Vector2
  2283. */
  2284. Vector2.prototype.addInPlace = function (otherVector) {
  2285. this.x += otherVector.x;
  2286. this.y += otherVector.y;
  2287. return this;
  2288. };
  2289. /**
  2290. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2291. * @param otherVector defines the other vector
  2292. * @returns a new Vector2
  2293. */
  2294. Vector2.prototype.addVector3 = function (otherVector) {
  2295. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2296. };
  2297. /**
  2298. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2299. * @param otherVector defines the other vector
  2300. * @returns a new Vector2
  2301. */
  2302. Vector2.prototype.subtract = function (otherVector) {
  2303. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2304. };
  2305. /**
  2306. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2307. * @param otherVector defines the other vector
  2308. * @param result defines the target vector
  2309. * @returns the unmodified current Vector2
  2310. */
  2311. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2312. result.x = this.x - otherVector.x;
  2313. result.y = this.y - otherVector.y;
  2314. return this;
  2315. };
  2316. /**
  2317. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2318. * @param otherVector defines the other vector
  2319. * @returns the current updated Vector2
  2320. */
  2321. Vector2.prototype.subtractInPlace = function (otherVector) {
  2322. this.x -= otherVector.x;
  2323. this.y -= otherVector.y;
  2324. return this;
  2325. };
  2326. /**
  2327. * Multiplies in place the current Vector2 coordinates by the given ones
  2328. * @param otherVector defines the other vector
  2329. * @returns the current updated Vector2
  2330. */
  2331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2332. this.x *= otherVector.x;
  2333. this.y *= otherVector.y;
  2334. return this;
  2335. };
  2336. /**
  2337. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2338. * @param otherVector defines the other vector
  2339. * @returns a new Vector2
  2340. */
  2341. Vector2.prototype.multiply = function (otherVector) {
  2342. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2343. };
  2344. /**
  2345. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2346. * @param otherVector defines the other vector
  2347. * @param result defines the target vector
  2348. * @returns the unmodified current Vector2
  2349. */
  2350. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2351. result.x = this.x * otherVector.x;
  2352. result.y = this.y * otherVector.y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2357. * @param x defines the first coordinate
  2358. * @param y defines the second coordinate
  2359. * @returns a new Vector2
  2360. */
  2361. Vector2.prototype.multiplyByFloats = function (x, y) {
  2362. return new Vector2(this.x * x, this.y * y);
  2363. };
  2364. /**
  2365. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2366. * @param otherVector defines the other vector
  2367. * @returns a new Vector2
  2368. */
  2369. Vector2.prototype.divide = function (otherVector) {
  2370. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @param result defines the target vector
  2376. * @returns the unmodified current Vector2
  2377. */
  2378. Vector2.prototype.divideToRef = function (otherVector, result) {
  2379. result.x = this.x / otherVector.x;
  2380. result.y = this.y / otherVector.y;
  2381. return this;
  2382. };
  2383. /**
  2384. * Divides the current Vector3 coordinates by the given ones
  2385. * @param otherVector defines the other vector
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.divideInPlace = function (otherVector) {
  2389. return this.divideToRef(otherVector, this);
  2390. };
  2391. /**
  2392. * Gets a new Vector2 with current Vector2 negated coordinates
  2393. * @returns a new Vector2
  2394. */
  2395. Vector2.prototype.negate = function () {
  2396. return new Vector2(-this.x, -this.y);
  2397. };
  2398. /**
  2399. * Multiply the Vector2 coordinates by scale
  2400. * @param scale defines the scaling factor
  2401. * @returns the current updated Vector2
  2402. */
  2403. Vector2.prototype.scaleInPlace = function (scale) {
  2404. this.x *= scale;
  2405. this.y *= scale;
  2406. return this;
  2407. };
  2408. /**
  2409. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2410. * @param scale defines the scaling factor
  2411. * @returns a new Vector2
  2412. */
  2413. Vector2.prototype.scale = function (scale) {
  2414. var result = new Vector2(0, 0);
  2415. this.scaleToRef(scale, result);
  2416. return result;
  2417. };
  2418. /**
  2419. * Scale the current Vector2 values by a factor to a given Vector2
  2420. * @param scale defines the scale factor
  2421. * @param result defines the Vector2 object where to store the result
  2422. * @returns the unmodified current Vector2
  2423. */
  2424. Vector2.prototype.scaleToRef = function (scale, result) {
  2425. result.x = this.x * scale;
  2426. result.y = this.y * scale;
  2427. return this;
  2428. };
  2429. /**
  2430. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2431. * @param scale defines the scale factor
  2432. * @param result defines the Vector2 object where to store the result
  2433. * @returns the unmodified current Vector2
  2434. */
  2435. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2436. result.x += this.x * scale;
  2437. result.y += this.y * scale;
  2438. return this;
  2439. };
  2440. /**
  2441. * Gets a boolean if two vectors are equals
  2442. * @param otherVector defines the other vector
  2443. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2444. */
  2445. Vector2.prototype.equals = function (otherVector) {
  2446. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2447. };
  2448. /**
  2449. * Gets a boolean if two vectors are equals (using an epsilon value)
  2450. * @param otherVector defines the other vector
  2451. * @param epsilon defines the minimal distance to consider equality
  2452. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2453. */
  2454. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2455. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2456. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2457. };
  2458. // Properties
  2459. /**
  2460. * Gets the length of the vector
  2461. * @returns the vector length (float)
  2462. */
  2463. Vector2.prototype.length = function () {
  2464. return Math.sqrt(this.x * this.x + this.y * this.y);
  2465. };
  2466. /**
  2467. * Gets the vector squared length
  2468. * @returns the vector squared length (float)
  2469. */
  2470. Vector2.prototype.lengthSquared = function () {
  2471. return (this.x * this.x + this.y * this.y);
  2472. };
  2473. // Methods
  2474. /**
  2475. * Normalize the vector
  2476. * @returns the current updated Vector2
  2477. */
  2478. Vector2.prototype.normalize = function () {
  2479. var len = this.length();
  2480. if (len === 0)
  2481. return this;
  2482. var num = 1.0 / len;
  2483. this.x *= num;
  2484. this.y *= num;
  2485. return this;
  2486. };
  2487. /**
  2488. * Gets a new Vector2 copied from the Vector2
  2489. * @returns a new Vector2
  2490. */
  2491. Vector2.prototype.clone = function () {
  2492. return new Vector2(this.x, this.y);
  2493. };
  2494. // Statics
  2495. /**
  2496. * Gets a new Vector2(0, 0)
  2497. * @returns a new Vector2
  2498. */
  2499. Vector2.Zero = function () {
  2500. return new Vector2(0, 0);
  2501. };
  2502. /**
  2503. * Gets a new Vector2(1, 1)
  2504. * @returns a new Vector2
  2505. */
  2506. Vector2.One = function () {
  2507. return new Vector2(1, 1);
  2508. };
  2509. /**
  2510. * Gets a new Vector2 set from the given index element of the given array
  2511. * @param array defines the data source
  2512. * @param offset defines the offset in the data source
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.FromArray = function (array, offset) {
  2516. if (offset === void 0) { offset = 0; }
  2517. return new Vector2(array[offset], array[offset + 1]);
  2518. };
  2519. /**
  2520. * Sets "result" from the given index element of the given array
  2521. * @param array defines the data source
  2522. * @param offset defines the offset in the data source
  2523. * @param result defines the target vector
  2524. */
  2525. Vector2.FromArrayToRef = function (array, offset, result) {
  2526. result.x = array[offset];
  2527. result.y = array[offset + 1];
  2528. };
  2529. /**
  2530. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2531. * @param value1 defines 1st point of control
  2532. * @param value2 defines 2nd point of control
  2533. * @param value3 defines 3rd point of control
  2534. * @param value4 defines 4th point of control
  2535. * @param amount defines the interpolation factor
  2536. * @returns a new Vector2
  2537. */
  2538. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2539. var squared = amount * amount;
  2540. var cubed = amount * squared;
  2541. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2542. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2543. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2544. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2545. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2546. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * 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".
  2551. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2552. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2553. * @param value defines the value to clamp
  2554. * @param min defines the lower limit
  2555. * @param max defines the upper limit
  2556. * @returns a new Vector2
  2557. */
  2558. Vector2.Clamp = function (value, min, max) {
  2559. var x = value.x;
  2560. x = (x > max.x) ? max.x : x;
  2561. x = (x < min.x) ? min.x : x;
  2562. var y = value.y;
  2563. y = (y > max.y) ? max.y : y;
  2564. y = (y < min.y) ? min.y : y;
  2565. return new Vector2(x, y);
  2566. };
  2567. /**
  2568. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2569. * @param value1 defines the 1st control point
  2570. * @param tangent1 defines the outgoing tangent
  2571. * @param value2 defines the 2nd control point
  2572. * @param tangent2 defines the incoming tangent
  2573. * @param amount defines the interpolation factor
  2574. * @returns a new Vector2
  2575. */
  2576. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2577. var squared = amount * amount;
  2578. var cubed = amount * squared;
  2579. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2580. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2581. var part3 = (cubed - (2.0 * squared)) + amount;
  2582. var part4 = cubed - squared;
  2583. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2584. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2585. return new Vector2(x, y);
  2586. };
  2587. /**
  2588. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2589. * @param start defines the start vector
  2590. * @param end defines the end vector
  2591. * @param amount defines the interpolation factor
  2592. * @returns a new Vector2
  2593. */
  2594. Vector2.Lerp = function (start, end, amount) {
  2595. var x = start.x + ((end.x - start.x) * amount);
  2596. var y = start.y + ((end.y - start.y) * amount);
  2597. return new Vector2(x, y);
  2598. };
  2599. /**
  2600. * Gets the dot product of the vector "left" and the vector "right"
  2601. * @param left defines first vector
  2602. * @param right defines second vector
  2603. * @returns the dot product (float)
  2604. */
  2605. Vector2.Dot = function (left, right) {
  2606. return left.x * right.x + left.y * right.y;
  2607. };
  2608. /**
  2609. * Returns a new Vector2 equal to the normalized given vector
  2610. * @param vector defines the vector to normalize
  2611. * @returns a new Vector2
  2612. */
  2613. Vector2.Normalize = function (vector) {
  2614. var newVector = vector.clone();
  2615. newVector.normalize();
  2616. return newVector;
  2617. };
  2618. /**
  2619. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2620. * @param left defines 1st vector
  2621. * @param right defines 2nd vector
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.Minimize = function (left, right) {
  2625. var x = (left.x < right.x) ? left.x : right.x;
  2626. var y = (left.y < right.y) ? left.y : right.y;
  2627. return new Vector2(x, y);
  2628. };
  2629. /**
  2630. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2631. * @param left defines 1st vector
  2632. * @param right defines 2nd vector
  2633. * @returns a new Vector2
  2634. */
  2635. Vector2.Maximize = function (left, right) {
  2636. var x = (left.x > right.x) ? left.x : right.x;
  2637. var y = (left.y > right.y) ? left.y : right.y;
  2638. return new Vector2(x, y);
  2639. };
  2640. /**
  2641. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2642. * @param vector defines the vector to transform
  2643. * @param transformation defines the matrix to apply
  2644. * @returns a new Vector2
  2645. */
  2646. Vector2.Transform = function (vector, transformation) {
  2647. var r = Vector2.Zero();
  2648. Vector2.TransformToRef(vector, transformation, r);
  2649. return r;
  2650. };
  2651. /**
  2652. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2653. * @param vector defines the vector to transform
  2654. * @param transformation defines the matrix to apply
  2655. * @param result defines the target vector
  2656. */
  2657. Vector2.TransformToRef = function (vector, transformation, result) {
  2658. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2659. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2660. result.x = x;
  2661. result.y = y;
  2662. };
  2663. /**
  2664. * Determines if a given vector is included in a triangle
  2665. * @param p defines the vector to test
  2666. * @param p0 defines 1st triangle point
  2667. * @param p1 defines 2nd triangle point
  2668. * @param p2 defines 3rd triangle point
  2669. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2670. */
  2671. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2672. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2673. var sign = a < 0 ? -1 : 1;
  2674. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2675. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2676. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2677. };
  2678. /**
  2679. * Gets the distance between the vectors "value1" and "value2"
  2680. * @param value1 defines first vector
  2681. * @param value2 defines second vector
  2682. * @returns the distance between vectors
  2683. */
  2684. Vector2.Distance = function (value1, value2) {
  2685. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2686. };
  2687. /**
  2688. * Returns the squared distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the squared distance between vectors
  2692. */
  2693. Vector2.DistanceSquared = function (value1, value2) {
  2694. var x = value1.x - value2.x;
  2695. var y = value1.y - value2.y;
  2696. return (x * x) + (y * y);
  2697. };
  2698. /**
  2699. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2700. * @param value1 defines first vector
  2701. * @param value2 defines second vector
  2702. * @returns a new Vector2
  2703. */
  2704. Vector2.Center = function (value1, value2) {
  2705. var center = value1.add(value2);
  2706. center.scaleInPlace(0.5);
  2707. return center;
  2708. };
  2709. /**
  2710. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2711. * @param p defines the middle point
  2712. * @param segA defines one point of the segment
  2713. * @param segB defines the other point of the segment
  2714. * @returns the shortest distance
  2715. */
  2716. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2717. var l2 = Vector2.DistanceSquared(segA, segB);
  2718. if (l2 === 0.0) {
  2719. return Vector2.Distance(p, segA);
  2720. }
  2721. var v = segB.subtract(segA);
  2722. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2723. var proj = segA.add(v.multiplyByFloats(t, t));
  2724. return Vector2.Distance(p, proj);
  2725. };
  2726. return Vector2;
  2727. }());
  2728. BABYLON.Vector2 = Vector2;
  2729. /**
  2730. * Classed used to store (x,y,z) vector representation
  2731. * A Vector3 is the main object used in 3D geometry
  2732. * It can represent etiher the coordinates of a point the space, either a direction
  2733. * Reminder: Babylon.js uses a left handed forward facing system
  2734. */
  2735. var Vector3 = /** @class */ (function () {
  2736. /**
  2737. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2738. * @param x defines the first coordinates (on X axis)
  2739. * @param y defines the second coordinates (on Y axis)
  2740. * @param z defines the third coordinates (on Z axis)
  2741. */
  2742. function Vector3(
  2743. /**
  2744. * Defines the first coordinates (on X axis)
  2745. */
  2746. x,
  2747. /**
  2748. * Defines the second coordinates (on Y axis)
  2749. */
  2750. y,
  2751. /**
  2752. * Defines the third coordinates (on Z axis)
  2753. */
  2754. z) {
  2755. this.x = x;
  2756. this.y = y;
  2757. this.z = z;
  2758. }
  2759. /**
  2760. * Creates a string representation of the Vector3
  2761. * @returns a string with the Vector3 coordinates.
  2762. */
  2763. Vector3.prototype.toString = function () {
  2764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2765. };
  2766. /**
  2767. * Gets the class name
  2768. * @returns the string "Vector3"
  2769. */
  2770. Vector3.prototype.getClassName = function () {
  2771. return "Vector3";
  2772. };
  2773. /**
  2774. * Creates the Vector3 hash code
  2775. * @returns a number which tends to be unique between Vector3 instances
  2776. */
  2777. Vector3.prototype.getHashCode = function () {
  2778. var hash = this.x || 0;
  2779. hash = (hash * 397) ^ (this.y || 0);
  2780. hash = (hash * 397) ^ (this.z || 0);
  2781. return hash;
  2782. };
  2783. // Operators
  2784. /**
  2785. * Creates an array containing three elements : the coordinates of the Vector3
  2786. * @returns a new array of numbers
  2787. */
  2788. Vector3.prototype.asArray = function () {
  2789. var result = [];
  2790. this.toArray(result, 0);
  2791. return result;
  2792. };
  2793. /**
  2794. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2795. * @param array defines the destination array
  2796. * @param index defines the offset in the destination array
  2797. * @returns the current Vector3
  2798. */
  2799. Vector3.prototype.toArray = function (array, index) {
  2800. if (index === void 0) { index = 0; }
  2801. array[index] = this.x;
  2802. array[index + 1] = this.y;
  2803. array[index + 2] = this.z;
  2804. return this;
  2805. };
  2806. /**
  2807. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2808. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2809. */
  2810. Vector3.prototype.toQuaternion = function () {
  2811. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2812. };
  2813. /**
  2814. * Adds the given vector to the current Vector3
  2815. * @param otherVector defines the second operand
  2816. * @returns the current updated Vector3
  2817. */
  2818. Vector3.prototype.addInPlace = function (otherVector) {
  2819. this.x += otherVector.x;
  2820. this.y += otherVector.y;
  2821. this.z += otherVector.z;
  2822. return this;
  2823. };
  2824. /**
  2825. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2826. * @param otherVector defines the second operand
  2827. * @returns the resulting Vector3
  2828. */
  2829. Vector3.prototype.add = function (otherVector) {
  2830. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2831. };
  2832. /**
  2833. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2834. * @param otherVector defines the second operand
  2835. * @param result defines the Vector3 object where to store the result
  2836. * @returns the current Vector3
  2837. */
  2838. Vector3.prototype.addToRef = function (otherVector, result) {
  2839. result.x = this.x + otherVector.x;
  2840. result.y = this.y + otherVector.y;
  2841. result.z = this.z + otherVector.z;
  2842. return this;
  2843. };
  2844. /**
  2845. * Subtract the given vector from the current Vector3
  2846. * @param otherVector defines the second operand
  2847. * @returns the current updated Vector3
  2848. */
  2849. Vector3.prototype.subtractInPlace = function (otherVector) {
  2850. this.x -= otherVector.x;
  2851. this.y -= otherVector.y;
  2852. this.z -= otherVector.z;
  2853. return this;
  2854. };
  2855. /**
  2856. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2857. * @param otherVector defines the second operand
  2858. * @returns the resulting Vector3
  2859. */
  2860. Vector3.prototype.subtract = function (otherVector) {
  2861. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2862. };
  2863. /**
  2864. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2865. * @param otherVector defines the second operand
  2866. * @param result defines the Vector3 object where to store the result
  2867. * @returns the current Vector3
  2868. */
  2869. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2870. result.x = this.x - otherVector.x;
  2871. result.y = this.y - otherVector.y;
  2872. result.z = this.z - otherVector.z;
  2873. return this;
  2874. };
  2875. /**
  2876. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2877. * @param x defines the x coordinate of the operand
  2878. * @param y defines the y coordinate of the operand
  2879. * @param z defines the z coordinate of the operand
  2880. * @returns the resulting Vector3
  2881. */
  2882. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2883. return new Vector3(this.x - x, this.y - y, this.z - z);
  2884. };
  2885. /**
  2886. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2887. * @param x defines the x coordinate of the operand
  2888. * @param y defines the y coordinate of the operand
  2889. * @param z defines the z coordinate of the operand
  2890. * @param result defines the Vector3 object where to store the result
  2891. * @returns the current Vector3
  2892. */
  2893. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2894. result.x = this.x - x;
  2895. result.y = this.y - y;
  2896. result.z = this.z - z;
  2897. return this;
  2898. };
  2899. /**
  2900. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2901. * @returns a new Vector3
  2902. */
  2903. Vector3.prototype.negate = function () {
  2904. return new Vector3(-this.x, -this.y, -this.z);
  2905. };
  2906. /**
  2907. * Multiplies the Vector3 coordinates by the float "scale"
  2908. * @param scale defines the multiplier factor
  2909. * @returns the current updated Vector3
  2910. */
  2911. Vector3.prototype.scaleInPlace = function (scale) {
  2912. this.x *= scale;
  2913. this.y *= scale;
  2914. this.z *= scale;
  2915. return this;
  2916. };
  2917. /**
  2918. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2919. * @param scale defines the multiplier factor
  2920. * @returns a new Vector3
  2921. */
  2922. Vector3.prototype.scale = function (scale) {
  2923. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2924. };
  2925. /**
  2926. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2927. * @param scale defines the multiplier factor
  2928. * @param result defines the Vector3 object where to store the result
  2929. * @returns the current Vector3
  2930. */
  2931. Vector3.prototype.scaleToRef = function (scale, result) {
  2932. result.x = this.x * scale;
  2933. result.y = this.y * scale;
  2934. result.z = this.z * scale;
  2935. return this;
  2936. };
  2937. /**
  2938. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2939. * @param scale defines the scale factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the unmodified current Vector3
  2942. */
  2943. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2944. result.x += this.x * scale;
  2945. result.y += this.y * scale;
  2946. result.z += this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2951. * @param otherVector defines the second operand
  2952. * @returns true if both vectors are equals
  2953. */
  2954. Vector3.prototype.equals = function (otherVector) {
  2955. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2956. };
  2957. /**
  2958. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2959. * @param otherVector defines the second operand
  2960. * @param epsilon defines the minimal distance to define values as equals
  2961. * @returns true if both vectors are distant less than epsilon
  2962. */
  2963. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2964. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2965. 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);
  2966. };
  2967. /**
  2968. * Returns true if the current Vector3 coordinates equals the given floats
  2969. * @param x defines the x coordinate of the operand
  2970. * @param y defines the y coordinate of the operand
  2971. * @param z defines the z coordinate of the operand
  2972. * @returns true if both vectors are equals
  2973. */
  2974. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2975. return this.x === x && this.y === y && this.z === z;
  2976. };
  2977. /**
  2978. * Multiplies the current Vector3 coordinates by the given ones
  2979. * @param otherVector defines the second operand
  2980. * @returns the current updated Vector3
  2981. */
  2982. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2983. this.x *= otherVector.x;
  2984. this.y *= otherVector.y;
  2985. this.z *= otherVector.z;
  2986. return this;
  2987. };
  2988. /**
  2989. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2990. * @param otherVector defines the second operand
  2991. * @returns the new Vector3
  2992. */
  2993. Vector3.prototype.multiply = function (otherVector) {
  2994. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2995. };
  2996. /**
  2997. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  2998. * @param otherVector defines the second operand
  2999. * @param result defines the Vector3 object where to store the result
  3000. * @returns the current Vector3
  3001. */
  3002. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3003. result.x = this.x * otherVector.x;
  3004. result.y = this.y * otherVector.y;
  3005. result.z = this.z * otherVector.z;
  3006. return this;
  3007. };
  3008. /**
  3009. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3010. * @param x defines the x coordinate of the operand
  3011. * @param y defines the y coordinate of the operand
  3012. * @param z defines the z coordinate of the operand
  3013. * @returns the new Vector3
  3014. */
  3015. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3016. return new Vector3(this.x * x, this.y * y, this.z * z);
  3017. };
  3018. /**
  3019. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3020. * @param otherVector defines the second operand
  3021. * @returns the new Vector3
  3022. */
  3023. Vector3.prototype.divide = function (otherVector) {
  3024. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3025. };
  3026. /**
  3027. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3028. * @param otherVector defines the second operand
  3029. * @param result defines the Vector3 object where to store the result
  3030. * @returns the current Vector3
  3031. */
  3032. Vector3.prototype.divideToRef = function (otherVector, result) {
  3033. result.x = this.x / otherVector.x;
  3034. result.y = this.y / otherVector.y;
  3035. result.z = this.z / otherVector.z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones.
  3040. * @param otherVector defines the second operand
  3041. * @returns the current updated Vector3
  3042. */
  3043. Vector3.prototype.divideInPlace = function (otherVector) {
  3044. return this.divideToRef(otherVector, this);
  3045. };
  3046. /**
  3047. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3048. * @param other defines the second operand
  3049. * @returns the current updated Vector3
  3050. */
  3051. Vector3.prototype.minimizeInPlace = function (other) {
  3052. if (other.x < this.x)
  3053. this.x = other.x;
  3054. if (other.y < this.y)
  3055. this.y = other.y;
  3056. if (other.z < this.z)
  3057. this.z = other.z;
  3058. return this;
  3059. };
  3060. /**
  3061. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3062. * @param other defines the second operand
  3063. * @returns the current updated Vector3
  3064. */
  3065. Vector3.prototype.maximizeInPlace = function (other) {
  3066. if (other.x > this.x)
  3067. this.x = other.x;
  3068. if (other.y > this.y)
  3069. this.y = other.y;
  3070. if (other.z > this.z)
  3071. this.z = other.z;
  3072. return this;
  3073. };
  3074. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3075. /**
  3076. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3077. */
  3078. get: function () {
  3079. var absX = Math.abs(this.x);
  3080. var absY = Math.abs(this.y);
  3081. if (absX !== absY) {
  3082. return true;
  3083. }
  3084. var absZ = Math.abs(this.z);
  3085. if (absX !== absZ) {
  3086. return true;
  3087. }
  3088. if (absY !== absZ) {
  3089. return true;
  3090. }
  3091. return false;
  3092. },
  3093. enumerable: true,
  3094. configurable: true
  3095. });
  3096. // Properties
  3097. /**
  3098. * Gets the length of the Vector3
  3099. * @returns the length of the Vecto3
  3100. */
  3101. Vector3.prototype.length = function () {
  3102. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3103. };
  3104. /**
  3105. * Gets the squared length of the Vector3
  3106. * @returns squared length of the Vector3
  3107. */
  3108. Vector3.prototype.lengthSquared = function () {
  3109. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3110. };
  3111. /**
  3112. * Normalize the current Vector3.
  3113. * Please note that this is an in place operation.
  3114. * @returns the current updated Vector3
  3115. */
  3116. Vector3.prototype.normalize = function () {
  3117. var len = this.length();
  3118. if (len === 0 || len === 1.0)
  3119. return this;
  3120. var num = 1.0 / len;
  3121. this.x *= num;
  3122. this.y *= num;
  3123. this.z *= num;
  3124. return this;
  3125. };
  3126. /**
  3127. * Normalize the current Vector3 to a new vector
  3128. * @returns the new Vector3
  3129. */
  3130. Vector3.prototype.normalizeToNew = function () {
  3131. var normalized = new Vector3(0, 0, 0);
  3132. this.normalizeToRef(normalized);
  3133. return normalized;
  3134. };
  3135. /**
  3136. * Normalize the current Vector3 to the reference
  3137. * @param reference define the Vector3 to update
  3138. * @returns the updated Vector3
  3139. */
  3140. Vector3.prototype.normalizeToRef = function (reference) {
  3141. var len = this.length();
  3142. if (len === 0 || len === 1.0) {
  3143. reference.set(this.x, this.y, this.z);
  3144. return reference;
  3145. }
  3146. var scale = 1.0 / len;
  3147. this.scaleToRef(scale, reference);
  3148. return reference;
  3149. };
  3150. /**
  3151. * Creates a new Vector3 copied from the current Vector3
  3152. * @returns the new Vector3
  3153. */
  3154. Vector3.prototype.clone = function () {
  3155. return new Vector3(this.x, this.y, this.z);
  3156. };
  3157. /**
  3158. * Copies the given vector coordinates to the current Vector3 ones
  3159. * @param source defines the source Vector3
  3160. * @returns the current updated Vector3
  3161. */
  3162. Vector3.prototype.copyFrom = function (source) {
  3163. this.x = source.x;
  3164. this.y = source.y;
  3165. this.z = source.z;
  3166. return this;
  3167. };
  3168. /**
  3169. * Copies the given floats to the current Vector3 coordinates
  3170. * @param x defines the x coordinate of the operand
  3171. * @param y defines the y coordinate of the operand
  3172. * @param z defines the z coordinate of the operand
  3173. * @returns the current updated Vector3
  3174. */
  3175. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3176. this.x = x;
  3177. this.y = y;
  3178. this.z = z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Copies the given floats to the current Vector3 coordinates
  3183. * @param x defines the x coordinate of the operand
  3184. * @param y defines the y coordinate of the operand
  3185. * @param z defines the z coordinate of the operand
  3186. * @returns the current updated Vector3
  3187. */
  3188. Vector3.prototype.set = function (x, y, z) {
  3189. return this.copyFromFloats(x, y, z);
  3190. };
  3191. // Statics
  3192. /**
  3193. * Get the clip factor between two vectors
  3194. * @param vector0 defines the first operand
  3195. * @param vector1 defines the second operand
  3196. * @param axis defines the axis to use
  3197. * @param size defines the size along the axis
  3198. * @returns the clip factor
  3199. */
  3200. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3201. var d0 = Vector3.Dot(vector0, axis) - size;
  3202. var d1 = Vector3.Dot(vector1, axis) - size;
  3203. var s = d0 / (d0 - d1);
  3204. return s;
  3205. };
  3206. /**
  3207. * Get angle between two vectors
  3208. * @param vector0 angle between vector0 and vector1
  3209. * @param vector1 angle between vector0 and vector1
  3210. * @param normal direction of the normal
  3211. * @return the angle between vector0 and vector1
  3212. */
  3213. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3214. var v0 = vector0.clone().normalize();
  3215. var v1 = vector1.clone().normalize();
  3216. var dot = Vector3.Dot(v0, v1);
  3217. var n = Vector3.Cross(v0, v1);
  3218. if (Vector3.Dot(n, normal) > 0) {
  3219. return Math.acos(dot);
  3220. }
  3221. return -Math.acos(dot);
  3222. };
  3223. /**
  3224. * Returns a new Vector3 set from the index "offset" of the given array
  3225. * @param array defines the source array
  3226. * @param offset defines the offset in the source array
  3227. * @returns the new Vector3
  3228. */
  3229. Vector3.FromArray = function (array, offset) {
  3230. if (!offset) {
  3231. offset = 0;
  3232. }
  3233. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3237. * This function is deprecated. Use FromArray instead
  3238. * @param array defines the source array
  3239. * @param offset defines the offset in the source array
  3240. * @returns the new Vector3
  3241. */
  3242. Vector3.FromFloatArray = function (array, offset) {
  3243. return Vector3.FromArray(array, offset);
  3244. };
  3245. /**
  3246. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3247. * @param array defines the source array
  3248. * @param offset defines the offset in the source array
  3249. * @param result defines the Vector3 where to store the result
  3250. */
  3251. Vector3.FromArrayToRef = function (array, offset, result) {
  3252. result.x = array[offset];
  3253. result.y = array[offset + 1];
  3254. result.z = array[offset + 2];
  3255. };
  3256. /**
  3257. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3258. * This function is deprecated. Use FromArrayToRef instead.
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3264. return Vector3.FromArrayToRef(array, offset, result);
  3265. };
  3266. /**
  3267. * Sets the given vector "result" with the given floats.
  3268. * @param x defines the x coordinate of the source
  3269. * @param y defines the y coordinate of the source
  3270. * @param z defines the z coordinate of the source
  3271. * @param result defines the Vector3 where to store the result
  3272. */
  3273. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3274. result.x = x;
  3275. result.y = y;
  3276. result.z = z;
  3277. };
  3278. /**
  3279. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3280. * @returns a new empty Vector3
  3281. */
  3282. Vector3.Zero = function () {
  3283. return new Vector3(0.0, 0.0, 0.0);
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3287. * @returns a new unit Vector3
  3288. */
  3289. Vector3.One = function () {
  3290. return new Vector3(1.0, 1.0, 1.0);
  3291. };
  3292. /**
  3293. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3294. * @returns a new up Vector3
  3295. */
  3296. Vector3.Up = function () {
  3297. return new Vector3(0.0, 1.0, 0.0);
  3298. };
  3299. /**
  3300. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3301. * @returns a new forward Vector3
  3302. */
  3303. Vector3.Forward = function () {
  3304. return new Vector3(0.0, 0.0, 1.0);
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3308. * @returns a new right Vector3
  3309. */
  3310. Vector3.Right = function () {
  3311. return new Vector3(1.0, 0.0, 0.0);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3315. * @returns a new left Vector3
  3316. */
  3317. Vector3.Left = function () {
  3318. return new Vector3(-1.0, 0.0, 0.0);
  3319. };
  3320. /**
  3321. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3322. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3323. * @param vector defines the Vector3 to transform
  3324. * @param transformation defines the transformation matrix
  3325. * @returns the transformed Vector3
  3326. */
  3327. Vector3.TransformCoordinates = function (vector, transformation) {
  3328. var result = Vector3.Zero();
  3329. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3330. return result;
  3331. };
  3332. /**
  3333. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3334. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3335. * @param vector defines the Vector3 to transform
  3336. * @param transformation defines the transformation matrix
  3337. * @param result defines the Vector3 where to store the result
  3338. */
  3339. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3340. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3341. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3342. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3343. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3344. result.x = x / w;
  3345. result.y = y / w;
  3346. result.z = z / w;
  3347. };
  3348. /**
  3349. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3350. * This method computes tranformed coordinates only, not transformed direction vectors
  3351. * @param x define the x coordinate of the source vector
  3352. * @param y define the y coordinate of the source vector
  3353. * @param z define the z coordinate of the source vector
  3354. * @param transformation defines the transformation matrix
  3355. * @param result defines the Vector3 where to store the result
  3356. */
  3357. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3358. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3359. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3360. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3361. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3362. result.x = rx / rw;
  3363. result.y = ry / rw;
  3364. result.z = rz / rw;
  3365. };
  3366. /**
  3367. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3368. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @returns the new Vector3
  3372. */
  3373. Vector3.TransformNormal = function (vector, transformation) {
  3374. var result = Vector3.Zero();
  3375. Vector3.TransformNormalToRef(vector, transformation, result);
  3376. return result;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3380. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3381. * @param vector defines the Vector3 to transform
  3382. * @param transformation defines the transformation matrix
  3383. * @param result defines the Vector3 where to store the result
  3384. */
  3385. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3386. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3387. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3388. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3389. result.x = x;
  3390. result.y = y;
  3391. result.z = z;
  3392. };
  3393. /**
  3394. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3395. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3396. * @param x define the x coordinate of the source vector
  3397. * @param y define the y coordinate of the source vector
  3398. * @param z define the z coordinate of the source vector
  3399. * @param transformation defines the transformation matrix
  3400. * @param result defines the Vector3 where to store the result
  3401. */
  3402. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3403. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3404. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3405. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3406. };
  3407. /**
  3408. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3409. * @param value1 defines the first control point
  3410. * @param value2 defines the second control point
  3411. * @param value3 defines the third control point
  3412. * @param value4 defines the fourth control point
  3413. * @param amount defines the amount on the spline to use
  3414. * @returns the new Vector3
  3415. */
  3416. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3417. var squared = amount * amount;
  3418. var cubed = amount * squared;
  3419. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3420. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3421. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3422. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3423. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3424. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3425. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3426. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3427. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3428. return new Vector3(x, y, z);
  3429. };
  3430. /**
  3431. * 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"
  3432. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3433. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3434. * @param value defines the current value
  3435. * @param min defines the lower range value
  3436. * @param max defines the upper range value
  3437. * @returns the new Vector3
  3438. */
  3439. Vector3.Clamp = function (value, min, max) {
  3440. var x = value.x;
  3441. x = (x > max.x) ? max.x : x;
  3442. x = (x < min.x) ? min.x : x;
  3443. var y = value.y;
  3444. y = (y > max.y) ? max.y : y;
  3445. y = (y < min.y) ? min.y : y;
  3446. var z = value.z;
  3447. z = (z > max.z) ? max.z : z;
  3448. z = (z < min.z) ? min.z : z;
  3449. return new Vector3(x, y, z);
  3450. };
  3451. /**
  3452. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3453. * @param value1 defines the first control point
  3454. * @param tangent1 defines the first tangent vector
  3455. * @param value2 defines the second control point
  3456. * @param tangent2 defines the second tangent vector
  3457. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3458. * @returns the new Vector3
  3459. */
  3460. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3461. var squared = amount * amount;
  3462. var cubed = amount * squared;
  3463. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3464. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3465. var part3 = (cubed - (2.0 * squared)) + amount;
  3466. var part4 = cubed - squared;
  3467. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3468. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3469. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3470. return new Vector3(x, y, z);
  3471. };
  3472. /**
  3473. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3474. * @param start defines the start value
  3475. * @param end defines the end value
  3476. * @param amount max defines amount between both (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Lerp = function (start, end, amount) {
  3480. var result = new Vector3(0, 0, 0);
  3481. Vector3.LerpToRef(start, end, amount, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3486. * @param start defines the start value
  3487. * @param end defines the end value
  3488. * @param amount max defines amount between both (between 0 and 1)
  3489. * @param result defines the Vector3 where to store the result
  3490. */
  3491. Vector3.LerpToRef = function (start, end, amount, result) {
  3492. result.x = start.x + ((end.x - start.x) * amount);
  3493. result.y = start.y + ((end.y - start.y) * amount);
  3494. result.z = start.z + ((end.z - start.z) * amount);
  3495. };
  3496. /**
  3497. * Returns the dot product (float) between the vectors "left" and "right"
  3498. * @param left defines the left operand
  3499. * @param right defines the right operand
  3500. * @returns the dot product
  3501. */
  3502. Vector3.Dot = function (left, right) {
  3503. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3504. };
  3505. /**
  3506. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3507. * The cross product is then orthogonal to both "left" and "right"
  3508. * @param left defines the left operand
  3509. * @param right defines the right operand
  3510. * @returns the cross product
  3511. */
  3512. Vector3.Cross = function (left, right) {
  3513. var result = Vector3.Zero();
  3514. Vector3.CrossToRef(left, right, result);
  3515. return result;
  3516. };
  3517. /**
  3518. * Sets the given vector "result" with the cross product of "left" and "right"
  3519. * The cross product is then orthogonal to both "left" and "right"
  3520. * @param left defines the left operand
  3521. * @param right defines the right operand
  3522. * @param result defines the Vector3 where to store the result
  3523. */
  3524. Vector3.CrossToRef = function (left, right, result) {
  3525. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3526. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3527. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3528. result.copyFrom(MathTmp.Vector3[0]);
  3529. };
  3530. /**
  3531. * Returns a new Vector3 as the normalization of the given vector
  3532. * @param vector defines the Vector3 to normalize
  3533. * @returns the new Vector3
  3534. */
  3535. Vector3.Normalize = function (vector) {
  3536. var result = Vector3.Zero();
  3537. Vector3.NormalizeToRef(vector, result);
  3538. return result;
  3539. };
  3540. /**
  3541. * Sets the given vector "result" with the normalization of the given first vector
  3542. * @param vector defines the Vector3 to normalize
  3543. * @param result defines the Vector3 where to store the result
  3544. */
  3545. Vector3.NormalizeToRef = function (vector, result) {
  3546. result.copyFrom(vector);
  3547. result.normalize();
  3548. };
  3549. /**
  3550. * Project a Vector3 onto screen space
  3551. * @param vector defines the Vector3 to project
  3552. * @param world defines the world matrix to use
  3553. * @param transform defines the transform (view x projection) matrix to use
  3554. * @param viewport defines the screen viewport to use
  3555. * @returns the new Vector3
  3556. */
  3557. Vector3.Project = function (vector, world, transform, viewport) {
  3558. var cw = viewport.width;
  3559. var ch = viewport.height;
  3560. var cx = viewport.x;
  3561. var cy = viewport.y;
  3562. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3563. 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);
  3564. var matrix = MathTmp.Matrix[0];
  3565. world.multiplyToRef(transform, matrix);
  3566. matrix.multiplyToRef(viewportMatrix, matrix);
  3567. return Vector3.TransformCoordinates(vector, matrix);
  3568. };
  3569. /**
  3570. * Unproject from screen space to object space
  3571. * @param source defines the screen space Vector3 to use
  3572. * @param viewportWidth defines the current width of the viewport
  3573. * @param viewportHeight defines the current height of the viewport
  3574. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3575. * @param transform defines the transform (view x projection) matrix to use
  3576. * @returns the new Vector3
  3577. */
  3578. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3579. var matrix = MathTmp.Matrix[0];
  3580. world.multiplyToRef(transform, matrix);
  3581. matrix.invert();
  3582. source.x = source.x / viewportWidth * 2 - 1;
  3583. source.y = -(source.y / viewportHeight * 2 - 1);
  3584. var vector = Vector3.TransformCoordinates(source, matrix);
  3585. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3586. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3587. vector = vector.scale(1.0 / num);
  3588. }
  3589. return vector;
  3590. };
  3591. /**
  3592. * Unproject from screen space to object space
  3593. * @param source defines the screen space Vector3 to use
  3594. * @param viewportWidth defines the current width of the viewport
  3595. * @param viewportHeight defines the current height of the viewport
  3596. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3597. * @param view defines the view matrix to use
  3598. * @param projection defines the projection matrix to use
  3599. * @returns the new Vector3
  3600. */
  3601. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3602. var result = Vector3.Zero();
  3603. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3604. return result;
  3605. };
  3606. /**
  3607. * Unproject from screen space to object space
  3608. * @param source defines the screen space Vector3 to use
  3609. * @param viewportWidth defines the current width of the viewport
  3610. * @param viewportHeight defines the current height of the viewport
  3611. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3612. * @param view defines the view matrix to use
  3613. * @param projection defines the projection matrix to use
  3614. * @param result defines the Vector3 where to store the result
  3615. */
  3616. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3617. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3618. };
  3619. /**
  3620. * Unproject from screen space to object space
  3621. * @param sourceX defines the screen space x coordinate to use
  3622. * @param sourceY defines the screen space y coordinate to use
  3623. * @param sourceZ defines the screen space z coordinate to use
  3624. * @param viewportWidth defines the current width of the viewport
  3625. * @param viewportHeight defines the current height of the viewport
  3626. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3627. * @param view defines the view matrix to use
  3628. * @param projection defines the projection matrix to use
  3629. * @param result defines the Vector3 where to store the result
  3630. */
  3631. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3632. var matrix = MathTmp.Matrix[0];
  3633. world.multiplyToRef(view, matrix);
  3634. matrix.multiplyToRef(projection, matrix);
  3635. matrix.invert();
  3636. var screenSource = MathTmp.Vector3[0];
  3637. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3638. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3639. screenSource.z = 2 * sourceZ - 1.0;
  3640. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3641. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3642. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3643. result.scaleInPlace(1.0 / num);
  3644. }
  3645. };
  3646. /**
  3647. * Gets the minimal coordinate values between two Vector3
  3648. * @param left defines the first operand
  3649. * @param right defines the second operand
  3650. * @returns the new Vector3
  3651. */
  3652. Vector3.Minimize = function (left, right) {
  3653. var min = left.clone();
  3654. min.minimizeInPlace(right);
  3655. return min;
  3656. };
  3657. /**
  3658. * Gets the maximal coordinate values between two Vector3
  3659. * @param left defines the first operand
  3660. * @param right defines the second operand
  3661. * @returns the new Vector3
  3662. */
  3663. Vector3.Maximize = function (left, right) {
  3664. var max = left.clone();
  3665. max.maximizeInPlace(right);
  3666. return max;
  3667. };
  3668. /**
  3669. * Returns the distance between the vectors "value1" and "value2"
  3670. * @param value1 defines the first operand
  3671. * @param value2 defines the second operand
  3672. * @returns the distance
  3673. */
  3674. Vector3.Distance = function (value1, value2) {
  3675. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3676. };
  3677. /**
  3678. * Returns the squared distance between the vectors "value1" and "value2"
  3679. * @param value1 defines the first operand
  3680. * @param value2 defines the second operand
  3681. * @returns the squared distance
  3682. */
  3683. Vector3.DistanceSquared = function (value1, value2) {
  3684. var x = value1.x - value2.x;
  3685. var y = value1.y - value2.y;
  3686. var z = value1.z - value2.z;
  3687. return (x * x) + (y * y) + (z * z);
  3688. };
  3689. /**
  3690. * Returns a new Vector3 located at the center between "value1" and "value2"
  3691. * @param value1 defines the first operand
  3692. * @param value2 defines the second operand
  3693. * @returns the new Vector3
  3694. */
  3695. Vector3.Center = function (value1, value2) {
  3696. var center = value1.add(value2);
  3697. center.scaleInPlace(0.5);
  3698. return center;
  3699. };
  3700. /**
  3701. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3702. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3703. * to something in order to rotate it from its local system to the given target system
  3704. * Note: axis1, axis2 and axis3 are normalized during this operation
  3705. * @param axis1 defines the first axis
  3706. * @param axis2 defines the second axis
  3707. * @param axis3 defines the third axis
  3708. * @returns a new Vector3
  3709. */
  3710. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3711. var rotation = Vector3.Zero();
  3712. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3713. return rotation;
  3714. };
  3715. /**
  3716. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3717. * @param axis1 defines the first axis
  3718. * @param axis2 defines the second axis
  3719. * @param axis3 defines the third axis
  3720. * @param ref defines the Vector3 where to store the result
  3721. */
  3722. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3723. var quat = MathTmp.Quaternion[0];
  3724. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3725. quat.toEulerAnglesToRef(ref);
  3726. };
  3727. return Vector3;
  3728. }());
  3729. BABYLON.Vector3 = Vector3;
  3730. //Vector4 class created for EulerAngle class conversion to Quaternion
  3731. var Vector4 = /** @class */ (function () {
  3732. /**
  3733. * Creates a Vector4 object from the given floats.
  3734. */
  3735. function Vector4(x, y, z, w) {
  3736. this.x = x;
  3737. this.y = y;
  3738. this.z = z;
  3739. this.w = w;
  3740. }
  3741. /**
  3742. * Returns the string with the Vector4 coordinates.
  3743. */
  3744. Vector4.prototype.toString = function () {
  3745. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3746. };
  3747. /**
  3748. * Returns the string "Vector4".
  3749. */
  3750. Vector4.prototype.getClassName = function () {
  3751. return "Vector4";
  3752. };
  3753. /**
  3754. * Returns the Vector4 hash code.
  3755. */
  3756. Vector4.prototype.getHashCode = function () {
  3757. var hash = this.x || 0;
  3758. hash = (hash * 397) ^ (this.y || 0);
  3759. hash = (hash * 397) ^ (this.z || 0);
  3760. hash = (hash * 397) ^ (this.w || 0);
  3761. return hash;
  3762. };
  3763. // Operators
  3764. /**
  3765. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3766. */
  3767. Vector4.prototype.asArray = function () {
  3768. var result = new Array();
  3769. this.toArray(result, 0);
  3770. return result;
  3771. };
  3772. /**
  3773. * Populates the given array from the given index with the Vector4 coordinates.
  3774. * Returns the Vector4.
  3775. */
  3776. Vector4.prototype.toArray = function (array, index) {
  3777. if (index === undefined) {
  3778. index = 0;
  3779. }
  3780. array[index] = this.x;
  3781. array[index + 1] = this.y;
  3782. array[index + 2] = this.z;
  3783. array[index + 3] = this.w;
  3784. return this;
  3785. };
  3786. /**
  3787. * Adds the given vector to the current Vector4.
  3788. * Returns the updated Vector4.
  3789. */
  3790. Vector4.prototype.addInPlace = function (otherVector) {
  3791. this.x += otherVector.x;
  3792. this.y += otherVector.y;
  3793. this.z += otherVector.z;
  3794. this.w += otherVector.w;
  3795. return this;
  3796. };
  3797. /**
  3798. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3799. */
  3800. Vector4.prototype.add = function (otherVector) {
  3801. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3802. };
  3803. /**
  3804. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3805. * Returns the current Vector4.
  3806. */
  3807. Vector4.prototype.addToRef = function (otherVector, result) {
  3808. result.x = this.x + otherVector.x;
  3809. result.y = this.y + otherVector.y;
  3810. result.z = this.z + otherVector.z;
  3811. result.w = this.w + otherVector.w;
  3812. return this;
  3813. };
  3814. /**
  3815. * Subtract in place the given vector from the current Vector4.
  3816. * Returns the updated Vector4.
  3817. */
  3818. Vector4.prototype.subtractInPlace = function (otherVector) {
  3819. this.x -= otherVector.x;
  3820. this.y -= otherVector.y;
  3821. this.z -= otherVector.z;
  3822. this.w -= otherVector.w;
  3823. return this;
  3824. };
  3825. /**
  3826. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3827. */
  3828. Vector4.prototype.subtract = function (otherVector) {
  3829. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3830. };
  3831. /**
  3832. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3833. * Returns the current Vector4.
  3834. */
  3835. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3836. result.x = this.x - otherVector.x;
  3837. result.y = this.y - otherVector.y;
  3838. result.z = this.z - otherVector.z;
  3839. result.w = this.w - otherVector.w;
  3840. return this;
  3841. };
  3842. /**
  3843. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3844. */
  3845. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3846. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3847. };
  3848. /**
  3849. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3850. * Returns the current Vector4.
  3851. */
  3852. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3853. result.x = this.x - x;
  3854. result.y = this.y - y;
  3855. result.z = this.z - z;
  3856. result.w = this.w - w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3861. */
  3862. Vector4.prototype.negate = function () {
  3863. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3864. };
  3865. /**
  3866. * Multiplies the current Vector4 coordinates by scale (float).
  3867. * Returns the updated Vector4.
  3868. */
  3869. Vector4.prototype.scaleInPlace = function (scale) {
  3870. this.x *= scale;
  3871. this.y *= scale;
  3872. this.z *= scale;
  3873. this.w *= scale;
  3874. return this;
  3875. };
  3876. /**
  3877. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3878. */
  3879. Vector4.prototype.scale = function (scale) {
  3880. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3881. };
  3882. /**
  3883. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3884. * Returns the current Vector4.
  3885. */
  3886. Vector4.prototype.scaleToRef = function (scale, result) {
  3887. result.x = this.x * scale;
  3888. result.y = this.y * scale;
  3889. result.z = this.z * scale;
  3890. result.w = this.w * scale;
  3891. return this;
  3892. };
  3893. /**
  3894. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3895. * @param scale defines the scale factor
  3896. * @param result defines the Vector4 object where to store the result
  3897. * @returns the unmodified current Vector4
  3898. */
  3899. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3900. result.x += this.x * scale;
  3901. result.y += this.y * scale;
  3902. result.z += this.z * scale;
  3903. result.w += this.w * scale;
  3904. return this;
  3905. };
  3906. /**
  3907. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3908. */
  3909. Vector4.prototype.equals = function (otherVector) {
  3910. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3911. };
  3912. /**
  3913. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3914. */
  3915. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3916. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3917. return otherVector
  3918. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3919. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3920. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3921. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3922. };
  3923. /**
  3924. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3925. */
  3926. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3927. return this.x === x && this.y === y && this.z === z && this.w === w;
  3928. };
  3929. /**
  3930. * Multiplies in place the current Vector4 by the given one.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3934. this.x *= otherVector.x;
  3935. this.y *= otherVector.y;
  3936. this.z *= otherVector.z;
  3937. this.w *= otherVector.w;
  3938. return this;
  3939. };
  3940. /**
  3941. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3942. */
  3943. Vector4.prototype.multiply = function (otherVector) {
  3944. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3945. };
  3946. /**
  3947. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3948. * Returns the current Vector4.
  3949. */
  3950. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3951. result.x = this.x * otherVector.x;
  3952. result.y = this.y * otherVector.y;
  3953. result.z = this.z * otherVector.z;
  3954. result.w = this.w * otherVector.w;
  3955. return this;
  3956. };
  3957. /**
  3958. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3959. */
  3960. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3961. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3962. };
  3963. /**
  3964. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3965. */
  3966. Vector4.prototype.divide = function (otherVector) {
  3967. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3968. };
  3969. /**
  3970. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3971. * Returns the current Vector4.
  3972. */
  3973. Vector4.prototype.divideToRef = function (otherVector, result) {
  3974. result.x = this.x / otherVector.x;
  3975. result.y = this.y / otherVector.y;
  3976. result.z = this.z / otherVector.z;
  3977. result.w = this.w / otherVector.w;
  3978. return this;
  3979. };
  3980. /**
  3981. * Divides the current Vector3 coordinates by the given ones.
  3982. * @returns the updated Vector3.
  3983. */
  3984. Vector4.prototype.divideInPlace = function (otherVector) {
  3985. return this.divideToRef(otherVector, this);
  3986. };
  3987. /**
  3988. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3989. * @param other defines the second operand
  3990. * @returns the current updated Vector4
  3991. */
  3992. Vector4.prototype.minimizeInPlace = function (other) {
  3993. if (other.x < this.x)
  3994. this.x = other.x;
  3995. if (other.y < this.y)
  3996. this.y = other.y;
  3997. if (other.z < this.z)
  3998. this.z = other.z;
  3999. if (other.w < this.w)
  4000. this.w = other.w;
  4001. return this;
  4002. };
  4003. /**
  4004. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4005. * @param other defines the second operand
  4006. * @returns the current updated Vector4
  4007. */
  4008. Vector4.prototype.maximizeInPlace = function (other) {
  4009. if (other.x > this.x)
  4010. this.x = other.x;
  4011. if (other.y > this.y)
  4012. this.y = other.y;
  4013. if (other.z > this.z)
  4014. this.z = other.z;
  4015. if (other.w > this.w)
  4016. this.w = other.w;
  4017. return this;
  4018. };
  4019. // Properties
  4020. /**
  4021. * Returns the Vector4 length (float).
  4022. */
  4023. Vector4.prototype.length = function () {
  4024. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4025. };
  4026. /**
  4027. * Returns the Vector4 squared length (float).
  4028. */
  4029. Vector4.prototype.lengthSquared = function () {
  4030. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4031. };
  4032. // Methods
  4033. /**
  4034. * Normalizes in place the Vector4.
  4035. * Returns the updated Vector4.
  4036. */
  4037. Vector4.prototype.normalize = function () {
  4038. var len = this.length();
  4039. if (len === 0)
  4040. return this;
  4041. var num = 1.0 / len;
  4042. this.x *= num;
  4043. this.y *= num;
  4044. this.z *= num;
  4045. this.w *= num;
  4046. return this;
  4047. };
  4048. /**
  4049. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4050. */
  4051. Vector4.prototype.toVector3 = function () {
  4052. return new Vector3(this.x, this.y, this.z);
  4053. };
  4054. /**
  4055. * Returns a new Vector4 copied from the current one.
  4056. */
  4057. Vector4.prototype.clone = function () {
  4058. return new Vector4(this.x, this.y, this.z, this.w);
  4059. };
  4060. /**
  4061. * Updates the current Vector4 with the given one coordinates.
  4062. * Returns the updated Vector4.
  4063. */
  4064. Vector4.prototype.copyFrom = function (source) {
  4065. this.x = source.x;
  4066. this.y = source.y;
  4067. this.z = source.z;
  4068. this.w = source.w;
  4069. return this;
  4070. };
  4071. /**
  4072. * Updates the current Vector4 coordinates with the given floats.
  4073. * Returns the updated Vector4.
  4074. */
  4075. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4076. this.x = x;
  4077. this.y = y;
  4078. this.z = z;
  4079. this.w = w;
  4080. return this;
  4081. };
  4082. /**
  4083. * Updates the current Vector4 coordinates with the given floats.
  4084. * Returns the updated Vector4.
  4085. */
  4086. Vector4.prototype.set = function (x, y, z, w) {
  4087. return this.copyFromFloats(x, y, z, w);
  4088. };
  4089. // Statics
  4090. /**
  4091. * Returns a new Vector4 set from the starting index of the given array.
  4092. */
  4093. Vector4.FromArray = function (array, offset) {
  4094. if (!offset) {
  4095. offset = 0;
  4096. }
  4097. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4098. };
  4099. /**
  4100. * Updates the given vector "result" from the starting index of the given array.
  4101. */
  4102. Vector4.FromArrayToRef = function (array, offset, result) {
  4103. result.x = array[offset];
  4104. result.y = array[offset + 1];
  4105. result.z = array[offset + 2];
  4106. result.w = array[offset + 3];
  4107. };
  4108. /**
  4109. * Updates the given vector "result" from the starting index of the given Float32Array.
  4110. */
  4111. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4112. Vector4.FromArrayToRef(array, offset, result);
  4113. };
  4114. /**
  4115. * Updates the given vector "result" coordinates from the given floats.
  4116. */
  4117. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4118. result.x = x;
  4119. result.y = y;
  4120. result.z = z;
  4121. result.w = w;
  4122. };
  4123. /**
  4124. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4125. */
  4126. Vector4.Zero = function () {
  4127. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4128. };
  4129. /**
  4130. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4131. */
  4132. Vector4.One = function () {
  4133. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4134. };
  4135. /**
  4136. * Returns a new normalized Vector4 from the given one.
  4137. */
  4138. Vector4.Normalize = function (vector) {
  4139. var result = Vector4.Zero();
  4140. Vector4.NormalizeToRef(vector, result);
  4141. return result;
  4142. };
  4143. /**
  4144. * Updates the given vector "result" from the normalization of the given one.
  4145. */
  4146. Vector4.NormalizeToRef = function (vector, result) {
  4147. result.copyFrom(vector);
  4148. result.normalize();
  4149. };
  4150. Vector4.Minimize = function (left, right) {
  4151. var min = left.clone();
  4152. min.minimizeInPlace(right);
  4153. return min;
  4154. };
  4155. Vector4.Maximize = function (left, right) {
  4156. var max = left.clone();
  4157. max.maximizeInPlace(right);
  4158. return max;
  4159. };
  4160. /**
  4161. * Returns the distance (float) between the vectors "value1" and "value2".
  4162. */
  4163. Vector4.Distance = function (value1, value2) {
  4164. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4165. };
  4166. /**
  4167. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4168. */
  4169. Vector4.DistanceSquared = function (value1, value2) {
  4170. var x = value1.x - value2.x;
  4171. var y = value1.y - value2.y;
  4172. var z = value1.z - value2.z;
  4173. var w = value1.w - value2.w;
  4174. return (x * x) + (y * y) + (z * z) + (w * w);
  4175. };
  4176. /**
  4177. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4178. */
  4179. Vector4.Center = function (value1, value2) {
  4180. var center = value1.add(value2);
  4181. center.scaleInPlace(0.5);
  4182. return center;
  4183. };
  4184. /**
  4185. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4186. * This methods computes transformed normalized direction vectors only.
  4187. */
  4188. Vector4.TransformNormal = function (vector, transformation) {
  4189. var result = Vector4.Zero();
  4190. Vector4.TransformNormalToRef(vector, transformation, result);
  4191. return result;
  4192. };
  4193. /**
  4194. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4195. * This methods computes transformed normalized direction vectors only.
  4196. */
  4197. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4198. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4199. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4200. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4201. result.x = x;
  4202. result.y = y;
  4203. result.z = z;
  4204. result.w = vector.w;
  4205. };
  4206. /**
  4207. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4208. * This methods computes transformed normalized direction vectors only.
  4209. */
  4210. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4211. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4212. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4213. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4214. result.w = w;
  4215. };
  4216. return Vector4;
  4217. }());
  4218. BABYLON.Vector4 = Vector4;
  4219. var Size = /** @class */ (function () {
  4220. /**
  4221. * Creates a Size object from the given width and height (floats).
  4222. */
  4223. function Size(width, height) {
  4224. this.width = width;
  4225. this.height = height;
  4226. }
  4227. // Returns a string with the Size width and height.
  4228. Size.prototype.toString = function () {
  4229. return "{W: " + this.width + ", H: " + this.height + "}";
  4230. };
  4231. /**
  4232. * Returns the string "Size"
  4233. */
  4234. Size.prototype.getClassName = function () {
  4235. return "Size";
  4236. };
  4237. /**
  4238. * Returns the Size hash code.
  4239. */
  4240. Size.prototype.getHashCode = function () {
  4241. var hash = this.width || 0;
  4242. hash = (hash * 397) ^ (this.height || 0);
  4243. return hash;
  4244. };
  4245. /**
  4246. * Updates the current size from the given one.
  4247. * Returns the updated Size.
  4248. */
  4249. Size.prototype.copyFrom = function (src) {
  4250. this.width = src.width;
  4251. this.height = src.height;
  4252. };
  4253. /**
  4254. * Updates in place the current Size from the given floats.
  4255. * Returns the updated Size.
  4256. */
  4257. Size.prototype.copyFromFloats = function (width, height) {
  4258. this.width = width;
  4259. this.height = height;
  4260. return this;
  4261. };
  4262. /**
  4263. * Updates in place the current Size from the given floats.
  4264. * Returns the updated Size.
  4265. */
  4266. Size.prototype.set = function (width, height) {
  4267. return this.copyFromFloats(width, height);
  4268. };
  4269. /**
  4270. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4271. */
  4272. Size.prototype.multiplyByFloats = function (w, h) {
  4273. return new Size(this.width * w, this.height * h);
  4274. };
  4275. /**
  4276. * Returns a new Size copied from the given one.
  4277. */
  4278. Size.prototype.clone = function () {
  4279. return new Size(this.width, this.height);
  4280. };
  4281. /**
  4282. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4283. */
  4284. Size.prototype.equals = function (other) {
  4285. if (!other) {
  4286. return false;
  4287. }
  4288. return (this.width === other.width) && (this.height === other.height);
  4289. };
  4290. Object.defineProperty(Size.prototype, "surface", {
  4291. /**
  4292. * Returns the surface of the Size : width * height (float).
  4293. */
  4294. get: function () {
  4295. return this.width * this.height;
  4296. },
  4297. enumerable: true,
  4298. configurable: true
  4299. });
  4300. /**
  4301. * Returns a new Size set to (0.0, 0.0)
  4302. */
  4303. Size.Zero = function () {
  4304. return new Size(0.0, 0.0);
  4305. };
  4306. /**
  4307. * Returns a new Size set as the addition result of the current Size and the given one.
  4308. */
  4309. Size.prototype.add = function (otherSize) {
  4310. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4311. return r;
  4312. };
  4313. /**
  4314. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4315. */
  4316. Size.prototype.subtract = function (otherSize) {
  4317. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4318. return r;
  4319. };
  4320. /**
  4321. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4322. */
  4323. Size.Lerp = function (start, end, amount) {
  4324. var w = start.width + ((end.width - start.width) * amount);
  4325. var h = start.height + ((end.height - start.height) * amount);
  4326. return new Size(w, h);
  4327. };
  4328. return Size;
  4329. }());
  4330. BABYLON.Size = Size;
  4331. /**
  4332. * Class used to store quaternion data
  4333. * @see https://en.wikipedia.org/wiki/Quaternion
  4334. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4335. */
  4336. var Quaternion = /** @class */ (function () {
  4337. /**
  4338. * Creates a new Quaternion from the given floats
  4339. * @param x defines the first component (0 by default)
  4340. * @param y defines the second component (0 by default)
  4341. * @param z defines the third component (0 by default)
  4342. * @param w defines the fourth component (1.0 by default)
  4343. */
  4344. function Quaternion(
  4345. /** defines the first component (0 by default) */
  4346. x,
  4347. /** defines the second component (0 by default) */
  4348. y,
  4349. /** defines the third component (0 by default) */
  4350. z,
  4351. /** defines the fourth component (1.0 by default) */
  4352. w) {
  4353. if (x === void 0) { x = 0.0; }
  4354. if (y === void 0) { y = 0.0; }
  4355. if (z === void 0) { z = 0.0; }
  4356. if (w === void 0) { w = 1.0; }
  4357. this.x = x;
  4358. this.y = y;
  4359. this.z = z;
  4360. this.w = w;
  4361. }
  4362. /**
  4363. * Gets a string representation for the current quaternion
  4364. * @returns a string with the Quaternion coordinates
  4365. */
  4366. Quaternion.prototype.toString = function () {
  4367. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4368. };
  4369. /**
  4370. * Gets the class name of the quaternion
  4371. * @returns the string "Quaternion"
  4372. */
  4373. Quaternion.prototype.getClassName = function () {
  4374. return "Quaternion";
  4375. };
  4376. /**
  4377. * Gets a hash code for this quaternion
  4378. * @returns the quaternion hash code
  4379. */
  4380. Quaternion.prototype.getHashCode = function () {
  4381. var hash = this.x || 0;
  4382. hash = (hash * 397) ^ (this.y || 0);
  4383. hash = (hash * 397) ^ (this.z || 0);
  4384. hash = (hash * 397) ^ (this.w || 0);
  4385. return hash;
  4386. };
  4387. /**
  4388. * Copy the quaternion to an array
  4389. * @returns a new array populated with 4 elements from the quaternion coordinates
  4390. */
  4391. Quaternion.prototype.asArray = function () {
  4392. return [this.x, this.y, this.z, this.w];
  4393. };
  4394. /**
  4395. * Check if two quaternions are equals
  4396. * @param otherQuaternion defines the second operand
  4397. * @return true if the current quaternion and the given one coordinates are strictly equals
  4398. */
  4399. Quaternion.prototype.equals = function (otherQuaternion) {
  4400. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4401. };
  4402. /**
  4403. * Clone the current quaternion
  4404. * @returns a new quaternion copied from the current one
  4405. */
  4406. Quaternion.prototype.clone = function () {
  4407. return new Quaternion(this.x, this.y, this.z, this.w);
  4408. };
  4409. /**
  4410. * Copy a quaternion to the current one
  4411. * @param other defines the other quaternion
  4412. * @returns the updated current quaternion
  4413. */
  4414. Quaternion.prototype.copyFrom = function (other) {
  4415. this.x = other.x;
  4416. this.y = other.y;
  4417. this.z = other.z;
  4418. this.w = other.w;
  4419. return this;
  4420. };
  4421. /**
  4422. * Updates the current quaternion with the given float coordinates
  4423. * @param x defines the x coordinate
  4424. * @param y defines the y coordinate
  4425. * @param z defines the z coordinate
  4426. * @param w defines the w coordinate
  4427. * @returns the updated current quaternion
  4428. */
  4429. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4430. this.x = x;
  4431. this.y = y;
  4432. this.z = z;
  4433. this.w = w;
  4434. return this;
  4435. };
  4436. /**
  4437. * Updates the current quaternion from the given float coordinates
  4438. * @param x defines the x coordinate
  4439. * @param y defines the y coordinate
  4440. * @param z defines the z coordinate
  4441. * @param w defines the w coordinate
  4442. * @returns the updated current quaternion
  4443. */
  4444. Quaternion.prototype.set = function (x, y, z, w) {
  4445. return this.copyFromFloats(x, y, z, w);
  4446. };
  4447. /**
  4448. * Adds two quaternions
  4449. * @param other defines the second operand
  4450. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4451. */
  4452. Quaternion.prototype.add = function (other) {
  4453. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4454. };
  4455. /**
  4456. * Add a quaternion to the current one
  4457. * @param other defines the quaternion to add
  4458. * @returns the current quaternion
  4459. */
  4460. Quaternion.prototype.addInPlace = function (other) {
  4461. this.x += other.x;
  4462. this.y += other.y;
  4463. this.z += other.z;
  4464. this.w += other.w;
  4465. return this;
  4466. };
  4467. /**
  4468. * Subtract two quaternions
  4469. * @param other defines the second operand
  4470. * @returns a new quaternion as the subtraction result of the given one from the current one
  4471. */
  4472. Quaternion.prototype.subtract = function (other) {
  4473. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4474. };
  4475. /**
  4476. * Multiplies the current quaternion by a scale factor
  4477. * @param value defines the scale factor
  4478. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4479. */
  4480. Quaternion.prototype.scale = function (value) {
  4481. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4482. };
  4483. /**
  4484. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4485. * @param scale defines the scale factor
  4486. * @param result defines the Quaternion object where to store the result
  4487. * @returns the unmodified current quaternion
  4488. */
  4489. Quaternion.prototype.scaleToRef = function (scale, result) {
  4490. result.x = this.x * scale;
  4491. result.y = this.y * scale;
  4492. result.z = this.z * scale;
  4493. result.w = this.w * scale;
  4494. return this;
  4495. };
  4496. /**
  4497. * Multiplies in place the current quaternion by a scale factor
  4498. * @param value defines the scale factor
  4499. * @returns the current modified quaternion
  4500. */
  4501. Quaternion.prototype.scaleInPlace = function (value) {
  4502. this.x *= value;
  4503. this.y *= value;
  4504. this.z *= value;
  4505. this.w *= value;
  4506. return this;
  4507. };
  4508. /**
  4509. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4510. * @param scale defines the scale factor
  4511. * @param result defines the Quaternion object where to store the result
  4512. * @returns the unmodified current quaternion
  4513. */
  4514. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4515. result.x += this.x * scale;
  4516. result.y += this.y * scale;
  4517. result.z += this.z * scale;
  4518. result.w += this.w * scale;
  4519. return this;
  4520. };
  4521. /**
  4522. * Multiplies two quaternions
  4523. * @param q1 defines the second operand
  4524. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4525. */
  4526. Quaternion.prototype.multiply = function (q1) {
  4527. var result = new Quaternion(0, 0, 0, 1.0);
  4528. this.multiplyToRef(q1, result);
  4529. return result;
  4530. };
  4531. /**
  4532. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4533. * @param q1 defines the second operand
  4534. * @param result defines the target quaternion
  4535. * @returns the current quaternion
  4536. */
  4537. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4538. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4539. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4540. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4541. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4542. result.copyFromFloats(x, y, z, w);
  4543. return this;
  4544. };
  4545. /**
  4546. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4547. * @param q1 defines the second operand
  4548. * @returns the currentupdated quaternion
  4549. */
  4550. Quaternion.prototype.multiplyInPlace = function (q1) {
  4551. this.multiplyToRef(q1, this);
  4552. return this;
  4553. };
  4554. /**
  4555. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4556. * @param ref defines the target quaternion
  4557. * @returns the current quaternion
  4558. */
  4559. Quaternion.prototype.conjugateToRef = function (ref) {
  4560. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4561. return this;
  4562. };
  4563. /**
  4564. * Conjugates in place (1-q) the current quaternion
  4565. * @returns the current updated quaternion
  4566. */
  4567. Quaternion.prototype.conjugateInPlace = function () {
  4568. this.x *= -1;
  4569. this.y *= -1;
  4570. this.z *= -1;
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates in place (1-q) the current quaternion
  4575. * @returns a new quaternion
  4576. */
  4577. Quaternion.prototype.conjugate = function () {
  4578. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4579. return result;
  4580. };
  4581. /**
  4582. * Gets length of current quaternion
  4583. * @returns the quaternion length (float)
  4584. */
  4585. Quaternion.prototype.length = function () {
  4586. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4587. };
  4588. /**
  4589. * Normalize in place the current quaternion
  4590. * @returns the current updated quaternion
  4591. */
  4592. Quaternion.prototype.normalize = function () {
  4593. var length = 1.0 / this.length();
  4594. this.x *= length;
  4595. this.y *= length;
  4596. this.z *= length;
  4597. this.w *= length;
  4598. return this;
  4599. };
  4600. /**
  4601. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4602. * @param order is a reserved parameter and is ignore for now
  4603. * @returns a new Vector3 containing the Euler angles
  4604. */
  4605. Quaternion.prototype.toEulerAngles = function (order) {
  4606. if (order === void 0) { order = "YZX"; }
  4607. var result = Vector3.Zero();
  4608. this.toEulerAnglesToRef(result, order);
  4609. return result;
  4610. };
  4611. /**
  4612. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4613. * @param result defines the vector which will be filled with the Euler angles
  4614. * @param order is a reserved parameter and is ignore for now
  4615. * @returns the current unchanged quaternion
  4616. */
  4617. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4618. if (order === void 0) { order = "YZX"; }
  4619. var qz = this.z;
  4620. var qx = this.x;
  4621. var qy = this.y;
  4622. var qw = this.w;
  4623. var sqw = qw * qw;
  4624. var sqz = qz * qz;
  4625. var sqx = qx * qx;
  4626. var sqy = qy * qy;
  4627. var zAxisY = qy * qz - qx * qw;
  4628. var limit = .4999999;
  4629. if (zAxisY < -limit) {
  4630. result.y = 2 * Math.atan2(qy, qw);
  4631. result.x = Math.PI / 2;
  4632. result.z = 0;
  4633. }
  4634. else if (zAxisY > limit) {
  4635. result.y = 2 * Math.atan2(qy, qw);
  4636. result.x = -Math.PI / 2;
  4637. result.z = 0;
  4638. }
  4639. else {
  4640. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4641. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4642. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4643. }
  4644. return this;
  4645. };
  4646. /**
  4647. * Updates the given rotation matrix with the current quaternion values
  4648. * @param result defines the target matrix
  4649. * @returns the current unchanged quaternion
  4650. */
  4651. Quaternion.prototype.toRotationMatrix = function (result) {
  4652. var xx = this.x * this.x;
  4653. var yy = this.y * this.y;
  4654. var zz = this.z * this.z;
  4655. var xy = this.x * this.y;
  4656. var zw = this.z * this.w;
  4657. var zx = this.z * this.x;
  4658. var yw = this.y * this.w;
  4659. var yz = this.y * this.z;
  4660. var xw = this.x * this.w;
  4661. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4662. result.m[1] = 2.0 * (xy + zw);
  4663. result.m[2] = 2.0 * (zx - yw);
  4664. result.m[3] = 0;
  4665. result.m[4] = 2.0 * (xy - zw);
  4666. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4667. result.m[6] = 2.0 * (yz + xw);
  4668. result.m[7] = 0;
  4669. result.m[8] = 2.0 * (zx + yw);
  4670. result.m[9] = 2.0 * (yz - xw);
  4671. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4672. result.m[11] = 0;
  4673. result.m[12] = 0;
  4674. result.m[13] = 0;
  4675. result.m[14] = 0;
  4676. result.m[15] = 1.0;
  4677. result._markAsUpdated();
  4678. return this;
  4679. };
  4680. /**
  4681. * Updates the current quaternion from the given rotation matrix values
  4682. * @param matrix defines the source matrix
  4683. * @returns the current updated quaternion
  4684. */
  4685. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4686. Quaternion.FromRotationMatrixToRef(matrix, this);
  4687. return this;
  4688. };
  4689. // Statics
  4690. /**
  4691. * Creates a new quaternion from a rotation matrix
  4692. * @param matrix defines the source matrix
  4693. * @returns a new quaternion created from the given rotation matrix values
  4694. */
  4695. Quaternion.FromRotationMatrix = function (matrix) {
  4696. var result = new Quaternion();
  4697. Quaternion.FromRotationMatrixToRef(matrix, result);
  4698. return result;
  4699. };
  4700. /**
  4701. * Updates the given quaternion with the given rotation matrix values
  4702. * @param matrix defines the source matrix
  4703. * @param result defines the target quaternion
  4704. */
  4705. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4706. var data = matrix.m;
  4707. var m11 = data[0], m12 = data[4], m13 = data[8];
  4708. var m21 = data[1], m22 = data[5], m23 = data[9];
  4709. var m31 = data[2], m32 = data[6], m33 = data[10];
  4710. var trace = m11 + m22 + m33;
  4711. var s;
  4712. if (trace > 0) {
  4713. s = 0.5 / Math.sqrt(trace + 1.0);
  4714. result.w = 0.25 / s;
  4715. result.x = (m32 - m23) * s;
  4716. result.y = (m13 - m31) * s;
  4717. result.z = (m21 - m12) * s;
  4718. }
  4719. else if (m11 > m22 && m11 > m33) {
  4720. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4721. result.w = (m32 - m23) / s;
  4722. result.x = 0.25 * s;
  4723. result.y = (m12 + m21) / s;
  4724. result.z = (m13 + m31) / s;
  4725. }
  4726. else if (m22 > m33) {
  4727. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4728. result.w = (m13 - m31) / s;
  4729. result.x = (m12 + m21) / s;
  4730. result.y = 0.25 * s;
  4731. result.z = (m23 + m32) / s;
  4732. }
  4733. else {
  4734. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4735. result.w = (m21 - m12) / s;
  4736. result.x = (m13 + m31) / s;
  4737. result.y = (m23 + m32) / s;
  4738. result.z = 0.25 * s;
  4739. }
  4740. };
  4741. /**
  4742. * Creates an empty quaternion
  4743. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4744. */
  4745. Quaternion.Zero = function () {
  4746. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4747. };
  4748. /**
  4749. * Inverse a given quaternion
  4750. * @param q defines the source quaternion
  4751. * @returns a new quaternion as the inverted current quaternion
  4752. */
  4753. Quaternion.Inverse = function (q) {
  4754. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4755. };
  4756. /**
  4757. * Creates an identity quaternion
  4758. * @returns the identity quaternion
  4759. */
  4760. Quaternion.Identity = function () {
  4761. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4762. };
  4763. /**
  4764. * Gets a boolean indicating if the given quaternion is identity
  4765. * @param quaternion defines the quaternion to check
  4766. * @returns true if the quaternion is identity
  4767. */
  4768. Quaternion.IsIdentity = function (quaternion) {
  4769. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4770. };
  4771. /**
  4772. * Creates a quaternion from a rotation around an axis
  4773. * @param axis defines the axis to use
  4774. * @param angle defines the angle to use
  4775. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4776. */
  4777. Quaternion.RotationAxis = function (axis, angle) {
  4778. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4779. };
  4780. /**
  4781. * Creates a rotation around an axis and stores it into the given quaternion
  4782. * @param axis defines the axis to use
  4783. * @param angle defines the angle to use
  4784. * @param result defines the target quaternion
  4785. * @returns the target quaternion
  4786. */
  4787. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4788. var sin = Math.sin(angle / 2);
  4789. axis.normalize();
  4790. result.w = Math.cos(angle / 2);
  4791. result.x = axis.x * sin;
  4792. result.y = axis.y * sin;
  4793. result.z = axis.z * sin;
  4794. return result;
  4795. };
  4796. /**
  4797. * Creates a new quaternion from data stored into an array
  4798. * @param array defines the data source
  4799. * @param offset defines the offset in the source array where the data starts
  4800. * @returns a new quaternion
  4801. */
  4802. Quaternion.FromArray = function (array, offset) {
  4803. if (!offset) {
  4804. offset = 0;
  4805. }
  4806. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4807. };
  4808. /**
  4809. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4810. * @param yaw defines the rotation around Y axis
  4811. * @param pitch defines the rotation around X axis
  4812. * @param roll defines the rotation around Z axis
  4813. * @returns the new quaternion
  4814. */
  4815. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4816. var q = new Quaternion();
  4817. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4818. return q;
  4819. };
  4820. /**
  4821. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4822. * @param yaw defines the rotation around Y axis
  4823. * @param pitch defines the rotation around X axis
  4824. * @param roll defines the rotation around Z axis
  4825. * @param result defines the target quaternion
  4826. */
  4827. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4828. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4829. var halfRoll = roll * 0.5;
  4830. var halfPitch = pitch * 0.5;
  4831. var halfYaw = yaw * 0.5;
  4832. var sinRoll = Math.sin(halfRoll);
  4833. var cosRoll = Math.cos(halfRoll);
  4834. var sinPitch = Math.sin(halfPitch);
  4835. var cosPitch = Math.cos(halfPitch);
  4836. var sinYaw = Math.sin(halfYaw);
  4837. var cosYaw = Math.cos(halfYaw);
  4838. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4839. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4840. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4841. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4842. };
  4843. /**
  4844. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4845. * @param alpha defines the rotation around first axis
  4846. * @param beta defines the rotation around second axis
  4847. * @param gamma defines the rotation around third axis
  4848. * @returns the new quaternion
  4849. */
  4850. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4851. var result = new Quaternion();
  4852. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4853. return result;
  4854. };
  4855. /**
  4856. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4857. * @param alpha defines the rotation around first axis
  4858. * @param beta defines the rotation around second axis
  4859. * @param gamma defines the rotation around third axis
  4860. * @param result defines the target quaternion
  4861. */
  4862. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4863. // Produces a quaternion from Euler angles in the z-x-z orientation
  4864. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4865. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4866. var halfBeta = beta * 0.5;
  4867. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4868. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4869. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4870. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4871. };
  4872. /**
  4873. * 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)
  4874. * @param axis1 defines the first axis
  4875. * @param axis2 defines the second axis
  4876. * @param axis3 defines the third axis
  4877. * @returns the new quaternion
  4878. */
  4879. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4880. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4881. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4882. return quat;
  4883. };
  4884. /**
  4885. * 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
  4886. * @param axis1 defines the first axis
  4887. * @param axis2 defines the second axis
  4888. * @param axis3 defines the third axis
  4889. * @param ref defines the target quaternion
  4890. */
  4891. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4892. var rotMat = MathTmp.Matrix[0];
  4893. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4894. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4895. };
  4896. /**
  4897. * Interpolates between two quaternions
  4898. * @param left defines first quaternion
  4899. * @param right defines second quaternion
  4900. * @param amount defines the gradient to use
  4901. * @returns the new interpolated quaternion
  4902. */
  4903. Quaternion.Slerp = function (left, right, amount) {
  4904. var result = Quaternion.Identity();
  4905. Quaternion.SlerpToRef(left, right, amount, result);
  4906. return result;
  4907. };
  4908. /**
  4909. * Interpolates between two quaternions and stores it into a target quaternion
  4910. * @param left defines first quaternion
  4911. * @param right defines second quaternion
  4912. * @param amount defines the gradient to use
  4913. * @param result defines the target quaternion
  4914. */
  4915. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4916. var num2;
  4917. var num3;
  4918. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4919. var flag = false;
  4920. if (num4 < 0) {
  4921. flag = true;
  4922. num4 = -num4;
  4923. }
  4924. if (num4 > 0.999999) {
  4925. num3 = 1 - amount;
  4926. num2 = flag ? -amount : amount;
  4927. }
  4928. else {
  4929. var num5 = Math.acos(num4);
  4930. var num6 = (1.0 / Math.sin(num5));
  4931. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4932. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4933. }
  4934. result.x = (num3 * left.x) + (num2 * right.x);
  4935. result.y = (num3 * left.y) + (num2 * right.y);
  4936. result.z = (num3 * left.z) + (num2 * right.z);
  4937. result.w = (num3 * left.w) + (num2 * right.w);
  4938. };
  4939. /**
  4940. * Interpolate between two quaternions using Hermite interpolation
  4941. * @param value1 defines first quaternion
  4942. * @param tangent1 defines the incoming tangent
  4943. * @param value2 defines second quaternion
  4944. * @param tangent2 defines the outgoing tangent
  4945. * @param amount defines the target quaternion
  4946. * @returns the new interpolated quaternion
  4947. */
  4948. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4949. var squared = amount * amount;
  4950. var cubed = amount * squared;
  4951. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4952. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4953. var part3 = (cubed - (2.0 * squared)) + amount;
  4954. var part4 = cubed - squared;
  4955. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4956. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4957. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4958. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4959. return new Quaternion(x, y, z, w);
  4960. };
  4961. return Quaternion;
  4962. }());
  4963. BABYLON.Quaternion = Quaternion;
  4964. /**
  4965. * Class used to store matrix data (4x4)
  4966. */
  4967. var Matrix = /** @class */ (function () {
  4968. /**
  4969. * Creates an empty matrix (filled with zeros)
  4970. */
  4971. function Matrix() {
  4972. this._isIdentity = false;
  4973. this._isIdentityDirty = true;
  4974. /**
  4975. * Gets or sets the internal data of the matrix
  4976. */
  4977. this.m = new Float32Array(16);
  4978. this._markAsUpdated();
  4979. }
  4980. /** @hidden */
  4981. Matrix.prototype._markAsUpdated = function () {
  4982. this.updateFlag = Matrix._updateFlagSeed++;
  4983. this._isIdentityDirty = true;
  4984. };
  4985. // Properties
  4986. /**
  4987. * Check if the current matrix is indentity
  4988. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4989. * @returns true is the matrix is the identity matrix
  4990. */
  4991. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4992. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4993. if (this._isIdentityDirty) {
  4994. this._isIdentityDirty = false;
  4995. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4996. this._isIdentity = false;
  4997. }
  4998. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4999. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5000. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5001. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5002. this._isIdentity = false;
  5003. }
  5004. else {
  5005. this._isIdentity = true;
  5006. }
  5007. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5008. this._isIdentity = false;
  5009. }
  5010. }
  5011. return this._isIdentity;
  5012. };
  5013. /**
  5014. * Gets the determinant of the matrix
  5015. * @returns the matrix determinant
  5016. */
  5017. Matrix.prototype.determinant = function () {
  5018. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5019. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5020. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5021. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5022. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5023. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5024. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5025. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5026. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5027. };
  5028. // Methods
  5029. /**
  5030. * Returns the matrix as a Float32Array
  5031. * @returns the matrix underlying array
  5032. */
  5033. Matrix.prototype.toArray = function () {
  5034. return this.m;
  5035. };
  5036. /**
  5037. * Returns the matrix as a Float32Array
  5038. * @returns the matrix underlying array.
  5039. */
  5040. Matrix.prototype.asArray = function () {
  5041. return this.toArray();
  5042. };
  5043. /**
  5044. * Inverts the current matrix in place
  5045. * @returns the current inverted matrix
  5046. */
  5047. Matrix.prototype.invert = function () {
  5048. this.invertToRef(this);
  5049. return this;
  5050. };
  5051. /**
  5052. * Sets all the matrix elements to zero
  5053. * @returns the current matrix
  5054. */
  5055. Matrix.prototype.reset = function () {
  5056. for (var index = 0; index < 16; index++) {
  5057. this.m[index] = 0.0;
  5058. }
  5059. this._markAsUpdated();
  5060. return this;
  5061. };
  5062. /**
  5063. * Adds the current matrix with a second one
  5064. * @param other defines the matrix to add
  5065. * @returns a new matrix as the addition of the current matrix and the given one
  5066. */
  5067. Matrix.prototype.add = function (other) {
  5068. var result = new Matrix();
  5069. this.addToRef(other, result);
  5070. return result;
  5071. };
  5072. /**
  5073. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5074. * @param other defines the matrix to add
  5075. * @param result defines the target matrix
  5076. * @returns the current matrix
  5077. */
  5078. Matrix.prototype.addToRef = function (other, result) {
  5079. for (var index = 0; index < 16; index++) {
  5080. result.m[index] = this.m[index] + other.m[index];
  5081. }
  5082. result._markAsUpdated();
  5083. return this;
  5084. };
  5085. /**
  5086. * Adds in place the given matrix to the current matrix
  5087. * @param other defines the second operand
  5088. * @returns the current updated matrix
  5089. */
  5090. Matrix.prototype.addToSelf = function (other) {
  5091. for (var index = 0; index < 16; index++) {
  5092. this.m[index] += other.m[index];
  5093. }
  5094. this._markAsUpdated();
  5095. return this;
  5096. };
  5097. /**
  5098. * Sets the given matrix to the current inverted Matrix
  5099. * @param other defines the target matrix
  5100. * @returns the unmodified current matrix
  5101. */
  5102. Matrix.prototype.invertToRef = function (other) {
  5103. var l1 = this.m[0];
  5104. var l2 = this.m[1];
  5105. var l3 = this.m[2];
  5106. var l4 = this.m[3];
  5107. var l5 = this.m[4];
  5108. var l6 = this.m[5];
  5109. var l7 = this.m[6];
  5110. var l8 = this.m[7];
  5111. var l9 = this.m[8];
  5112. var l10 = this.m[9];
  5113. var l11 = this.m[10];
  5114. var l12 = this.m[11];
  5115. var l13 = this.m[12];
  5116. var l14 = this.m[13];
  5117. var l15 = this.m[14];
  5118. var l16 = this.m[15];
  5119. var l17 = (l11 * l16) - (l12 * l15);
  5120. var l18 = (l10 * l16) - (l12 * l14);
  5121. var l19 = (l10 * l15) - (l11 * l14);
  5122. var l20 = (l9 * l16) - (l12 * l13);
  5123. var l21 = (l9 * l15) - (l11 * l13);
  5124. var l22 = (l9 * l14) - (l10 * l13);
  5125. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5126. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5127. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5128. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5129. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5130. var l28 = (l7 * l16) - (l8 * l15);
  5131. var l29 = (l6 * l16) - (l8 * l14);
  5132. var l30 = (l6 * l15) - (l7 * l14);
  5133. var l31 = (l5 * l16) - (l8 * l13);
  5134. var l32 = (l5 * l15) - (l7 * l13);
  5135. var l33 = (l5 * l14) - (l6 * l13);
  5136. var l34 = (l7 * l12) - (l8 * l11);
  5137. var l35 = (l6 * l12) - (l8 * l10);
  5138. var l36 = (l6 * l11) - (l7 * l10);
  5139. var l37 = (l5 * l12) - (l8 * l9);
  5140. var l38 = (l5 * l11) - (l7 * l9);
  5141. var l39 = (l5 * l10) - (l6 * l9);
  5142. other.m[0] = l23 * l27;
  5143. other.m[4] = l24 * l27;
  5144. other.m[8] = l25 * l27;
  5145. other.m[12] = l26 * l27;
  5146. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5147. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5148. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5149. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5150. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5151. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5152. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5153. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5154. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5155. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5156. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5157. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5158. other._markAsUpdated();
  5159. return this;
  5160. };
  5161. /**
  5162. * Inserts the translation vector (using 3 floats) in the current matrix
  5163. * @param x defines the 1st component of the translation
  5164. * @param y defines the 2nd component of the translation
  5165. * @param z defines the 3rd component of the translation
  5166. * @returns the current updated matrix
  5167. */
  5168. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5169. this.m[12] = x;
  5170. this.m[13] = y;
  5171. this.m[14] = z;
  5172. this._markAsUpdated();
  5173. return this;
  5174. };
  5175. /**
  5176. * Inserts the translation vector in the current matrix
  5177. * @param vector3 defines the translation to insert
  5178. * @returns the current updated matrix
  5179. */
  5180. Matrix.prototype.setTranslation = function (vector3) {
  5181. this.m[12] = vector3.x;
  5182. this.m[13] = vector3.y;
  5183. this.m[14] = vector3.z;
  5184. this._markAsUpdated();
  5185. return this;
  5186. };
  5187. /**
  5188. * Gets the translation value of the current matrix
  5189. * @returns a new Vector3 as the extracted translation from the matrix
  5190. */
  5191. Matrix.prototype.getTranslation = function () {
  5192. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5193. };
  5194. /**
  5195. * Fill a Vector3 with the extracted translation from the matrix
  5196. * @param result defines the Vector3 where to store the translation
  5197. * @returns the current matrix
  5198. */
  5199. Matrix.prototype.getTranslationToRef = function (result) {
  5200. result.x = this.m[12];
  5201. result.y = this.m[13];
  5202. result.z = this.m[14];
  5203. return this;
  5204. };
  5205. /**
  5206. * Remove rotation and scaling part from the matrix
  5207. * @returns the updated matrix
  5208. */
  5209. Matrix.prototype.removeRotationAndScaling = function () {
  5210. this.setRowFromFloats(0, 1, 0, 0, 0);
  5211. this.setRowFromFloats(1, 0, 1, 0, 0);
  5212. this.setRowFromFloats(2, 0, 0, 1, 0);
  5213. return this;
  5214. };
  5215. /**
  5216. * Multiply two matrices
  5217. * @param other defines the second operand
  5218. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5219. */
  5220. Matrix.prototype.multiply = function (other) {
  5221. var result = new Matrix();
  5222. this.multiplyToRef(other, result);
  5223. return result;
  5224. };
  5225. /**
  5226. * Copy the current matrix from the given one
  5227. * @param other defines the source matrix
  5228. * @returns the current updated matrix
  5229. */
  5230. Matrix.prototype.copyFrom = function (other) {
  5231. for (var index = 0; index < 16; index++) {
  5232. this.m[index] = other.m[index];
  5233. }
  5234. this._markAsUpdated();
  5235. return this;
  5236. };
  5237. /**
  5238. * Populates the given array from the starting index with the current matrix values
  5239. * @param array defines the target array
  5240. * @param offset defines the offset in the target array where to start storing values
  5241. * @returns the current matrix
  5242. */
  5243. Matrix.prototype.copyToArray = function (array, offset) {
  5244. if (offset === void 0) { offset = 0; }
  5245. for (var index = 0; index < 16; index++) {
  5246. array[offset + index] = this.m[index];
  5247. }
  5248. return this;
  5249. };
  5250. /**
  5251. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5252. * @param other defines the second operand
  5253. * @param result defines the matrix where to store the multiplication
  5254. * @returns the current matrix
  5255. */
  5256. Matrix.prototype.multiplyToRef = function (other, result) {
  5257. this.multiplyToArray(other, result.m, 0);
  5258. result._markAsUpdated();
  5259. return this;
  5260. };
  5261. /**
  5262. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5263. * @param other defines the second operand
  5264. * @param result defines the array where to store the multiplication
  5265. * @param offset defines the offset in the target array where to start storing values
  5266. * @returns the current matrix
  5267. */
  5268. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5269. var tm0 = this.m[0];
  5270. var tm1 = this.m[1];
  5271. var tm2 = this.m[2];
  5272. var tm3 = this.m[3];
  5273. var tm4 = this.m[4];
  5274. var tm5 = this.m[5];
  5275. var tm6 = this.m[6];
  5276. var tm7 = this.m[7];
  5277. var tm8 = this.m[8];
  5278. var tm9 = this.m[9];
  5279. var tm10 = this.m[10];
  5280. var tm11 = this.m[11];
  5281. var tm12 = this.m[12];
  5282. var tm13 = this.m[13];
  5283. var tm14 = this.m[14];
  5284. var tm15 = this.m[15];
  5285. var om0 = other.m[0];
  5286. var om1 = other.m[1];
  5287. var om2 = other.m[2];
  5288. var om3 = other.m[3];
  5289. var om4 = other.m[4];
  5290. var om5 = other.m[5];
  5291. var om6 = other.m[6];
  5292. var om7 = other.m[7];
  5293. var om8 = other.m[8];
  5294. var om9 = other.m[9];
  5295. var om10 = other.m[10];
  5296. var om11 = other.m[11];
  5297. var om12 = other.m[12];
  5298. var om13 = other.m[13];
  5299. var om14 = other.m[14];
  5300. var om15 = other.m[15];
  5301. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5302. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5303. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5304. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5305. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5306. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5307. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5308. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5309. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5310. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5311. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5312. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5313. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5314. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5315. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5316. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5317. return this;
  5318. };
  5319. /**
  5320. * Check equality between this matrix and a second one
  5321. * @param value defines the second matrix to compare
  5322. * @returns true is the current matrix and the given one values are strictly equal
  5323. */
  5324. Matrix.prototype.equals = function (value) {
  5325. return value &&
  5326. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5327. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5328. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5329. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5330. };
  5331. /**
  5332. * Clone the current matrix
  5333. * @returns a new matrix from the current matrix
  5334. */
  5335. Matrix.prototype.clone = function () {
  5336. 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]);
  5337. };
  5338. /**
  5339. * Returns the name of the current matrix class
  5340. * @returns the string "Matrix"
  5341. */
  5342. Matrix.prototype.getClassName = function () {
  5343. return "Matrix";
  5344. };
  5345. /**
  5346. * Gets the hash code of the current matrix
  5347. * @returns the hash code
  5348. */
  5349. Matrix.prototype.getHashCode = function () {
  5350. var hash = this.m[0] || 0;
  5351. for (var i = 1; i < 16; i++) {
  5352. hash = (hash * 397) ^ (this.m[i] || 0);
  5353. }
  5354. return hash;
  5355. };
  5356. /**
  5357. * Decomposes the current Matrix into a translation, rotation and scaling components
  5358. * @param scale defines the scale vector3 given as a reference to update
  5359. * @param rotation defines the rotation quaternion given as a reference to update
  5360. * @param translation defines the translation vector3 given as a reference to update
  5361. * @returns true if operation was successful
  5362. */
  5363. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5364. if (translation) {
  5365. translation.x = this.m[12];
  5366. translation.y = this.m[13];
  5367. translation.z = this.m[14];
  5368. }
  5369. scale = scale || MathTmp.Vector3[0];
  5370. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5371. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5372. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5373. if (this.determinant() <= 0) {
  5374. scale.y *= -1;
  5375. }
  5376. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5377. if (rotation) {
  5378. rotation.x = 0;
  5379. rotation.y = 0;
  5380. rotation.z = 0;
  5381. rotation.w = 1;
  5382. }
  5383. return false;
  5384. }
  5385. if (rotation) {
  5386. 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]);
  5387. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5388. }
  5389. return true;
  5390. };
  5391. /**
  5392. * Gets specific row of the matrix
  5393. * @param index defines the number of the row to get
  5394. * @returns the index-th row of the current matrix as a new Vector4
  5395. */
  5396. Matrix.prototype.getRow = function (index) {
  5397. if (index < 0 || index > 3) {
  5398. return null;
  5399. }
  5400. var i = index * 4;
  5401. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5402. };
  5403. /**
  5404. * Sets the index-th row of the current matrix to the vector4 values
  5405. * @param index defines the number of the row to set
  5406. * @param row defines the target vector4
  5407. * @returns the updated current matrix
  5408. */
  5409. Matrix.prototype.setRow = function (index, row) {
  5410. if (index < 0 || index > 3) {
  5411. return this;
  5412. }
  5413. var i = index * 4;
  5414. this.m[i + 0] = row.x;
  5415. this.m[i + 1] = row.y;
  5416. this.m[i + 2] = row.z;
  5417. this.m[i + 3] = row.w;
  5418. this._markAsUpdated();
  5419. return this;
  5420. };
  5421. /**
  5422. * Compute the transpose of the matrix
  5423. * @returns the new transposed matrix
  5424. */
  5425. Matrix.prototype.transpose = function () {
  5426. return Matrix.Transpose(this);
  5427. };
  5428. /**
  5429. * Compute the transpose of the matrix and store it in a given matrix
  5430. * @param result defines the target matrix
  5431. * @returns the current matrix
  5432. */
  5433. Matrix.prototype.transposeToRef = function (result) {
  5434. Matrix.TransposeToRef(this, result);
  5435. return this;
  5436. };
  5437. /**
  5438. * Sets the index-th row of the current matrix with the given 4 x float values
  5439. * @param index defines the row index
  5440. * @param x defines the x component to set
  5441. * @param y defines the y component to set
  5442. * @param z defines the z component to set
  5443. * @param w defines the w component to set
  5444. * @returns the updated current matrix
  5445. */
  5446. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5447. if (index < 0 || index > 3) {
  5448. return this;
  5449. }
  5450. var i = index * 4;
  5451. this.m[i + 0] = x;
  5452. this.m[i + 1] = y;
  5453. this.m[i + 2] = z;
  5454. this.m[i + 3] = w;
  5455. this._markAsUpdated();
  5456. return this;
  5457. };
  5458. /**
  5459. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5460. * @param scale defines the scale factor
  5461. * @returns a new matrix
  5462. */
  5463. Matrix.prototype.scale = function (scale) {
  5464. var result = new Matrix();
  5465. this.scaleToRef(scale, result);
  5466. return result;
  5467. };
  5468. /**
  5469. * Scale the current matrix values by a factor to a given result matrix
  5470. * @param scale defines the scale factor
  5471. * @param result defines the matrix to store the result
  5472. * @returns the current matrix
  5473. */
  5474. Matrix.prototype.scaleToRef = function (scale, result) {
  5475. for (var index = 0; index < 16; index++) {
  5476. result.m[index] = this.m[index] * scale;
  5477. }
  5478. result._markAsUpdated();
  5479. return this;
  5480. };
  5481. /**
  5482. * Scale the current matrix values by a factor and add the result to a given matrix
  5483. * @param scale defines the scale factor
  5484. * @param result defines the Matrix to store the result
  5485. * @returns the current matrix
  5486. */
  5487. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5488. for (var index = 0; index < 16; index++) {
  5489. result.m[index] += this.m[index] * scale;
  5490. }
  5491. result._markAsUpdated();
  5492. return this;
  5493. };
  5494. /**
  5495. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5496. * @param ref matrix to store the result
  5497. */
  5498. Matrix.prototype.toNormalMatrix = function (ref) {
  5499. this.invertToRef(ref);
  5500. ref.transpose();
  5501. var m = ref.m;
  5502. 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);
  5503. };
  5504. /**
  5505. * Gets only rotation part of the current matrix
  5506. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5507. */
  5508. Matrix.prototype.getRotationMatrix = function () {
  5509. var result = Matrix.Identity();
  5510. this.getRotationMatrixToRef(result);
  5511. return result;
  5512. };
  5513. /**
  5514. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5515. * @param result defines the target matrix to store data to
  5516. * @returns the current matrix
  5517. */
  5518. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5519. var m = this.m;
  5520. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5521. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5522. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5523. if (this.determinant() <= 0) {
  5524. sy *= -1;
  5525. }
  5526. if (sx === 0 || sy === 0 || sz === 0) {
  5527. Matrix.IdentityToRef(result);
  5528. }
  5529. else {
  5530. 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);
  5531. }
  5532. return this;
  5533. };
  5534. // Statics
  5535. /**
  5536. * Creates a matrix from an array
  5537. * @param array defines the source array
  5538. * @param offset defines an offset in the source array
  5539. * @returns a new Matrix set from the starting index of the given array
  5540. */
  5541. Matrix.FromArray = function (array, offset) {
  5542. var result = new Matrix();
  5543. if (!offset) {
  5544. offset = 0;
  5545. }
  5546. Matrix.FromArrayToRef(array, offset, result);
  5547. return result;
  5548. };
  5549. /**
  5550. * Copy the content of an array into a given matrix
  5551. * @param array defines the source array
  5552. * @param offset defines an offset in the source array
  5553. * @param result defines the target matrix
  5554. */
  5555. Matrix.FromArrayToRef = function (array, offset, result) {
  5556. for (var index = 0; index < 16; index++) {
  5557. result.m[index] = array[index + offset];
  5558. }
  5559. result._markAsUpdated();
  5560. };
  5561. /**
  5562. * Stores an array into a matrix after having multiplied each component by a given factor
  5563. * @param array defines the source array
  5564. * @param offset defines the offset in the source array
  5565. * @param scale defines the scaling factor
  5566. * @param result defines the target matrix
  5567. */
  5568. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5569. for (var index = 0; index < 16; index++) {
  5570. result.m[index] = array[index + offset] * scale;
  5571. }
  5572. result._markAsUpdated();
  5573. };
  5574. /**
  5575. * Stores a list of values (16) inside a given matrix
  5576. * @param initialM11 defines 1st value of 1st row
  5577. * @param initialM12 defines 2nd value of 1st row
  5578. * @param initialM13 defines 3rd value of 1st row
  5579. * @param initialM14 defines 4th value of 1st row
  5580. * @param initialM21 defines 1st value of 2nd row
  5581. * @param initialM22 defines 2nd value of 2nd row
  5582. * @param initialM23 defines 3rd value of 2nd row
  5583. * @param initialM24 defines 4th value of 2nd row
  5584. * @param initialM31 defines 1st value of 3rd row
  5585. * @param initialM32 defines 2nd value of 3rd row
  5586. * @param initialM33 defines 3rd value of 3rd row
  5587. * @param initialM34 defines 4th value of 3rd row
  5588. * @param initialM41 defines 1st value of 4th row
  5589. * @param initialM42 defines 2nd value of 4th row
  5590. * @param initialM43 defines 3rd value of 4th row
  5591. * @param initialM44 defines 4th value of 4th row
  5592. * @param result defines the target matrix
  5593. */
  5594. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5595. result.m[0] = initialM11;
  5596. result.m[1] = initialM12;
  5597. result.m[2] = initialM13;
  5598. result.m[3] = initialM14;
  5599. result.m[4] = initialM21;
  5600. result.m[5] = initialM22;
  5601. result.m[6] = initialM23;
  5602. result.m[7] = initialM24;
  5603. result.m[8] = initialM31;
  5604. result.m[9] = initialM32;
  5605. result.m[10] = initialM33;
  5606. result.m[11] = initialM34;
  5607. result.m[12] = initialM41;
  5608. result.m[13] = initialM42;
  5609. result.m[14] = initialM43;
  5610. result.m[15] = initialM44;
  5611. result._markAsUpdated();
  5612. };
  5613. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5614. /**
  5615. * Gets an identity matrix that must not be updated
  5616. */
  5617. get: function () {
  5618. return Matrix._identityReadOnly;
  5619. },
  5620. enumerable: true,
  5621. configurable: true
  5622. });
  5623. /**
  5624. * Creates new matrix from a list of values (16)
  5625. * @param initialM11 defines 1st value of 1st row
  5626. * @param initialM12 defines 2nd value of 1st row
  5627. * @param initialM13 defines 3rd value of 1st row
  5628. * @param initialM14 defines 4th value of 1st row
  5629. * @param initialM21 defines 1st value of 2nd row
  5630. * @param initialM22 defines 2nd value of 2nd row
  5631. * @param initialM23 defines 3rd value of 2nd row
  5632. * @param initialM24 defines 4th value of 2nd row
  5633. * @param initialM31 defines 1st value of 3rd row
  5634. * @param initialM32 defines 2nd value of 3rd row
  5635. * @param initialM33 defines 3rd value of 3rd row
  5636. * @param initialM34 defines 4th value of 3rd row
  5637. * @param initialM41 defines 1st value of 4th row
  5638. * @param initialM42 defines 2nd value of 4th row
  5639. * @param initialM43 defines 3rd value of 4th row
  5640. * @param initialM44 defines 4th value of 4th row
  5641. * @returns the new matrix
  5642. */
  5643. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5644. var result = new Matrix();
  5645. result.m[0] = initialM11;
  5646. result.m[1] = initialM12;
  5647. result.m[2] = initialM13;
  5648. result.m[3] = initialM14;
  5649. result.m[4] = initialM21;
  5650. result.m[5] = initialM22;
  5651. result.m[6] = initialM23;
  5652. result.m[7] = initialM24;
  5653. result.m[8] = initialM31;
  5654. result.m[9] = initialM32;
  5655. result.m[10] = initialM33;
  5656. result.m[11] = initialM34;
  5657. result.m[12] = initialM41;
  5658. result.m[13] = initialM42;
  5659. result.m[14] = initialM43;
  5660. result.m[15] = initialM44;
  5661. return result;
  5662. };
  5663. /**
  5664. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5665. * @param scale defines the scale vector3
  5666. * @param rotation defines the rotation quaternion
  5667. * @param translation defines the translation vector3
  5668. * @returns a new matrix
  5669. */
  5670. Matrix.Compose = function (scale, rotation, translation) {
  5671. var result = Matrix.Identity();
  5672. Matrix.ComposeToRef(scale, rotation, translation, result);
  5673. return result;
  5674. };
  5675. /**
  5676. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5677. * @param scale defines the scale vector3
  5678. * @param rotation defines the rotation quaternion
  5679. * @param translation defines the translation vector3
  5680. * @param result defines the target matrix
  5681. */
  5682. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5683. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5684. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5685. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5686. result.setTranslation(translation);
  5687. };
  5688. /**
  5689. * Creates a new identity matrix
  5690. * @returns a new identity matrix
  5691. */
  5692. Matrix.Identity = function () {
  5693. 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);
  5694. };
  5695. /**
  5696. * Creates a new identity matrix and stores the result in a given matrix
  5697. * @param result defines the target matrix
  5698. */
  5699. Matrix.IdentityToRef = function (result) {
  5700. 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);
  5701. };
  5702. /**
  5703. * Creates a new zero matrix
  5704. * @returns a new zero matrix
  5705. */
  5706. Matrix.Zero = function () {
  5707. 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);
  5708. };
  5709. /**
  5710. * Creates a new rotation matrix for "angle" radians around the X axis
  5711. * @param angle defines the angle (in radians) to use
  5712. * @return the new matrix
  5713. */
  5714. Matrix.RotationX = function (angle) {
  5715. var result = new Matrix();
  5716. Matrix.RotationXToRef(angle, result);
  5717. return result;
  5718. };
  5719. /**
  5720. * Creates a new matrix as the invert of a given matrix
  5721. * @param source defines the source matrix
  5722. * @returns the new matrix
  5723. */
  5724. Matrix.Invert = function (source) {
  5725. var result = new Matrix();
  5726. source.invertToRef(result);
  5727. return result;
  5728. };
  5729. /**
  5730. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5731. * @param angle defines the angle (in radians) to use
  5732. * @param result defines the target matrix
  5733. */
  5734. Matrix.RotationXToRef = function (angle, result) {
  5735. var s = Math.sin(angle);
  5736. var c = Math.cos(angle);
  5737. result.m[0] = 1.0;
  5738. result.m[15] = 1.0;
  5739. result.m[5] = c;
  5740. result.m[10] = c;
  5741. result.m[9] = -s;
  5742. result.m[6] = s;
  5743. result.m[1] = 0.0;
  5744. result.m[2] = 0.0;
  5745. result.m[3] = 0.0;
  5746. result.m[4] = 0.0;
  5747. result.m[7] = 0.0;
  5748. result.m[8] = 0.0;
  5749. result.m[11] = 0.0;
  5750. result.m[12] = 0.0;
  5751. result.m[13] = 0.0;
  5752. result.m[14] = 0.0;
  5753. result._markAsUpdated();
  5754. };
  5755. /**
  5756. * Creates a new rotation matrix for "angle" radians around the Y axis
  5757. * @param angle defines the angle (in radians) to use
  5758. * @return the new matrix
  5759. */
  5760. Matrix.RotationY = function (angle) {
  5761. var result = new Matrix();
  5762. Matrix.RotationYToRef(angle, result);
  5763. return result;
  5764. };
  5765. /**
  5766. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5767. * @param angle defines the angle (in radians) to use
  5768. * @param result defines the target matrix
  5769. */
  5770. Matrix.RotationYToRef = function (angle, result) {
  5771. var s = Math.sin(angle);
  5772. var c = Math.cos(angle);
  5773. result.m[5] = 1.0;
  5774. result.m[15] = 1.0;
  5775. result.m[0] = c;
  5776. result.m[2] = -s;
  5777. result.m[8] = s;
  5778. result.m[10] = c;
  5779. result.m[1] = 0.0;
  5780. result.m[3] = 0.0;
  5781. result.m[4] = 0.0;
  5782. result.m[6] = 0.0;
  5783. result.m[7] = 0.0;
  5784. result.m[9] = 0.0;
  5785. result.m[11] = 0.0;
  5786. result.m[12] = 0.0;
  5787. result.m[13] = 0.0;
  5788. result.m[14] = 0.0;
  5789. result._markAsUpdated();
  5790. };
  5791. /**
  5792. * Creates a new rotation matrix for "angle" radians around the Z axis
  5793. * @param angle defines the angle (in radians) to use
  5794. * @return the new matrix
  5795. */
  5796. Matrix.RotationZ = function (angle) {
  5797. var result = new Matrix();
  5798. Matrix.RotationZToRef(angle, result);
  5799. return result;
  5800. };
  5801. /**
  5802. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5803. * @param angle defines the angle (in radians) to use
  5804. * @param result defines the target matrix
  5805. */
  5806. Matrix.RotationZToRef = function (angle, result) {
  5807. var s = Math.sin(angle);
  5808. var c = Math.cos(angle);
  5809. result.m[10] = 1.0;
  5810. result.m[15] = 1.0;
  5811. result.m[0] = c;
  5812. result.m[1] = s;
  5813. result.m[4] = -s;
  5814. result.m[5] = c;
  5815. result.m[2] = 0.0;
  5816. result.m[3] = 0.0;
  5817. result.m[6] = 0.0;
  5818. result.m[7] = 0.0;
  5819. result.m[8] = 0.0;
  5820. result.m[9] = 0.0;
  5821. result.m[11] = 0.0;
  5822. result.m[12] = 0.0;
  5823. result.m[13] = 0.0;
  5824. result.m[14] = 0.0;
  5825. result._markAsUpdated();
  5826. };
  5827. /**
  5828. * Creates a new rotation matrix for "angle" radians around the given axis
  5829. * @param axis defines the axis to use
  5830. * @param angle defines the angle (in radians) to use
  5831. * @return the new matrix
  5832. */
  5833. Matrix.RotationAxis = function (axis, angle) {
  5834. var result = Matrix.Zero();
  5835. Matrix.RotationAxisToRef(axis, angle, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5840. * @param axis defines the axis to use
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5845. var s = Math.sin(-angle);
  5846. var c = Math.cos(-angle);
  5847. var c1 = 1 - c;
  5848. axis.normalize();
  5849. result.m[0] = (axis.x * axis.x) * c1 + c;
  5850. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5851. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5852. result.m[3] = 0.0;
  5853. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5854. result.m[5] = (axis.y * axis.y) * c1 + c;
  5855. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5856. result.m[7] = 0.0;
  5857. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5858. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5859. result.m[10] = (axis.z * axis.z) * c1 + c;
  5860. result.m[11] = 0.0;
  5861. result.m[15] = 1.0;
  5862. result._markAsUpdated();
  5863. };
  5864. /**
  5865. * Creates a rotation matrix
  5866. * @param yaw defines the yaw angle in radians (Y axis)
  5867. * @param pitch defines the pitch angle in radians (X axis)
  5868. * @param roll defines the roll angle in radians (X axis)
  5869. * @returns the new rotation matrix
  5870. */
  5871. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5872. var result = new Matrix();
  5873. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a rotation matrix and stores it in a given matrix
  5878. * @param yaw defines the yaw angle in radians (Y axis)
  5879. * @param pitch defines the pitch angle in radians (X axis)
  5880. * @param roll defines the roll angle in radians (X axis)
  5881. * @param result defines the target matrix
  5882. */
  5883. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5884. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5885. this._tempQuaternion.toRotationMatrix(result);
  5886. };
  5887. /**
  5888. * Creates a scaling matrix
  5889. * @param x defines the scale factor on X axis
  5890. * @param y defines the scale factor on Y axis
  5891. * @param z defines the scale factor on Z axis
  5892. * @returns the new matrix
  5893. */
  5894. Matrix.Scaling = function (x, y, z) {
  5895. var result = Matrix.Zero();
  5896. Matrix.ScalingToRef(x, y, z, result);
  5897. return result;
  5898. };
  5899. /**
  5900. * Creates a scaling matrix and stores it in a given matrix
  5901. * @param x defines the scale factor on X axis
  5902. * @param y defines the scale factor on Y axis
  5903. * @param z defines the scale factor on Z axis
  5904. * @param result defines the target matrix
  5905. */
  5906. Matrix.ScalingToRef = function (x, y, z, result) {
  5907. result.m[0] = x;
  5908. result.m[1] = 0.0;
  5909. result.m[2] = 0.0;
  5910. result.m[3] = 0.0;
  5911. result.m[4] = 0.0;
  5912. result.m[5] = y;
  5913. result.m[6] = 0.0;
  5914. result.m[7] = 0.0;
  5915. result.m[8] = 0.0;
  5916. result.m[9] = 0.0;
  5917. result.m[10] = z;
  5918. result.m[11] = 0.0;
  5919. result.m[12] = 0.0;
  5920. result.m[13] = 0.0;
  5921. result.m[14] = 0.0;
  5922. result.m[15] = 1.0;
  5923. result._markAsUpdated();
  5924. };
  5925. /**
  5926. * Creates a translation matrix
  5927. * @param x defines the translation on X axis
  5928. * @param y defines the translation on Y axis
  5929. * @param z defines the translationon Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Translation = function (x, y, z) {
  5933. var result = Matrix.Identity();
  5934. Matrix.TranslationToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a translation matrix and stores it in a given matrix
  5939. * @param x defines the translation on X axis
  5940. * @param y defines the translation on Y axis
  5941. * @param z defines the translationon Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.TranslationToRef = function (x, y, z, result) {
  5945. 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);
  5946. };
  5947. /**
  5948. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5949. * @param startValue defines the start value
  5950. * @param endValue defines the end value
  5951. * @param gradient defines the gradient factor
  5952. * @returns the new matrix
  5953. */
  5954. Matrix.Lerp = function (startValue, endValue, gradient) {
  5955. var result = Matrix.Zero();
  5956. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5957. return result;
  5958. };
  5959. /**
  5960. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5961. * @param startValue defines the start value
  5962. * @param endValue defines the end value
  5963. * @param gradient defines the gradient factor
  5964. * @param result defines the Matrix object where to store data
  5965. */
  5966. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5967. for (var index = 0; index < 16; index++) {
  5968. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5969. }
  5970. result._markAsUpdated();
  5971. };
  5972. /**
  5973. * Builds a new matrix whose values are computed by:
  5974. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5975. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5976. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5977. * @param startValue defines the first matrix
  5978. * @param endValue defines the second matrix
  5979. * @param gradient defines the gradient between the two matrices
  5980. * @returns the new matrix
  5981. */
  5982. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5983. var result = Matrix.Zero();
  5984. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5985. return result;
  5986. };
  5987. /**
  5988. * Update a matrix to values which are computed by:
  5989. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5990. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5991. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5992. * @param startValue defines the first matrix
  5993. * @param endValue defines the second matrix
  5994. * @param gradient defines the gradient between the two matrices
  5995. * @param result defines the target matrix
  5996. */
  5997. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5998. var startScale = MathTmp.Vector3[0];
  5999. var startRotation = MathTmp.Quaternion[0];
  6000. var startTranslation = MathTmp.Vector3[1];
  6001. startValue.decompose(startScale, startRotation, startTranslation);
  6002. var endScale = MathTmp.Vector3[2];
  6003. var endRotation = MathTmp.Quaternion[1];
  6004. var endTranslation = MathTmp.Vector3[3];
  6005. endValue.decompose(endScale, endRotation, endTranslation);
  6006. var resultScale = MathTmp.Vector3[4];
  6007. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6008. var resultRotation = MathTmp.Quaternion[2];
  6009. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6010. var resultTranslation = MathTmp.Vector3[5];
  6011. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6012. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6013. };
  6014. /**
  6015. * 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"
  6016. * This function works in left handed mode
  6017. * @param eye defines the final position of the entity
  6018. * @param target defines where the entity should look at
  6019. * @param up defines the up vector for the entity
  6020. * @returns the new matrix
  6021. */
  6022. Matrix.LookAtLH = function (eye, target, up) {
  6023. var result = Matrix.Zero();
  6024. Matrix.LookAtLHToRef(eye, target, up, result);
  6025. return result;
  6026. };
  6027. /**
  6028. * 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".
  6029. * This function works in left handed mode
  6030. * @param eye defines the final position of the entity
  6031. * @param target defines where the entity should look at
  6032. * @param up defines the up vector for the entity
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6036. // Z axis
  6037. target.subtractToRef(eye, this._zAxis);
  6038. this._zAxis.normalize();
  6039. // X axis
  6040. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6041. if (this._xAxis.lengthSquared() === 0) {
  6042. this._xAxis.x = 1.0;
  6043. }
  6044. else {
  6045. this._xAxis.normalize();
  6046. }
  6047. // Y axis
  6048. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6049. this._yAxis.normalize();
  6050. // Eye angles
  6051. var ex = -Vector3.Dot(this._xAxis, eye);
  6052. var ey = -Vector3.Dot(this._yAxis, eye);
  6053. var ez = -Vector3.Dot(this._zAxis, eye);
  6054. 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);
  6055. };
  6056. /**
  6057. * 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"
  6058. * This function works in right handed mode
  6059. * @param eye defines the final position of the entity
  6060. * @param target defines where the entity should look at
  6061. * @param up defines the up vector for the entity
  6062. * @returns the new matrix
  6063. */
  6064. Matrix.LookAtRH = function (eye, target, up) {
  6065. var result = Matrix.Zero();
  6066. Matrix.LookAtRHToRef(eye, target, up, result);
  6067. return result;
  6068. };
  6069. /**
  6070. * 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".
  6071. * This function works in right handed mode
  6072. * @param eye defines the final position of the entity
  6073. * @param target defines where the entity should look at
  6074. * @param up defines the up vector for the entity
  6075. * @param result defines the target matrix
  6076. */
  6077. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6078. // Z axis
  6079. eye.subtractToRef(target, this._zAxis);
  6080. this._zAxis.normalize();
  6081. // X axis
  6082. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6083. if (this._xAxis.lengthSquared() === 0) {
  6084. this._xAxis.x = 1.0;
  6085. }
  6086. else {
  6087. this._xAxis.normalize();
  6088. }
  6089. // Y axis
  6090. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6091. this._yAxis.normalize();
  6092. // Eye angles
  6093. var ex = -Vector3.Dot(this._xAxis, eye);
  6094. var ey = -Vector3.Dot(this._yAxis, eye);
  6095. var ez = -Vector3.Dot(this._zAxis, eye);
  6096. 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);
  6097. };
  6098. /**
  6099. * Create a left-handed orthographic projection matrix
  6100. * @param width defines the viewport width
  6101. * @param height defines the viewport height
  6102. * @param znear defines the near clip plane
  6103. * @param zfar defines the far clip plane
  6104. * @returns a new matrix as a left-handed orthographic projection matrix
  6105. */
  6106. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6107. var matrix = Matrix.Zero();
  6108. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6109. return matrix;
  6110. };
  6111. /**
  6112. * Store a left-handed orthographic projection to a given matrix
  6113. * @param width defines the viewport width
  6114. * @param height defines the viewport height
  6115. * @param znear defines the near clip plane
  6116. * @param zfar defines the far clip plane
  6117. * @param result defines the target matrix
  6118. */
  6119. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6120. var n = znear;
  6121. var f = zfar;
  6122. var a = 2.0 / width;
  6123. var b = 2.0 / height;
  6124. var c = 2.0 / (f - n);
  6125. var d = -(f + n) / (f - n);
  6126. 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);
  6127. };
  6128. /**
  6129. * Create a left-handed orthographic projection matrix
  6130. * @param left defines the viewport left coordinate
  6131. * @param right defines the viewport right coordinate
  6132. * @param bottom defines the viewport bottom coordinate
  6133. * @param top defines the viewport top coordinate
  6134. * @param znear defines the near clip plane
  6135. * @param zfar defines the far clip plane
  6136. * @returns a new matrix as a left-handed orthographic projection matrix
  6137. */
  6138. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6139. var matrix = Matrix.Zero();
  6140. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6141. return matrix;
  6142. };
  6143. /**
  6144. * Stores a left-handed orthographic projection into a given matrix
  6145. * @param left defines the viewport left coordinate
  6146. * @param right defines the viewport right coordinate
  6147. * @param bottom defines the viewport bottom coordinate
  6148. * @param top defines the viewport top coordinate
  6149. * @param znear defines the near clip plane
  6150. * @param zfar defines the far clip plane
  6151. * @param result defines the target matrix
  6152. */
  6153. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6154. var n = znear;
  6155. var f = zfar;
  6156. var a = 2.0 / (right - left);
  6157. var b = 2.0 / (top - bottom);
  6158. var c = 2.0 / (f - n);
  6159. var d = -(f + n) / (f - n);
  6160. var i0 = (left + right) / (left - right);
  6161. var i1 = (top + bottom) / (bottom - top);
  6162. 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);
  6163. };
  6164. /**
  6165. * Creates a right-handed orthographic projection matrix
  6166. * @param left defines the viewport left coordinate
  6167. * @param right defines the viewport right coordinate
  6168. * @param bottom defines the viewport bottom coordinate
  6169. * @param top defines the viewport top coordinate
  6170. * @param znear defines the near clip plane
  6171. * @param zfar defines the far clip plane
  6172. * @returns a new matrix as a right-handed orthographic projection matrix
  6173. */
  6174. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6175. var matrix = Matrix.Zero();
  6176. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6177. return matrix;
  6178. };
  6179. /**
  6180. * Stores a right-handed orthographic projection into a given matrix
  6181. * @param left defines the viewport left coordinate
  6182. * @param right defines the viewport right coordinate
  6183. * @param bottom defines the viewport bottom coordinate
  6184. * @param top defines the viewport top coordinate
  6185. * @param znear defines the near clip plane
  6186. * @param zfar defines the far clip plane
  6187. * @param result defines the target matrix
  6188. */
  6189. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6190. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6191. result.m[10] *= -1.0;
  6192. };
  6193. /**
  6194. * Creates a left-handed perspective projection matrix
  6195. * @param width defines the viewport width
  6196. * @param height defines the viewport height
  6197. * @param znear defines the near clip plane
  6198. * @param zfar defines the far clip plane
  6199. * @returns a new matrix as a left-handed perspective projection matrix
  6200. */
  6201. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6202. var matrix = Matrix.Zero();
  6203. var n = znear;
  6204. var f = zfar;
  6205. var a = 2.0 * n / width;
  6206. var b = 2.0 * n / height;
  6207. var c = (f + n) / (f - n);
  6208. var d = -2.0 * f * n / (f - n);
  6209. 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);
  6210. return matrix;
  6211. };
  6212. /**
  6213. * Creates a left-handed perspective projection matrix
  6214. * @param fov defines the horizontal field of view
  6215. * @param aspect defines the aspect ratio
  6216. * @param znear defines the near clip plane
  6217. * @param zfar defines the far clip plane
  6218. * @returns a new matrix as a left-handed perspective projection matrix
  6219. */
  6220. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6221. var matrix = Matrix.Zero();
  6222. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6223. return matrix;
  6224. };
  6225. /**
  6226. * Stores a left-handed perspective projection into a given matrix
  6227. * @param fov defines the horizontal field of view
  6228. * @param aspect defines the aspect ratio
  6229. * @param znear defines the near clip plane
  6230. * @param zfar defines the far clip plane
  6231. * @param result defines the target matrix
  6232. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6233. */
  6234. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6235. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6236. var n = znear;
  6237. var f = zfar;
  6238. var t = 1.0 / (Math.tan(fov * 0.5));
  6239. var a = isVerticalFovFixed ? (t / aspect) : t;
  6240. var b = isVerticalFovFixed ? t : (t * aspect);
  6241. var c = (f + n) / (f - n);
  6242. var d = -2.0 * f * n / (f - n);
  6243. 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);
  6244. };
  6245. /**
  6246. * Creates a right-handed perspective projection matrix
  6247. * @param fov defines the horizontal field of view
  6248. * @param aspect defines the aspect ratio
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a right-handed perspective projection matrix
  6252. */
  6253. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Stores a right-handed perspective projection into a given matrix
  6260. * @param fov defines the horizontal field of view
  6261. * @param aspect defines the aspect ratio
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @param result defines the target matrix
  6265. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6266. */
  6267. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6268. //alternatively this could be expressed as:
  6269. // m = PerspectiveFovLHToRef
  6270. // m[10] *= -1.0;
  6271. // m[11] *= -1.0;
  6272. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6273. var n = znear;
  6274. var f = zfar;
  6275. var t = 1.0 / (Math.tan(fov * 0.5));
  6276. var a = isVerticalFovFixed ? (t / aspect) : t;
  6277. var b = isVerticalFovFixed ? t : (t * aspect);
  6278. var c = -(f + n) / (f - n);
  6279. var d = -2 * f * n / (f - n);
  6280. 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);
  6281. };
  6282. /**
  6283. * Stores a perspective projection for WebVR info a given matrix
  6284. * @param fov defines the field of view
  6285. * @param znear defines the near clip plane
  6286. * @param zfar defines the far clip plane
  6287. * @param result defines the target matrix
  6288. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6289. */
  6290. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6291. if (rightHanded === void 0) { rightHanded = false; }
  6292. var rightHandedFactor = rightHanded ? -1 : 1;
  6293. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6294. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6295. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6296. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6297. var xScale = 2.0 / (leftTan + rightTan);
  6298. var yScale = 2.0 / (upTan + downTan);
  6299. result.m[0] = xScale;
  6300. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6301. result.m[5] = yScale;
  6302. result.m[6] = result.m[7] = 0.0;
  6303. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6304. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6305. result.m[10] = -zfar / (znear - zfar);
  6306. result.m[11] = 1.0 * rightHandedFactor;
  6307. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6308. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6309. result._markAsUpdated();
  6310. };
  6311. /**
  6312. * Computes a complete transformation matrix
  6313. * @param viewport defines the viewport to use
  6314. * @param world defines the world matrix
  6315. * @param view defines the view matrix
  6316. * @param projection defines the projection matrix
  6317. * @param zmin defines the near clip plane
  6318. * @param zmax defines the far clip plane
  6319. * @returns the transformation matrix
  6320. */
  6321. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6322. var cw = viewport.width;
  6323. var ch = viewport.height;
  6324. var cx = viewport.x;
  6325. var cy = viewport.y;
  6326. 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);
  6327. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6328. };
  6329. /**
  6330. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6331. * @param matrix defines the matrix to use
  6332. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6333. */
  6334. Matrix.GetAsMatrix2x2 = function (matrix) {
  6335. return new Float32Array([
  6336. matrix.m[0], matrix.m[1],
  6337. matrix.m[4], matrix.m[5]
  6338. ]);
  6339. };
  6340. /**
  6341. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6342. * @param matrix defines the matrix to use
  6343. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6344. */
  6345. Matrix.GetAsMatrix3x3 = function (matrix) {
  6346. return new Float32Array([
  6347. matrix.m[0], matrix.m[1], matrix.m[2],
  6348. matrix.m[4], matrix.m[5], matrix.m[6],
  6349. matrix.m[8], matrix.m[9], matrix.m[10]
  6350. ]);
  6351. };
  6352. /**
  6353. * Compute the transpose of a given matrix
  6354. * @param matrix defines the matrix to transpose
  6355. * @returns the new matrix
  6356. */
  6357. Matrix.Transpose = function (matrix) {
  6358. var result = new Matrix();
  6359. Matrix.TransposeToRef(matrix, result);
  6360. return result;
  6361. };
  6362. /**
  6363. * Compute the transpose of a matrix and store it in a target matrix
  6364. * @param matrix defines the matrix to transpose
  6365. * @param result defines the target matrix
  6366. */
  6367. Matrix.TransposeToRef = function (matrix, result) {
  6368. result.m[0] = matrix.m[0];
  6369. result.m[1] = matrix.m[4];
  6370. result.m[2] = matrix.m[8];
  6371. result.m[3] = matrix.m[12];
  6372. result.m[4] = matrix.m[1];
  6373. result.m[5] = matrix.m[5];
  6374. result.m[6] = matrix.m[9];
  6375. result.m[7] = matrix.m[13];
  6376. result.m[8] = matrix.m[2];
  6377. result.m[9] = matrix.m[6];
  6378. result.m[10] = matrix.m[10];
  6379. result.m[11] = matrix.m[14];
  6380. result.m[12] = matrix.m[3];
  6381. result.m[13] = matrix.m[7];
  6382. result.m[14] = matrix.m[11];
  6383. result.m[15] = matrix.m[15];
  6384. };
  6385. /**
  6386. * Computes a reflection matrix from a plane
  6387. * @param plane defines the reflection plane
  6388. * @returns a new matrix
  6389. */
  6390. Matrix.Reflection = function (plane) {
  6391. var matrix = new Matrix();
  6392. Matrix.ReflectionToRef(plane, matrix);
  6393. return matrix;
  6394. };
  6395. /**
  6396. * Computes a reflection matrix from a plane
  6397. * @param plane defines the reflection plane
  6398. * @param result defines the target matrix
  6399. */
  6400. Matrix.ReflectionToRef = function (plane, result) {
  6401. plane.normalize();
  6402. var x = plane.normal.x;
  6403. var y = plane.normal.y;
  6404. var z = plane.normal.z;
  6405. var temp = -2 * x;
  6406. var temp2 = -2 * y;
  6407. var temp3 = -2 * z;
  6408. result.m[0] = (temp * x) + 1;
  6409. result.m[1] = temp2 * x;
  6410. result.m[2] = temp3 * x;
  6411. result.m[3] = 0.0;
  6412. result.m[4] = temp * y;
  6413. result.m[5] = (temp2 * y) + 1;
  6414. result.m[6] = temp3 * y;
  6415. result.m[7] = 0.0;
  6416. result.m[8] = temp * z;
  6417. result.m[9] = temp2 * z;
  6418. result.m[10] = (temp3 * z) + 1;
  6419. result.m[11] = 0.0;
  6420. result.m[12] = temp * plane.d;
  6421. result.m[13] = temp2 * plane.d;
  6422. result.m[14] = temp3 * plane.d;
  6423. result.m[15] = 1.0;
  6424. result._markAsUpdated();
  6425. };
  6426. /**
  6427. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6428. * @param xaxis defines the value of the 1st axis
  6429. * @param yaxis defines the value of the 2nd axis
  6430. * @param zaxis defines the value of the 3rd axis
  6431. * @param result defines the target matrix
  6432. */
  6433. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6434. result.m[0] = xaxis.x;
  6435. result.m[1] = xaxis.y;
  6436. result.m[2] = xaxis.z;
  6437. result.m[3] = 0.0;
  6438. result.m[4] = yaxis.x;
  6439. result.m[5] = yaxis.y;
  6440. result.m[6] = yaxis.z;
  6441. result.m[7] = 0.0;
  6442. result.m[8] = zaxis.x;
  6443. result.m[9] = zaxis.y;
  6444. result.m[10] = zaxis.z;
  6445. result.m[11] = 0.0;
  6446. result.m[12] = 0.0;
  6447. result.m[13] = 0.0;
  6448. result.m[14] = 0.0;
  6449. result.m[15] = 1.0;
  6450. result._markAsUpdated();
  6451. };
  6452. /**
  6453. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6454. * @param quat defines the quaternion to use
  6455. * @param result defines the target matrix
  6456. */
  6457. Matrix.FromQuaternionToRef = function (quat, result) {
  6458. var xx = quat.x * quat.x;
  6459. var yy = quat.y * quat.y;
  6460. var zz = quat.z * quat.z;
  6461. var xy = quat.x * quat.y;
  6462. var zw = quat.z * quat.w;
  6463. var zx = quat.z * quat.x;
  6464. var yw = quat.y * quat.w;
  6465. var yz = quat.y * quat.z;
  6466. var xw = quat.x * quat.w;
  6467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6468. result.m[1] = 2.0 * (xy + zw);
  6469. result.m[2] = 2.0 * (zx - yw);
  6470. result.m[3] = 0.0;
  6471. result.m[4] = 2.0 * (xy - zw);
  6472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6473. result.m[6] = 2.0 * (yz + xw);
  6474. result.m[7] = 0.0;
  6475. result.m[8] = 2.0 * (zx + yw);
  6476. result.m[9] = 2.0 * (yz - xw);
  6477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6478. result.m[11] = 0.0;
  6479. result.m[12] = 0.0;
  6480. result.m[13] = 0.0;
  6481. result.m[14] = 0.0;
  6482. result.m[15] = 1.0;
  6483. result._markAsUpdated();
  6484. };
  6485. Matrix._tempQuaternion = new Quaternion();
  6486. Matrix._xAxis = Vector3.Zero();
  6487. Matrix._yAxis = Vector3.Zero();
  6488. Matrix._zAxis = Vector3.Zero();
  6489. Matrix._updateFlagSeed = 0;
  6490. Matrix._identityReadOnly = Matrix.Identity();
  6491. return Matrix;
  6492. }());
  6493. BABYLON.Matrix = Matrix;
  6494. var Plane = /** @class */ (function () {
  6495. /**
  6496. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6497. */
  6498. function Plane(a, b, c, d) {
  6499. this.normal = new Vector3(a, b, c);
  6500. this.d = d;
  6501. }
  6502. /**
  6503. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6504. */
  6505. Plane.prototype.asArray = function () {
  6506. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6507. };
  6508. // Methods
  6509. /**
  6510. * Returns a new plane copied from the current Plane.
  6511. */
  6512. Plane.prototype.clone = function () {
  6513. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6514. };
  6515. /**
  6516. * Returns the string "Plane".
  6517. */
  6518. Plane.prototype.getClassName = function () {
  6519. return "Plane";
  6520. };
  6521. /**
  6522. * Returns the Plane hash code.
  6523. */
  6524. Plane.prototype.getHashCode = function () {
  6525. var hash = this.normal.getHashCode();
  6526. hash = (hash * 397) ^ (this.d || 0);
  6527. return hash;
  6528. };
  6529. /**
  6530. * Normalize the current Plane in place.
  6531. * Returns the updated Plane.
  6532. */
  6533. Plane.prototype.normalize = function () {
  6534. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6535. var magnitude = 0.0;
  6536. if (norm !== 0) {
  6537. magnitude = 1.0 / norm;
  6538. }
  6539. this.normal.x *= magnitude;
  6540. this.normal.y *= magnitude;
  6541. this.normal.z *= magnitude;
  6542. this.d *= magnitude;
  6543. return this;
  6544. };
  6545. /**
  6546. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6547. */
  6548. Plane.prototype.transform = function (transformation) {
  6549. var transposedMatrix = Matrix.Transpose(transformation);
  6550. var x = this.normal.x;
  6551. var y = this.normal.y;
  6552. var z = this.normal.z;
  6553. var d = this.d;
  6554. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6555. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6556. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6557. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6558. return new Plane(normalX, normalY, normalZ, finalD);
  6559. };
  6560. /**
  6561. * Returns the dot product (float) of the point coordinates and the plane normal.
  6562. */
  6563. Plane.prototype.dotCoordinate = function (point) {
  6564. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6565. };
  6566. /**
  6567. * Updates the current Plane from the plane defined by the three given points.
  6568. * Returns the updated Plane.
  6569. */
  6570. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6571. var x1 = point2.x - point1.x;
  6572. var y1 = point2.y - point1.y;
  6573. var z1 = point2.z - point1.z;
  6574. var x2 = point3.x - point1.x;
  6575. var y2 = point3.y - point1.y;
  6576. var z2 = point3.z - point1.z;
  6577. var yz = (y1 * z2) - (z1 * y2);
  6578. var xz = (z1 * x2) - (x1 * z2);
  6579. var xy = (x1 * y2) - (y1 * x2);
  6580. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6581. var invPyth;
  6582. if (pyth !== 0) {
  6583. invPyth = 1.0 / pyth;
  6584. }
  6585. else {
  6586. invPyth = 0.0;
  6587. }
  6588. this.normal.x = yz * invPyth;
  6589. this.normal.y = xz * invPyth;
  6590. this.normal.z = xy * invPyth;
  6591. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6592. return this;
  6593. };
  6594. /**
  6595. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6596. */
  6597. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6598. var dot = Vector3.Dot(this.normal, direction);
  6599. return (dot <= epsilon);
  6600. };
  6601. /**
  6602. * Returns the signed distance (float) from the given point to the Plane.
  6603. */
  6604. Plane.prototype.signedDistanceTo = function (point) {
  6605. return Vector3.Dot(point, this.normal) + this.d;
  6606. };
  6607. // Statics
  6608. /**
  6609. * Returns a new Plane from the given array.
  6610. */
  6611. Plane.FromArray = function (array) {
  6612. return new Plane(array[0], array[1], array[2], array[3]);
  6613. };
  6614. /**
  6615. * Returns a new Plane defined by the three given points.
  6616. */
  6617. Plane.FromPoints = function (point1, point2, point3) {
  6618. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6619. result.copyFromPoints(point1, point2, point3);
  6620. return result;
  6621. };
  6622. /**
  6623. * Returns a new Plane the normal vector to this plane at the given origin point.
  6624. * Note : the vector "normal" is updated because normalized.
  6625. */
  6626. Plane.FromPositionAndNormal = function (origin, normal) {
  6627. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6628. normal.normalize();
  6629. result.normal = normal;
  6630. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6631. return result;
  6632. };
  6633. /**
  6634. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6635. */
  6636. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6637. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6638. return Vector3.Dot(point, normal) + d;
  6639. };
  6640. return Plane;
  6641. }());
  6642. BABYLON.Plane = Plane;
  6643. var Viewport = /** @class */ (function () {
  6644. /**
  6645. * Creates a Viewport object located at (x, y) and sized (width, height).
  6646. */
  6647. function Viewport(x, y, width, height) {
  6648. this.x = x;
  6649. this.y = y;
  6650. this.width = width;
  6651. this.height = height;
  6652. }
  6653. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6654. if (renderWidthOrEngine.getRenderWidth) {
  6655. var engine = renderWidthOrEngine;
  6656. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6657. }
  6658. var renderWidth = renderWidthOrEngine;
  6659. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6660. };
  6661. /**
  6662. * Returns a new Viewport copied from the current one.
  6663. */
  6664. Viewport.prototype.clone = function () {
  6665. return new Viewport(this.x, this.y, this.width, this.height);
  6666. };
  6667. return Viewport;
  6668. }());
  6669. BABYLON.Viewport = Viewport;
  6670. var Frustum = /** @class */ (function () {
  6671. function Frustum() {
  6672. }
  6673. /**
  6674. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6675. */
  6676. Frustum.GetPlanes = function (transform) {
  6677. var frustumPlanes = [];
  6678. for (var index = 0; index < 6; index++) {
  6679. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6680. }
  6681. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6682. return frustumPlanes;
  6683. };
  6684. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6685. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6686. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6687. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6688. frustumPlane.d = transform.m[15] + transform.m[14];
  6689. frustumPlane.normalize();
  6690. };
  6691. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6692. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6693. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6694. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6695. frustumPlane.d = transform.m[15] - transform.m[14];
  6696. frustumPlane.normalize();
  6697. };
  6698. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6699. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6700. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6701. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6702. frustumPlane.d = transform.m[15] + transform.m[12];
  6703. frustumPlane.normalize();
  6704. };
  6705. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6706. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6707. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6708. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6709. frustumPlane.d = transform.m[15] - transform.m[12];
  6710. frustumPlane.normalize();
  6711. };
  6712. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6713. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6714. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6715. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6716. frustumPlane.d = transform.m[15] - transform.m[13];
  6717. frustumPlane.normalize();
  6718. };
  6719. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6720. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6721. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6722. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6723. frustumPlane.d = transform.m[15] + transform.m[13];
  6724. frustumPlane.normalize();
  6725. };
  6726. /**
  6727. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6728. */
  6729. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6730. // Near
  6731. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6732. // Far
  6733. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6734. // Left
  6735. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6736. // Right
  6737. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6738. // Top
  6739. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6740. // Bottom
  6741. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6742. };
  6743. return Frustum;
  6744. }());
  6745. BABYLON.Frustum = Frustum;
  6746. /** Defines supported spaces */
  6747. var Space;
  6748. (function (Space) {
  6749. /** Local (object) space */
  6750. Space[Space["LOCAL"] = 0] = "LOCAL";
  6751. /** World space */
  6752. Space[Space["WORLD"] = 1] = "WORLD";
  6753. /** Bone space */
  6754. Space[Space["BONE"] = 2] = "BONE";
  6755. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6756. /** Defines the 3 main axes */
  6757. var Axis = /** @class */ (function () {
  6758. function Axis() {
  6759. }
  6760. /** X axis */
  6761. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6762. /** Y axis */
  6763. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6764. /** Z axis */
  6765. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6766. return Axis;
  6767. }());
  6768. BABYLON.Axis = Axis;
  6769. ;
  6770. var BezierCurve = /** @class */ (function () {
  6771. function BezierCurve() {
  6772. }
  6773. /**
  6774. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6775. */
  6776. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6777. // Extract X (which is equal to time here)
  6778. var f0 = 1 - 3 * x2 + 3 * x1;
  6779. var f1 = 3 * x2 - 6 * x1;
  6780. var f2 = 3 * x1;
  6781. var refinedT = t;
  6782. for (var i = 0; i < 5; i++) {
  6783. var refinedT2 = refinedT * refinedT;
  6784. var refinedT3 = refinedT2 * refinedT;
  6785. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6786. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6787. refinedT -= (x - t) * slope;
  6788. refinedT = Math.min(1, Math.max(0, refinedT));
  6789. }
  6790. // Resolve cubic bezier for the given x
  6791. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6792. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6793. Math.pow(refinedT, 3);
  6794. };
  6795. return BezierCurve;
  6796. }());
  6797. BABYLON.BezierCurve = BezierCurve;
  6798. /**
  6799. * Defines potential orientation for back face culling
  6800. */
  6801. var Orientation;
  6802. (function (Orientation) {
  6803. /**
  6804. * Clockwise
  6805. */
  6806. Orientation[Orientation["CW"] = 0] = "CW";
  6807. /** Counter clockwise */
  6808. Orientation[Orientation["CCW"] = 1] = "CCW";
  6809. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6810. /**
  6811. * Defines angle representation
  6812. */
  6813. var Angle = /** @class */ (function () {
  6814. /**
  6815. * Creates an Angle object of "radians" radians (float).
  6816. */
  6817. function Angle(radians) {
  6818. this._radians = radians;
  6819. if (this._radians < 0.0)
  6820. this._radians += (2.0 * Math.PI);
  6821. }
  6822. /**
  6823. * Get value in degrees
  6824. * @returns the Angle value in degrees (float)
  6825. */
  6826. Angle.prototype.degrees = function () {
  6827. return this._radians * 180.0 / Math.PI;
  6828. };
  6829. /**
  6830. * Get value in radians
  6831. * @returns the Angle value in radians (float)
  6832. */
  6833. Angle.prototype.radians = function () {
  6834. return this._radians;
  6835. };
  6836. /**
  6837. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6838. * @param a defines first vector
  6839. * @param b defines second vector
  6840. * @returns a new Angle
  6841. */
  6842. Angle.BetweenTwoPoints = function (a, b) {
  6843. var delta = b.subtract(a);
  6844. var theta = Math.atan2(delta.y, delta.x);
  6845. return new Angle(theta);
  6846. };
  6847. /**
  6848. * Gets a new Angle object from the given float in radians
  6849. * @param radians defines the angle value in radians
  6850. * @returns a new Angle
  6851. */
  6852. Angle.FromRadians = function (radians) {
  6853. return new Angle(radians);
  6854. };
  6855. /**
  6856. * Gets a new Angle object from the given float in degrees
  6857. * @param degrees defines the angle value in degrees
  6858. * @returns a new Angle
  6859. */
  6860. Angle.FromDegrees = function (degrees) {
  6861. return new Angle(degrees * Math.PI / 180.0);
  6862. };
  6863. return Angle;
  6864. }());
  6865. BABYLON.Angle = Angle;
  6866. var Arc2 = /** @class */ (function () {
  6867. /**
  6868. * Creates an Arc object from the three given points : start, middle and end.
  6869. */
  6870. function Arc2(startPoint, midPoint, endPoint) {
  6871. this.startPoint = startPoint;
  6872. this.midPoint = midPoint;
  6873. this.endPoint = endPoint;
  6874. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6875. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6876. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6877. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6878. 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);
  6879. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6880. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6881. var a1 = this.startAngle.degrees();
  6882. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6883. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6884. // angles correction
  6885. if (a2 - a1 > +180.0)
  6886. a2 -= 360.0;
  6887. if (a2 - a1 < -180.0)
  6888. a2 += 360.0;
  6889. if (a3 - a2 > +180.0)
  6890. a3 -= 360.0;
  6891. if (a3 - a2 < -180.0)
  6892. a3 += 360.0;
  6893. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6894. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6895. }
  6896. return Arc2;
  6897. }());
  6898. BABYLON.Arc2 = Arc2;
  6899. var Path2 = /** @class */ (function () {
  6900. /**
  6901. * Creates a Path2 object from the starting 2D coordinates x and y.
  6902. */
  6903. function Path2(x, y) {
  6904. this._points = new Array();
  6905. this._length = 0.0;
  6906. this.closed = false;
  6907. this._points.push(new Vector2(x, y));
  6908. }
  6909. /**
  6910. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6911. * Returns the updated Path2.
  6912. */
  6913. Path2.prototype.addLineTo = function (x, y) {
  6914. if (this.closed) {
  6915. return this;
  6916. }
  6917. var newPoint = new Vector2(x, y);
  6918. var previousPoint = this._points[this._points.length - 1];
  6919. this._points.push(newPoint);
  6920. this._length += newPoint.subtract(previousPoint).length();
  6921. return this;
  6922. };
  6923. /**
  6924. * 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.
  6925. * Returns the updated Path2.
  6926. */
  6927. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6928. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6929. if (this.closed) {
  6930. return this;
  6931. }
  6932. var startPoint = this._points[this._points.length - 1];
  6933. var midPoint = new Vector2(midX, midY);
  6934. var endPoint = new Vector2(endX, endY);
  6935. var arc = new Arc2(startPoint, midPoint, endPoint);
  6936. var increment = arc.angle.radians() / numberOfSegments;
  6937. if (arc.orientation === Orientation.CW)
  6938. increment *= -1;
  6939. var currentAngle = arc.startAngle.radians() + increment;
  6940. for (var i = 0; i < numberOfSegments; i++) {
  6941. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6942. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6943. this.addLineTo(x, y);
  6944. currentAngle += increment;
  6945. }
  6946. return this;
  6947. };
  6948. /**
  6949. * Closes the Path2.
  6950. * Returns the Path2.
  6951. */
  6952. Path2.prototype.close = function () {
  6953. this.closed = true;
  6954. return this;
  6955. };
  6956. /**
  6957. * Returns the Path2 total length (float).
  6958. */
  6959. Path2.prototype.length = function () {
  6960. var result = this._length;
  6961. if (!this.closed) {
  6962. var lastPoint = this._points[this._points.length - 1];
  6963. var firstPoint = this._points[0];
  6964. result += (firstPoint.subtract(lastPoint).length());
  6965. }
  6966. return result;
  6967. };
  6968. /**
  6969. * Returns the Path2 internal array of points.
  6970. */
  6971. Path2.prototype.getPoints = function () {
  6972. return this._points;
  6973. };
  6974. /**
  6975. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6976. */
  6977. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6978. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6979. return Vector2.Zero();
  6980. }
  6981. var lengthPosition = normalizedLengthPosition * this.length();
  6982. var previousOffset = 0;
  6983. for (var i = 0; i < this._points.length; i++) {
  6984. var j = (i + 1) % this._points.length;
  6985. var a = this._points[i];
  6986. var b = this._points[j];
  6987. var bToA = b.subtract(a);
  6988. var nextOffset = (bToA.length() + previousOffset);
  6989. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6990. var dir = bToA.normalize();
  6991. var localOffset = lengthPosition - previousOffset;
  6992. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6993. }
  6994. previousOffset = nextOffset;
  6995. }
  6996. return Vector2.Zero();
  6997. };
  6998. /**
  6999. * Returns a new Path2 starting at the coordinates (x, y).
  7000. */
  7001. Path2.StartingAt = function (x, y) {
  7002. return new Path2(x, y);
  7003. };
  7004. return Path2;
  7005. }());
  7006. BABYLON.Path2 = Path2;
  7007. var Path3D = /** @class */ (function () {
  7008. /**
  7009. * new Path3D(path, normal, raw)
  7010. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7011. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7012. * path : an array of Vector3, the curve axis of the Path3D
  7013. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7014. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7015. */
  7016. function Path3D(path, firstNormal, raw) {
  7017. if (firstNormal === void 0) { firstNormal = null; }
  7018. this.path = path;
  7019. this._curve = new Array();
  7020. this._distances = new Array();
  7021. this._tangents = new Array();
  7022. this._normals = new Array();
  7023. this._binormals = new Array();
  7024. for (var p = 0; p < path.length; p++) {
  7025. this._curve[p] = path[p].clone(); // hard copy
  7026. }
  7027. this._raw = raw || false;
  7028. this._compute(firstNormal);
  7029. }
  7030. /**
  7031. * Returns the Path3D array of successive Vector3 designing its curve.
  7032. */
  7033. Path3D.prototype.getCurve = function () {
  7034. return this._curve;
  7035. };
  7036. /**
  7037. * Returns an array populated with tangent vectors on each Path3D curve point.
  7038. */
  7039. Path3D.prototype.getTangents = function () {
  7040. return this._tangents;
  7041. };
  7042. /**
  7043. * Returns an array populated with normal vectors on each Path3D curve point.
  7044. */
  7045. Path3D.prototype.getNormals = function () {
  7046. return this._normals;
  7047. };
  7048. /**
  7049. * Returns an array populated with binormal vectors on each Path3D curve point.
  7050. */
  7051. Path3D.prototype.getBinormals = function () {
  7052. return this._binormals;
  7053. };
  7054. /**
  7055. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7056. */
  7057. Path3D.prototype.getDistances = function () {
  7058. return this._distances;
  7059. };
  7060. /**
  7061. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7062. * Returns the same object updated.
  7063. */
  7064. Path3D.prototype.update = function (path, firstNormal) {
  7065. if (firstNormal === void 0) { firstNormal = null; }
  7066. for (var p = 0; p < path.length; p++) {
  7067. this._curve[p].x = path[p].x;
  7068. this._curve[p].y = path[p].y;
  7069. this._curve[p].z = path[p].z;
  7070. }
  7071. this._compute(firstNormal);
  7072. return this;
  7073. };
  7074. // private function compute() : computes tangents, normals and binormals
  7075. Path3D.prototype._compute = function (firstNormal) {
  7076. var l = this._curve.length;
  7077. // first and last tangents
  7078. this._tangents[0] = this._getFirstNonNullVector(0);
  7079. if (!this._raw) {
  7080. this._tangents[0].normalize();
  7081. }
  7082. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7083. if (!this._raw) {
  7084. this._tangents[l - 1].normalize();
  7085. }
  7086. // normals and binormals at first point : arbitrary vector with _normalVector()
  7087. var tg0 = this._tangents[0];
  7088. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7089. this._normals[0] = pp0;
  7090. if (!this._raw) {
  7091. this._normals[0].normalize();
  7092. }
  7093. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7094. if (!this._raw) {
  7095. this._binormals[0].normalize();
  7096. }
  7097. this._distances[0] = 0.0;
  7098. // normals and binormals : next points
  7099. var prev; // previous vector (segment)
  7100. var cur; // current vector (segment)
  7101. var curTang; // current tangent
  7102. // previous normal
  7103. var prevBinor; // previous binormal
  7104. for (var i = 1; i < l; i++) {
  7105. // tangents
  7106. prev = this._getLastNonNullVector(i);
  7107. if (i < l - 1) {
  7108. cur = this._getFirstNonNullVector(i);
  7109. this._tangents[i] = prev.add(cur);
  7110. this._tangents[i].normalize();
  7111. }
  7112. this._distances[i] = this._distances[i - 1] + prev.length();
  7113. // normals and binormals
  7114. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7115. curTang = this._tangents[i];
  7116. prevBinor = this._binormals[i - 1];
  7117. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7118. if (!this._raw) {
  7119. this._normals[i].normalize();
  7120. }
  7121. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7122. if (!this._raw) {
  7123. this._binormals[i].normalize();
  7124. }
  7125. }
  7126. };
  7127. // private function getFirstNonNullVector(index)
  7128. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7129. Path3D.prototype._getFirstNonNullVector = function (index) {
  7130. var i = 1;
  7131. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7132. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7133. i++;
  7134. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7135. }
  7136. return nNVector;
  7137. };
  7138. // private function getLastNonNullVector(index)
  7139. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7140. Path3D.prototype._getLastNonNullVector = function (index) {
  7141. var i = 1;
  7142. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7143. while (nLVector.length() === 0 && index > i + 1) {
  7144. i++;
  7145. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7146. }
  7147. return nLVector;
  7148. };
  7149. // private function normalVector(v0, vt, va) :
  7150. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7151. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7152. Path3D.prototype._normalVector = function (v0, vt, va) {
  7153. var normal0;
  7154. var tgl = vt.length();
  7155. if (tgl === 0.0) {
  7156. tgl = 1.0;
  7157. }
  7158. if (va === undefined || va === null) {
  7159. var point;
  7160. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7161. point = new Vector3(0.0, -1.0, 0.0);
  7162. }
  7163. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7164. point = new Vector3(1.0, 0.0, 0.0);
  7165. }
  7166. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7167. point = new Vector3(0.0, 0.0, 1.0);
  7168. }
  7169. else {
  7170. point = Vector3.Zero();
  7171. }
  7172. normal0 = Vector3.Cross(vt, point);
  7173. }
  7174. else {
  7175. normal0 = Vector3.Cross(vt, va);
  7176. Vector3.CrossToRef(normal0, vt, normal0);
  7177. }
  7178. normal0.normalize();
  7179. return normal0;
  7180. };
  7181. return Path3D;
  7182. }());
  7183. BABYLON.Path3D = Path3D;
  7184. var Curve3 = /** @class */ (function () {
  7185. /**
  7186. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7187. * A Curve3 is designed from a series of successive Vector3.
  7188. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7189. */
  7190. function Curve3(points) {
  7191. this._length = 0.0;
  7192. this._points = points;
  7193. this._length = this._computeLength(points);
  7194. }
  7195. /**
  7196. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7197. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7198. * @param v1 (Vector3) the control point
  7199. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7200. * @param nbPoints (integer) the wanted number of points in the curve
  7201. */
  7202. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7203. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7204. var bez = new Array();
  7205. var equation = function (t, val0, val1, val2) {
  7206. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7207. return res;
  7208. };
  7209. for (var i = 0; i <= nbPoints; i++) {
  7210. 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)));
  7211. }
  7212. return new Curve3(bez);
  7213. };
  7214. /**
  7215. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7216. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7217. * @param v1 (Vector3) the first control point
  7218. * @param v2 (Vector3) the second control point
  7219. * @param v3 (Vector3) the end point of the Cubic Bezier
  7220. * @param nbPoints (integer) the wanted number of points in the curve
  7221. */
  7222. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7223. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7224. var bez = new Array();
  7225. var equation = function (t, val0, val1, val2, val3) {
  7226. 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;
  7227. return res;
  7228. };
  7229. for (var i = 0; i <= nbPoints; i++) {
  7230. 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)));
  7231. }
  7232. return new Curve3(bez);
  7233. };
  7234. /**
  7235. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7236. * @param p1 (Vector3) the origin point of the Hermite Spline
  7237. * @param t1 (Vector3) the tangent vector at the origin point
  7238. * @param p2 (Vector3) the end point of the Hermite Spline
  7239. * @param t2 (Vector3) the tangent vector at the end point
  7240. * @param nbPoints (integer) the wanted number of points in the curve
  7241. */
  7242. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7243. var hermite = new Array();
  7244. var step = 1.0 / nbPoints;
  7245. for (var i = 0; i <= nbPoints; i++) {
  7246. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7247. }
  7248. return new Curve3(hermite);
  7249. };
  7250. /**
  7251. * Returns a Curve3 object along a CatmullRom Spline curve :
  7252. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7253. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7254. */
  7255. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7256. var totalPoints = new Array();
  7257. totalPoints.push(points[0].clone());
  7258. Array.prototype.push.apply(totalPoints, points);
  7259. totalPoints.push(points[points.length - 1].clone());
  7260. var catmullRom = new Array();
  7261. var step = 1.0 / nbPoints;
  7262. var amount = 0.0;
  7263. for (var i = 0; i < totalPoints.length - 3; i++) {
  7264. amount = 0;
  7265. for (var c = 0; c < nbPoints; c++) {
  7266. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7267. amount += step;
  7268. }
  7269. }
  7270. i--;
  7271. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7272. return new Curve3(catmullRom);
  7273. };
  7274. /**
  7275. * Returns the Curve3 stored array of successive Vector3
  7276. */
  7277. Curve3.prototype.getPoints = function () {
  7278. return this._points;
  7279. };
  7280. /**
  7281. * Returns the computed length (float) of the curve.
  7282. */
  7283. Curve3.prototype.length = function () {
  7284. return this._length;
  7285. };
  7286. /**
  7287. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7288. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7289. * curveA and curveB keep unchanged.
  7290. */
  7291. Curve3.prototype.continue = function (curve) {
  7292. var lastPoint = this._points[this._points.length - 1];
  7293. var continuedPoints = this._points.slice();
  7294. var curvePoints = curve.getPoints();
  7295. for (var i = 1; i < curvePoints.length; i++) {
  7296. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7297. }
  7298. var continuedCurve = new Curve3(continuedPoints);
  7299. return continuedCurve;
  7300. };
  7301. Curve3.prototype._computeLength = function (path) {
  7302. var l = 0;
  7303. for (var i = 1; i < path.length; i++) {
  7304. l += (path[i].subtract(path[i - 1])).length();
  7305. }
  7306. return l;
  7307. };
  7308. return Curve3;
  7309. }());
  7310. BABYLON.Curve3 = Curve3;
  7311. // Vertex formats
  7312. var PositionNormalVertex = /** @class */ (function () {
  7313. function PositionNormalVertex(position, normal) {
  7314. if (position === void 0) { position = Vector3.Zero(); }
  7315. if (normal === void 0) { normal = Vector3.Up(); }
  7316. this.position = position;
  7317. this.normal = normal;
  7318. }
  7319. PositionNormalVertex.prototype.clone = function () {
  7320. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7321. };
  7322. return PositionNormalVertex;
  7323. }());
  7324. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7325. var PositionNormalTextureVertex = /** @class */ (function () {
  7326. function PositionNormalTextureVertex(position, normal, uv) {
  7327. if (position === void 0) { position = Vector3.Zero(); }
  7328. if (normal === void 0) { normal = Vector3.Up(); }
  7329. if (uv === void 0) { uv = Vector2.Zero(); }
  7330. this.position = position;
  7331. this.normal = normal;
  7332. this.uv = uv;
  7333. }
  7334. PositionNormalTextureVertex.prototype.clone = function () {
  7335. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7336. };
  7337. return PositionNormalTextureVertex;
  7338. }());
  7339. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7340. // Temporary pre-allocated objects for engine internal use
  7341. // usage in any internal function :
  7342. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7343. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7344. var Tmp = /** @class */ (function () {
  7345. function Tmp() {
  7346. }
  7347. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7348. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7349. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7350. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7351. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7352. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7353. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7354. Matrix.Zero(), Matrix.Zero(),
  7355. Matrix.Zero(), Matrix.Zero(),
  7356. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7357. return Tmp;
  7358. }());
  7359. BABYLON.Tmp = Tmp;
  7360. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7361. var MathTmp = /** @class */ (function () {
  7362. function MathTmp() {
  7363. }
  7364. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7365. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7366. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7367. return MathTmp;
  7368. }());
  7369. })(BABYLON || (BABYLON = {}));
  7370. //# sourceMappingURL=babylon.math.js.map
  7371. var BABYLON;
  7372. (function (BABYLON) {
  7373. var Scalar = /** @class */ (function () {
  7374. function Scalar() {
  7375. }
  7376. /**
  7377. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7378. */
  7379. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7380. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7381. var num = a - b;
  7382. return -epsilon <= num && num <= epsilon;
  7383. };
  7384. /**
  7385. * Returns a string : the upper case translation of the number i to hexadecimal.
  7386. */
  7387. Scalar.ToHex = function (i) {
  7388. var str = i.toString(16);
  7389. if (i <= 15) {
  7390. return ("0" + str).toUpperCase();
  7391. }
  7392. return str.toUpperCase();
  7393. };
  7394. /**
  7395. * Returns -1 if value is negative and +1 is value is positive.
  7396. * Returns the value itself if it's equal to zero.
  7397. */
  7398. Scalar.Sign = function (value) {
  7399. value = +value; // convert to a number
  7400. if (value === 0 || isNaN(value))
  7401. return value;
  7402. return value > 0 ? 1 : -1;
  7403. };
  7404. /**
  7405. * Returns the value itself if it's between min and max.
  7406. * Returns min if the value is lower than min.
  7407. * Returns max if the value is greater than max.
  7408. */
  7409. Scalar.Clamp = function (value, min, max) {
  7410. if (min === void 0) { min = 0; }
  7411. if (max === void 0) { max = 1; }
  7412. return Math.min(max, Math.max(min, value));
  7413. };
  7414. /**
  7415. * Returns the log2 of value.
  7416. */
  7417. Scalar.Log2 = function (value) {
  7418. return Math.log(value) * Math.LOG2E;
  7419. };
  7420. /**
  7421. * Loops the value, so that it is never larger than length and never smaller than 0.
  7422. *
  7423. * This is similar to the modulo operator but it works with floating point numbers.
  7424. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7425. * With t = 5 and length = 2.5, the result would be 0.0.
  7426. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7427. */
  7428. Scalar.Repeat = function (value, length) {
  7429. return value - Math.floor(value / length) * length;
  7430. };
  7431. /**
  7432. * Normalize the value between 0.0 and 1.0 using min and max values
  7433. */
  7434. Scalar.Normalize = function (value, min, max) {
  7435. return (value - min) / (max - min);
  7436. };
  7437. /**
  7438. * Denormalize the value from 0.0 and 1.0 using min and max values
  7439. */
  7440. Scalar.Denormalize = function (normalized, min, max) {
  7441. return (normalized * (max - min) + min);
  7442. };
  7443. /**
  7444. * Calculates the shortest difference between two given angles given in degrees.
  7445. */
  7446. Scalar.DeltaAngle = function (current, target) {
  7447. var num = Scalar.Repeat(target - current, 360.0);
  7448. if (num > 180.0) {
  7449. num -= 360.0;
  7450. }
  7451. return num;
  7452. };
  7453. /**
  7454. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7455. *
  7456. * The returned value will move back and forth between 0 and length
  7457. */
  7458. Scalar.PingPong = function (tx, length) {
  7459. var t = Scalar.Repeat(tx, length * 2.0);
  7460. return length - Math.abs(t - length);
  7461. };
  7462. /**
  7463. * Interpolates between min and max with smoothing at the limits.
  7464. *
  7465. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7466. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7467. */
  7468. Scalar.SmoothStep = function (from, to, tx) {
  7469. var t = Scalar.Clamp(tx);
  7470. t = -2.0 * t * t * t + 3.0 * t * t;
  7471. return to * t + from * (1.0 - t);
  7472. };
  7473. /**
  7474. * Moves a value current towards target.
  7475. *
  7476. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7477. * Negative values of maxDelta pushes the value away from target.
  7478. */
  7479. Scalar.MoveTowards = function (current, target, maxDelta) {
  7480. var result = 0;
  7481. if (Math.abs(target - current) <= maxDelta) {
  7482. result = target;
  7483. }
  7484. else {
  7485. result = current + Scalar.Sign(target - current) * maxDelta;
  7486. }
  7487. return result;
  7488. };
  7489. /**
  7490. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7491. *
  7492. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7493. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7494. */
  7495. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7496. var num = Scalar.DeltaAngle(current, target);
  7497. var result = 0;
  7498. if (-maxDelta < num && num < maxDelta) {
  7499. result = target;
  7500. }
  7501. else {
  7502. target = current + num;
  7503. result = Scalar.MoveTowards(current, target, maxDelta);
  7504. }
  7505. return result;
  7506. };
  7507. /**
  7508. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7509. */
  7510. Scalar.Lerp = function (start, end, amount) {
  7511. return start + ((end - start) * amount);
  7512. };
  7513. /**
  7514. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7515. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7516. */
  7517. Scalar.LerpAngle = function (start, end, amount) {
  7518. var num = Scalar.Repeat(end - start, 360.0);
  7519. if (num > 180.0) {
  7520. num -= 360.0;
  7521. }
  7522. return start + num * Scalar.Clamp(amount);
  7523. };
  7524. /**
  7525. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7526. */
  7527. Scalar.InverseLerp = function (a, b, value) {
  7528. var result = 0;
  7529. if (a != b) {
  7530. result = Scalar.Clamp((value - a) / (b - a));
  7531. }
  7532. else {
  7533. result = 0.0;
  7534. }
  7535. return result;
  7536. };
  7537. /**
  7538. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7539. */
  7540. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7541. var squared = amount * amount;
  7542. var cubed = amount * squared;
  7543. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7544. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7545. var part3 = (cubed - (2.0 * squared)) + amount;
  7546. var part4 = cubed - squared;
  7547. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7548. };
  7549. /**
  7550. * Returns a random float number between and min and max values
  7551. */
  7552. Scalar.RandomRange = function (min, max) {
  7553. if (min === max)
  7554. return min;
  7555. return ((Math.random() * (max - min)) + min);
  7556. };
  7557. /**
  7558. * This function returns percentage of a number in a given range.
  7559. *
  7560. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7561. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7562. */
  7563. Scalar.RangeToPercent = function (number, min, max) {
  7564. return ((number - min) / (max - min));
  7565. };
  7566. /**
  7567. * This function returns number that corresponds to the percentage in a given range.
  7568. *
  7569. * PercentToRange(0.34,0,100) will return 34.
  7570. */
  7571. Scalar.PercentToRange = function (percent, min, max) {
  7572. return ((max - min) * percent + min);
  7573. };
  7574. /**
  7575. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7576. * @param angle The angle to normalize in radian.
  7577. * @return The converted angle.
  7578. */
  7579. Scalar.NormalizeRadians = function (angle) {
  7580. // More precise but slower version kept for reference.
  7581. // angle = angle % Tools.TwoPi;
  7582. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7583. //if (angle > Math.PI) {
  7584. // angle -= Tools.TwoPi;
  7585. //}
  7586. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7587. return angle;
  7588. };
  7589. /**
  7590. * Two pi constants convenient for computation.
  7591. */
  7592. Scalar.TwoPi = Math.PI * 2;
  7593. return Scalar;
  7594. }());
  7595. BABYLON.Scalar = Scalar;
  7596. })(BABYLON || (BABYLON = {}));
  7597. //# sourceMappingURL=babylon.math.scalar.js.map
  7598. //# sourceMappingURL=babylon.mixins.js.map
  7599. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7600. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7601. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7602. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7603. //# sourceMappingURL=babylon.webgl2.js.map
  7604. var BABYLON;
  7605. (function (BABYLON) {
  7606. var __decoratorInitialStore = {};
  7607. var __mergedStore = {};
  7608. var _copySource = function (creationFunction, source, instanciate) {
  7609. var destination = creationFunction();
  7610. // Tags
  7611. if (BABYLON.Tags) {
  7612. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7613. }
  7614. var classStore = getMergedStore(destination);
  7615. // Properties
  7616. for (var property in classStore) {
  7617. var propertyDescriptor = classStore[property];
  7618. var sourceProperty = source[property];
  7619. var propertyType = propertyDescriptor.type;
  7620. if (sourceProperty !== undefined && sourceProperty !== null) {
  7621. switch (propertyType) {
  7622. case 0: // Value
  7623. case 6: // Mesh reference
  7624. case 11: // Camera reference
  7625. destination[property] = sourceProperty;
  7626. break;
  7627. case 1: // Texture
  7628. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7629. break;
  7630. case 2: // Color3
  7631. case 3: // FresnelParameters
  7632. case 4: // Vector2
  7633. case 5: // Vector3
  7634. case 7: // Color Curves
  7635. case 10: // Quaternion
  7636. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7637. break;
  7638. }
  7639. }
  7640. }
  7641. return destination;
  7642. };
  7643. function getDirectStore(target) {
  7644. var classKey = target.getClassName();
  7645. if (!__decoratorInitialStore[classKey]) {
  7646. __decoratorInitialStore[classKey] = {};
  7647. }
  7648. return __decoratorInitialStore[classKey];
  7649. }
  7650. /**
  7651. * Return the list of properties flagged as serializable
  7652. * @param target: host object
  7653. */
  7654. function getMergedStore(target) {
  7655. var classKey = target.getClassName();
  7656. if (__mergedStore[classKey]) {
  7657. return __mergedStore[classKey];
  7658. }
  7659. __mergedStore[classKey] = {};
  7660. var store = __mergedStore[classKey];
  7661. var currentTarget = target;
  7662. var currentKey = classKey;
  7663. while (currentKey) {
  7664. var initialStore = __decoratorInitialStore[currentKey];
  7665. for (var property in initialStore) {
  7666. store[property] = initialStore[property];
  7667. }
  7668. var parent_1 = void 0;
  7669. var done = false;
  7670. do {
  7671. parent_1 = Object.getPrototypeOf(currentTarget);
  7672. if (!parent_1.getClassName) {
  7673. done = true;
  7674. break;
  7675. }
  7676. if (parent_1.getClassName() !== currentKey) {
  7677. break;
  7678. }
  7679. currentTarget = parent_1;
  7680. } while (parent_1);
  7681. if (done) {
  7682. break;
  7683. }
  7684. currentKey = parent_1.getClassName();
  7685. currentTarget = parent_1;
  7686. }
  7687. return store;
  7688. }
  7689. function generateSerializableMember(type, sourceName) {
  7690. return function (target, propertyKey) {
  7691. var classStore = getDirectStore(target);
  7692. if (!classStore[propertyKey]) {
  7693. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7694. }
  7695. };
  7696. }
  7697. function generateExpandMember(setCallback, targetKey) {
  7698. if (targetKey === void 0) { targetKey = null; }
  7699. return function (target, propertyKey) {
  7700. var key = targetKey || ("_" + propertyKey);
  7701. Object.defineProperty(target, propertyKey, {
  7702. get: function () {
  7703. return this[key];
  7704. },
  7705. set: function (value) {
  7706. if (this[key] === value) {
  7707. return;
  7708. }
  7709. this[key] = value;
  7710. target[setCallback].apply(this);
  7711. },
  7712. enumerable: true,
  7713. configurable: true
  7714. });
  7715. };
  7716. }
  7717. function expandToProperty(callback, targetKey) {
  7718. if (targetKey === void 0) { targetKey = null; }
  7719. return generateExpandMember(callback, targetKey);
  7720. }
  7721. BABYLON.expandToProperty = expandToProperty;
  7722. function serialize(sourceName) {
  7723. return generateSerializableMember(0, sourceName); // value member
  7724. }
  7725. BABYLON.serialize = serialize;
  7726. function serializeAsTexture(sourceName) {
  7727. return generateSerializableMember(1, sourceName); // texture member
  7728. }
  7729. BABYLON.serializeAsTexture = serializeAsTexture;
  7730. function serializeAsColor3(sourceName) {
  7731. return generateSerializableMember(2, sourceName); // color3 member
  7732. }
  7733. BABYLON.serializeAsColor3 = serializeAsColor3;
  7734. function serializeAsFresnelParameters(sourceName) {
  7735. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7736. }
  7737. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7738. function serializeAsVector2(sourceName) {
  7739. return generateSerializableMember(4, sourceName); // vector2 member
  7740. }
  7741. BABYLON.serializeAsVector2 = serializeAsVector2;
  7742. function serializeAsVector3(sourceName) {
  7743. return generateSerializableMember(5, sourceName); // vector3 member
  7744. }
  7745. BABYLON.serializeAsVector3 = serializeAsVector3;
  7746. function serializeAsMeshReference(sourceName) {
  7747. return generateSerializableMember(6, sourceName); // mesh reference member
  7748. }
  7749. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7750. function serializeAsColorCurves(sourceName) {
  7751. return generateSerializableMember(7, sourceName); // color curves
  7752. }
  7753. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7754. function serializeAsColor4(sourceName) {
  7755. return generateSerializableMember(8, sourceName); // color 4
  7756. }
  7757. BABYLON.serializeAsColor4 = serializeAsColor4;
  7758. function serializeAsImageProcessingConfiguration(sourceName) {
  7759. return generateSerializableMember(9, sourceName); // image processing
  7760. }
  7761. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7762. function serializeAsQuaternion(sourceName) {
  7763. return generateSerializableMember(10, sourceName); // quaternion member
  7764. }
  7765. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7766. /**
  7767. * Decorator used to define property that can be serialized as reference to a camera
  7768. * @param sourceName defines the name of the property to decorate
  7769. */
  7770. function serializeAsCameraReference(sourceName) {
  7771. return generateSerializableMember(11, sourceName); // camera reference member
  7772. }
  7773. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7774. var SerializationHelper = /** @class */ (function () {
  7775. function SerializationHelper() {
  7776. }
  7777. SerializationHelper.Serialize = function (entity, serializationObject) {
  7778. if (!serializationObject) {
  7779. serializationObject = {};
  7780. }
  7781. // Tags
  7782. if (BABYLON.Tags) {
  7783. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7784. }
  7785. var serializedProperties = getMergedStore(entity);
  7786. // Properties
  7787. for (var property in serializedProperties) {
  7788. var propertyDescriptor = serializedProperties[property];
  7789. var targetPropertyName = propertyDescriptor.sourceName || property;
  7790. var propertyType = propertyDescriptor.type;
  7791. var sourceProperty = entity[property];
  7792. if (sourceProperty !== undefined && sourceProperty !== null) {
  7793. switch (propertyType) {
  7794. case 0: // Value
  7795. serializationObject[targetPropertyName] = sourceProperty;
  7796. break;
  7797. case 1: // Texture
  7798. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7799. break;
  7800. case 2: // Color3
  7801. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7802. break;
  7803. case 3: // FresnelParameters
  7804. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7805. break;
  7806. case 4: // Vector2
  7807. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7808. break;
  7809. case 5: // Vector3
  7810. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7811. break;
  7812. case 6: // Mesh reference
  7813. serializationObject[targetPropertyName] = sourceProperty.id;
  7814. break;
  7815. case 7: // Color Curves
  7816. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7817. break;
  7818. case 8: // Color 4
  7819. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7820. break;
  7821. case 9: // Image Processing
  7822. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7823. break;
  7824. case 10: // Quaternion
  7825. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7826. break;
  7827. case 11: // Camera reference
  7828. serializationObject[targetPropertyName] = sourceProperty.id;
  7829. break;
  7830. }
  7831. }
  7832. }
  7833. return serializationObject;
  7834. };
  7835. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7836. if (rootUrl === void 0) { rootUrl = null; }
  7837. var destination = creationFunction();
  7838. if (!rootUrl) {
  7839. rootUrl = "";
  7840. }
  7841. // Tags
  7842. if (BABYLON.Tags) {
  7843. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7844. }
  7845. var classStore = getMergedStore(destination);
  7846. // Properties
  7847. for (var property in classStore) {
  7848. var propertyDescriptor = classStore[property];
  7849. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7850. var propertyType = propertyDescriptor.type;
  7851. if (sourceProperty !== undefined && sourceProperty !== null) {
  7852. var dest = destination;
  7853. switch (propertyType) {
  7854. case 0: // Value
  7855. dest[property] = sourceProperty;
  7856. break;
  7857. case 1: // Texture
  7858. if (scene) {
  7859. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7860. }
  7861. break;
  7862. case 2: // Color3
  7863. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7864. break;
  7865. case 3: // FresnelParameters
  7866. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7867. break;
  7868. case 4: // Vector2
  7869. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7870. break;
  7871. case 5: // Vector3
  7872. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7873. break;
  7874. case 6: // Mesh reference
  7875. if (scene) {
  7876. dest[property] = scene.getLastMeshByID(sourceProperty);
  7877. }
  7878. break;
  7879. case 7: // Color Curves
  7880. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7881. break;
  7882. case 8: // Color 4
  7883. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7884. break;
  7885. case 9: // Image Processing
  7886. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7887. break;
  7888. case 10: // Quaternion
  7889. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7890. break;
  7891. case 11: // Camera reference
  7892. if (scene) {
  7893. dest[property] = scene.getCameraByID(sourceProperty);
  7894. }
  7895. break;
  7896. }
  7897. }
  7898. }
  7899. return destination;
  7900. };
  7901. SerializationHelper.Clone = function (creationFunction, source) {
  7902. return _copySource(creationFunction, source, false);
  7903. };
  7904. SerializationHelper.Instanciate = function (creationFunction, source) {
  7905. return _copySource(creationFunction, source, true);
  7906. };
  7907. return SerializationHelper;
  7908. }());
  7909. BABYLON.SerializationHelper = SerializationHelper;
  7910. })(BABYLON || (BABYLON = {}));
  7911. //# sourceMappingURL=babylon.decorators.js.map
  7912. var BABYLON;
  7913. (function (BABYLON) {
  7914. /**
  7915. * Wrapper class for promise with external resolve and reject.
  7916. */
  7917. var Deferred = /** @class */ (function () {
  7918. /**
  7919. * Constructor for this deferred object.
  7920. */
  7921. function Deferred() {
  7922. var _this = this;
  7923. this.promise = new Promise(function (resolve, reject) {
  7924. _this._resolve = resolve;
  7925. _this._reject = reject;
  7926. });
  7927. }
  7928. Object.defineProperty(Deferred.prototype, "resolve", {
  7929. /**
  7930. * The resolve method of the promise associated with this deferred object.
  7931. */
  7932. get: function () {
  7933. return this._resolve;
  7934. },
  7935. enumerable: true,
  7936. configurable: true
  7937. });
  7938. Object.defineProperty(Deferred.prototype, "reject", {
  7939. /**
  7940. * The reject method of the promise associated with this deferred object.
  7941. */
  7942. get: function () {
  7943. return this._reject;
  7944. },
  7945. enumerable: true,
  7946. configurable: true
  7947. });
  7948. return Deferred;
  7949. }());
  7950. BABYLON.Deferred = Deferred;
  7951. })(BABYLON || (BABYLON = {}));
  7952. //# sourceMappingURL=babylon.deferred.js.map
  7953. var BABYLON;
  7954. (function (BABYLON) {
  7955. /**
  7956. * A class serves as a medium between the observable and its observers
  7957. */
  7958. var EventState = /** @class */ (function () {
  7959. /**
  7960. * Create a new EventState
  7961. * @param mask defines the mask associated with this state
  7962. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7963. * @param target defines the original target of the state
  7964. * @param currentTarget defines the current target of the state
  7965. */
  7966. function EventState(mask, skipNextObservers, target, currentTarget) {
  7967. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7968. this.initalize(mask, skipNextObservers, target, currentTarget);
  7969. }
  7970. /**
  7971. * Initialize the current event state
  7972. * @param mask defines the mask associated with this state
  7973. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7974. * @param target defines the original target of the state
  7975. * @param currentTarget defines the current target of the state
  7976. * @returns the current event state
  7977. */
  7978. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7979. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7980. this.mask = mask;
  7981. this.skipNextObservers = skipNextObservers;
  7982. this.target = target;
  7983. this.currentTarget = currentTarget;
  7984. return this;
  7985. };
  7986. return EventState;
  7987. }());
  7988. BABYLON.EventState = EventState;
  7989. /**
  7990. * Represent an Observer registered to a given Observable object.
  7991. */
  7992. var Observer = /** @class */ (function () {
  7993. /**
  7994. * Creates a new observer
  7995. * @param callback defines the callback to call when the observer is notified
  7996. * @param mask defines the mask of the observer (used to filter notifications)
  7997. * @param scope defines the current scope used to restore the JS context
  7998. */
  7999. function Observer(
  8000. /**
  8001. * Defines the callback to call when the observer is notified
  8002. */
  8003. callback,
  8004. /**
  8005. * Defines the mask of the observer (used to filter notifications)
  8006. */
  8007. mask,
  8008. /**
  8009. * Defines the current scope used to restore the JS context
  8010. */
  8011. scope) {
  8012. if (scope === void 0) { scope = null; }
  8013. this.callback = callback;
  8014. this.mask = mask;
  8015. this.scope = scope;
  8016. /** @hidden */
  8017. this._willBeUnregistered = false;
  8018. /**
  8019. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8020. */
  8021. this.unregisterOnNextCall = false;
  8022. }
  8023. return Observer;
  8024. }());
  8025. BABYLON.Observer = Observer;
  8026. /**
  8027. * Represent a list of observers registered to multiple Observables object.
  8028. */
  8029. var MultiObserver = /** @class */ (function () {
  8030. function MultiObserver() {
  8031. }
  8032. /**
  8033. * Release associated resources
  8034. */
  8035. MultiObserver.prototype.dispose = function () {
  8036. if (this._observers && this._observables) {
  8037. for (var index = 0; index < this._observers.length; index++) {
  8038. this._observables[index].remove(this._observers[index]);
  8039. }
  8040. }
  8041. this._observers = null;
  8042. this._observables = null;
  8043. };
  8044. /**
  8045. * Raise a callback when one of the observable will notify
  8046. * @param observables defines a list of observables to watch
  8047. * @param callback defines the callback to call on notification
  8048. * @param mask defines the mask used to filter notifications
  8049. * @param scope defines the current scope used to restore the JS context
  8050. * @returns the new MultiObserver
  8051. */
  8052. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8053. if (mask === void 0) { mask = -1; }
  8054. if (scope === void 0) { scope = null; }
  8055. var result = new MultiObserver();
  8056. result._observers = new Array();
  8057. result._observables = observables;
  8058. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8059. var observable = observables_1[_i];
  8060. var observer = observable.add(callback, mask, false, scope);
  8061. if (observer) {
  8062. result._observers.push(observer);
  8063. }
  8064. }
  8065. return result;
  8066. };
  8067. return MultiObserver;
  8068. }());
  8069. BABYLON.MultiObserver = MultiObserver;
  8070. /**
  8071. * The Observable class is a simple implementation of the Observable pattern.
  8072. *
  8073. * 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.
  8074. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8075. * 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).
  8076. * 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.
  8077. */
  8078. var Observable = /** @class */ (function () {
  8079. /**
  8080. * Creates a new observable
  8081. * @param onObserverAdded defines a callback to call when a new observer is added
  8082. */
  8083. function Observable(onObserverAdded) {
  8084. this._observers = new Array();
  8085. this._eventState = new EventState(0);
  8086. if (onObserverAdded) {
  8087. this._onObserverAdded = onObserverAdded;
  8088. }
  8089. }
  8090. /**
  8091. * Create a new Observer with the specified callback
  8092. * @param callback the callback that will be executed for that Observer
  8093. * @param mask the mask used to filter observers
  8094. * @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.
  8095. * @param scope optional scope for the callback to be called from
  8096. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8097. * @returns the new observer created for the callback
  8098. */
  8099. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8100. if (mask === void 0) { mask = -1; }
  8101. if (insertFirst === void 0) { insertFirst = false; }
  8102. if (scope === void 0) { scope = null; }
  8103. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8104. if (!callback) {
  8105. return null;
  8106. }
  8107. var observer = new Observer(callback, mask, scope);
  8108. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8109. if (insertFirst) {
  8110. this._observers.unshift(observer);
  8111. }
  8112. else {
  8113. this._observers.push(observer);
  8114. }
  8115. if (this._onObserverAdded) {
  8116. this._onObserverAdded(observer);
  8117. }
  8118. return observer;
  8119. };
  8120. /**
  8121. * Remove an Observer from the Observable object
  8122. * @param observer the instance of the Observer to remove
  8123. * @returns false if it doesn't belong to this Observable
  8124. */
  8125. Observable.prototype.remove = function (observer) {
  8126. if (!observer) {
  8127. return false;
  8128. }
  8129. var index = this._observers.indexOf(observer);
  8130. if (index !== -1) {
  8131. this._observers.splice(index, 1);
  8132. return true;
  8133. }
  8134. return false;
  8135. };
  8136. /**
  8137. * Remove a callback from the Observable object
  8138. * @param callback the callback to remove
  8139. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8140. * @returns false if it doesn't belong to this Observable
  8141. */
  8142. Observable.prototype.removeCallback = function (callback, scope) {
  8143. for (var index = 0; index < this._observers.length; index++) {
  8144. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8145. this._observers.splice(index, 1);
  8146. return true;
  8147. }
  8148. }
  8149. return false;
  8150. };
  8151. Observable.prototype._deferUnregister = function (observer) {
  8152. var _this = this;
  8153. observer.unregisterOnNextCall = false;
  8154. observer._willBeUnregistered = true;
  8155. BABYLON.Tools.SetImmediate(function () {
  8156. _this.remove(observer);
  8157. });
  8158. };
  8159. /**
  8160. * Notify all Observers by calling their respective callback with the given data
  8161. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8162. * @param eventData defines the data to send to all observers
  8163. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8164. * @param target defines the original target of the state
  8165. * @param currentTarget defines the current target of the state
  8166. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8167. */
  8168. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8169. if (mask === void 0) { mask = -1; }
  8170. if (!this._observers.length) {
  8171. return true;
  8172. }
  8173. var state = this._eventState;
  8174. state.mask = mask;
  8175. state.target = target;
  8176. state.currentTarget = currentTarget;
  8177. state.skipNextObservers = false;
  8178. state.lastReturnValue = eventData;
  8179. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8180. var obs = _a[_i];
  8181. if (obs._willBeUnregistered) {
  8182. continue;
  8183. }
  8184. if (obs.mask & mask) {
  8185. if (obs.scope) {
  8186. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8187. }
  8188. else {
  8189. state.lastReturnValue = obs.callback(eventData, state);
  8190. }
  8191. if (obs.unregisterOnNextCall) {
  8192. this._deferUnregister(obs);
  8193. }
  8194. }
  8195. if (state.skipNextObservers) {
  8196. return false;
  8197. }
  8198. }
  8199. return true;
  8200. };
  8201. /**
  8202. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8203. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8204. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8205. * and it is crucial that all callbacks will be executed.
  8206. * The order of the callbacks is kept, callbacks are not executed parallel.
  8207. *
  8208. * @param eventData The data to be sent to each callback
  8209. * @param mask is used to filter observers defaults to -1
  8210. * @param target defines the callback target (see EventState)
  8211. * @param currentTarget defines he current object in the bubbling phase
  8212. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8213. */
  8214. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8215. var _this = this;
  8216. if (mask === void 0) { mask = -1; }
  8217. // create an empty promise
  8218. var p = Promise.resolve(eventData);
  8219. // no observers? return this promise.
  8220. if (!this._observers.length) {
  8221. return p;
  8222. }
  8223. var state = this._eventState;
  8224. state.mask = mask;
  8225. state.target = target;
  8226. state.currentTarget = currentTarget;
  8227. state.skipNextObservers = false;
  8228. // execute one callback after another (not using Promise.all, the order is important)
  8229. this._observers.forEach(function (obs) {
  8230. if (state.skipNextObservers) {
  8231. return;
  8232. }
  8233. if (obs._willBeUnregistered) {
  8234. return;
  8235. }
  8236. if (obs.mask & mask) {
  8237. if (obs.scope) {
  8238. p = p.then(function (lastReturnedValue) {
  8239. state.lastReturnValue = lastReturnedValue;
  8240. return obs.callback.apply(obs.scope, [eventData, state]);
  8241. });
  8242. }
  8243. else {
  8244. p = p.then(function (lastReturnedValue) {
  8245. state.lastReturnValue = lastReturnedValue;
  8246. return obs.callback(eventData, state);
  8247. });
  8248. }
  8249. if (obs.unregisterOnNextCall) {
  8250. _this._deferUnregister(obs);
  8251. }
  8252. }
  8253. });
  8254. // return the eventData
  8255. return p.then(function () { return eventData; });
  8256. };
  8257. /**
  8258. * Notify a specific observer
  8259. * @param observer defines the observer to notify
  8260. * @param eventData defines the data to be sent to each callback
  8261. * @param mask is used to filter observers defaults to -1
  8262. */
  8263. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8264. if (mask === void 0) { mask = -1; }
  8265. var state = this._eventState;
  8266. state.mask = mask;
  8267. state.skipNextObservers = false;
  8268. observer.callback(eventData, state);
  8269. };
  8270. /**
  8271. * Gets a boolean indicating if the observable has at least one observer
  8272. * @returns true is the Observable has at least one Observer registered
  8273. */
  8274. Observable.prototype.hasObservers = function () {
  8275. return this._observers.length > 0;
  8276. };
  8277. /**
  8278. * Clear the list of observers
  8279. */
  8280. Observable.prototype.clear = function () {
  8281. this._observers = new Array();
  8282. this._onObserverAdded = null;
  8283. };
  8284. /**
  8285. * Clone the current observable
  8286. * @returns a new observable
  8287. */
  8288. Observable.prototype.clone = function () {
  8289. var result = new Observable();
  8290. result._observers = this._observers.slice(0);
  8291. return result;
  8292. };
  8293. /**
  8294. * Does this observable handles observer registered with a given mask
  8295. * @param mask defines the mask to be tested
  8296. * @return whether or not one observer registered with the given mask is handeled
  8297. **/
  8298. Observable.prototype.hasSpecificMask = function (mask) {
  8299. if (mask === void 0) { mask = -1; }
  8300. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8301. var obs = _a[_i];
  8302. if (obs.mask & mask || obs.mask === mask) {
  8303. return true;
  8304. }
  8305. }
  8306. return false;
  8307. };
  8308. return Observable;
  8309. }());
  8310. BABYLON.Observable = Observable;
  8311. })(BABYLON || (BABYLON = {}));
  8312. //# sourceMappingURL=babylon.observable.js.map
  8313. var BABYLON;
  8314. (function (BABYLON) {
  8315. var SmartArray = /** @class */ (function () {
  8316. function SmartArray(capacity) {
  8317. this.length = 0;
  8318. this.data = new Array(capacity);
  8319. this._id = SmartArray._GlobalId++;
  8320. }
  8321. SmartArray.prototype.push = function (value) {
  8322. this.data[this.length++] = value;
  8323. if (this.length > this.data.length) {
  8324. this.data.length *= 2;
  8325. }
  8326. };
  8327. SmartArray.prototype.forEach = function (func) {
  8328. for (var index = 0; index < this.length; index++) {
  8329. func(this.data[index]);
  8330. }
  8331. };
  8332. SmartArray.prototype.sort = function (compareFn) {
  8333. this.data.sort(compareFn);
  8334. };
  8335. SmartArray.prototype.reset = function () {
  8336. this.length = 0;
  8337. };
  8338. SmartArray.prototype.dispose = function () {
  8339. this.reset();
  8340. if (this.data) {
  8341. this.data.length = 0;
  8342. this.data = [];
  8343. }
  8344. };
  8345. SmartArray.prototype.concat = function (array) {
  8346. if (array.length === 0) {
  8347. return;
  8348. }
  8349. if (this.length + array.length > this.data.length) {
  8350. this.data.length = (this.length + array.length) * 2;
  8351. }
  8352. for (var index = 0; index < array.length; index++) {
  8353. this.data[this.length++] = (array.data || array)[index];
  8354. }
  8355. };
  8356. SmartArray.prototype.indexOf = function (value) {
  8357. var position = this.data.indexOf(value);
  8358. if (position >= this.length) {
  8359. return -1;
  8360. }
  8361. return position;
  8362. };
  8363. SmartArray.prototype.contains = function (value) {
  8364. return this.data.indexOf(value) !== -1;
  8365. };
  8366. // Statics
  8367. SmartArray._GlobalId = 0;
  8368. return SmartArray;
  8369. }());
  8370. BABYLON.SmartArray = SmartArray;
  8371. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8372. __extends(SmartArrayNoDuplicate, _super);
  8373. function SmartArrayNoDuplicate() {
  8374. var _this = _super !== null && _super.apply(this, arguments) || this;
  8375. _this._duplicateId = 0;
  8376. return _this;
  8377. }
  8378. SmartArrayNoDuplicate.prototype.push = function (value) {
  8379. _super.prototype.push.call(this, value);
  8380. if (!value.__smartArrayFlags) {
  8381. value.__smartArrayFlags = {};
  8382. }
  8383. value.__smartArrayFlags[this._id] = this._duplicateId;
  8384. };
  8385. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8386. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8387. return false;
  8388. }
  8389. this.push(value);
  8390. return true;
  8391. };
  8392. SmartArrayNoDuplicate.prototype.reset = function () {
  8393. _super.prototype.reset.call(this);
  8394. this._duplicateId++;
  8395. };
  8396. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8397. if (array.length === 0) {
  8398. return;
  8399. }
  8400. if (this.length + array.length > this.data.length) {
  8401. this.data.length = (this.length + array.length) * 2;
  8402. }
  8403. for (var index = 0; index < array.length; index++) {
  8404. var item = (array.data || array)[index];
  8405. this.pushNoDuplicate(item);
  8406. }
  8407. };
  8408. return SmartArrayNoDuplicate;
  8409. }(SmartArray));
  8410. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8411. })(BABYLON || (BABYLON = {}));
  8412. //# sourceMappingURL=babylon.smartArray.js.map
  8413. var BABYLON;
  8414. (function (BABYLON) {
  8415. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8416. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8417. var LoadFileError = /** @class */ (function (_super) {
  8418. __extends(LoadFileError, _super);
  8419. function LoadFileError(message, request) {
  8420. var _this = _super.call(this, message) || this;
  8421. _this.request = request;
  8422. _this.name = "LoadFileError";
  8423. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8424. return _this;
  8425. }
  8426. // Polyfill for Object.setPrototypeOf if necessary.
  8427. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8428. return LoadFileError;
  8429. }(Error));
  8430. BABYLON.LoadFileError = LoadFileError;
  8431. var RetryStrategy = /** @class */ (function () {
  8432. function RetryStrategy() {
  8433. }
  8434. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8435. if (maxRetries === void 0) { maxRetries = 3; }
  8436. if (baseInterval === void 0) { baseInterval = 500; }
  8437. return function (url, request, retryIndex) {
  8438. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8439. return -1;
  8440. }
  8441. return Math.pow(2, retryIndex) * baseInterval;
  8442. };
  8443. };
  8444. return RetryStrategy;
  8445. }());
  8446. BABYLON.RetryStrategy = RetryStrategy;
  8447. // Screenshots
  8448. var screenshotCanvas;
  8449. var cloneValue = function (source, destinationObject) {
  8450. if (!source)
  8451. return null;
  8452. if (source instanceof BABYLON.Mesh) {
  8453. return null;
  8454. }
  8455. if (source instanceof BABYLON.SubMesh) {
  8456. return source.clone(destinationObject);
  8457. }
  8458. else if (source.clone) {
  8459. return source.clone();
  8460. }
  8461. return null;
  8462. };
  8463. var Tools = /** @class */ (function () {
  8464. function Tools() {
  8465. }
  8466. /**
  8467. * Interpolates between a and b via alpha
  8468. * @param a The lower value (returned when alpha = 0)
  8469. * @param b The upper value (returned when alpha = 1)
  8470. * @param alpha The interpolation-factor
  8471. * @return The mixed value
  8472. */
  8473. Tools.Mix = function (a, b, alpha) {
  8474. return a * (1 - alpha) + b * alpha;
  8475. };
  8476. Tools.Instantiate = function (className) {
  8477. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8478. return Tools.RegisteredExternalClasses[className];
  8479. }
  8480. var arr = className.split(".");
  8481. var fn = (window || this);
  8482. for (var i = 0, len = arr.length; i < len; i++) {
  8483. fn = fn[arr[i]];
  8484. }
  8485. if (typeof fn !== "function") {
  8486. return null;
  8487. }
  8488. return fn;
  8489. };
  8490. /**
  8491. * Provides a slice function that will work even on IE
  8492. * @param data defines the array to slice
  8493. * @param start defines the start of the data (optional)
  8494. * @param end defines the end of the data (optional)
  8495. * @returns the new sliced array
  8496. */
  8497. Tools.Slice = function (data, start, end) {
  8498. if (data.slice) {
  8499. return data.slice(start, end);
  8500. }
  8501. return Array.prototype.slice.call(data, start, end);
  8502. };
  8503. Tools.SetImmediate = function (action) {
  8504. if (window.setImmediate) {
  8505. window.setImmediate(action);
  8506. }
  8507. else {
  8508. setTimeout(action, 1);
  8509. }
  8510. };
  8511. Tools.IsExponentOfTwo = function (value) {
  8512. var count = 1;
  8513. do {
  8514. count *= 2;
  8515. } while (count < value);
  8516. return count === value;
  8517. };
  8518. /**
  8519. * Returns the nearest 32-bit single precision float representation of a Number
  8520. * @param value A Number. If the parameter is of a different type, it will get converted
  8521. * to a number or to NaN if it cannot be converted
  8522. * @returns number
  8523. */
  8524. Tools.FloatRound = function (value) {
  8525. if (Math.fround) {
  8526. return Math.fround(value);
  8527. }
  8528. return (Tools._tmpFloatArray[0] = value);
  8529. };
  8530. /**
  8531. * Find the next highest power of two.
  8532. * @param x Number to start search from.
  8533. * @return Next highest power of two.
  8534. */
  8535. Tools.CeilingPOT = function (x) {
  8536. x--;
  8537. x |= x >> 1;
  8538. x |= x >> 2;
  8539. x |= x >> 4;
  8540. x |= x >> 8;
  8541. x |= x >> 16;
  8542. x++;
  8543. return x;
  8544. };
  8545. /**
  8546. * Find the next lowest power of two.
  8547. * @param x Number to start search from.
  8548. * @return Next lowest power of two.
  8549. */
  8550. Tools.FloorPOT = function (x) {
  8551. x = x | (x >> 1);
  8552. x = x | (x >> 2);
  8553. x = x | (x >> 4);
  8554. x = x | (x >> 8);
  8555. x = x | (x >> 16);
  8556. return x - (x >> 1);
  8557. };
  8558. /**
  8559. * Find the nearest power of two.
  8560. * @param x Number to start search from.
  8561. * @return Next nearest power of two.
  8562. */
  8563. Tools.NearestPOT = function (x) {
  8564. var c = Tools.CeilingPOT(x);
  8565. var f = Tools.FloorPOT(x);
  8566. return (c - x) > (x - f) ? f : c;
  8567. };
  8568. Tools.GetExponentOfTwo = function (value, max, mode) {
  8569. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8570. var pot;
  8571. switch (mode) {
  8572. case BABYLON.Engine.SCALEMODE_FLOOR:
  8573. pot = Tools.FloorPOT(value);
  8574. break;
  8575. case BABYLON.Engine.SCALEMODE_NEAREST:
  8576. pot = Tools.NearestPOT(value);
  8577. break;
  8578. case BABYLON.Engine.SCALEMODE_CEILING:
  8579. default:
  8580. pot = Tools.CeilingPOT(value);
  8581. break;
  8582. }
  8583. return Math.min(pot, max);
  8584. };
  8585. Tools.GetFilename = function (path) {
  8586. var index = path.lastIndexOf("/");
  8587. if (index < 0)
  8588. return path;
  8589. return path.substring(index + 1);
  8590. };
  8591. /**
  8592. * Extracts the "folder" part of a path (everything before the filename).
  8593. * @param uri The URI to extract the info from
  8594. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8595. * @returns The "folder" part of the path
  8596. */
  8597. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8598. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8599. var index = uri.lastIndexOf("/");
  8600. if (index < 0) {
  8601. if (returnUnchangedIfNoSlash) {
  8602. return uri;
  8603. }
  8604. return "";
  8605. }
  8606. return uri.substring(0, index + 1);
  8607. };
  8608. Tools.GetDOMTextContent = function (element) {
  8609. var result = "";
  8610. var child = element.firstChild;
  8611. while (child) {
  8612. if (child.nodeType === 3) {
  8613. result += child.textContent;
  8614. }
  8615. child = child.nextSibling;
  8616. }
  8617. return result;
  8618. };
  8619. Tools.ToDegrees = function (angle) {
  8620. return angle * 180 / Math.PI;
  8621. };
  8622. Tools.ToRadians = function (angle) {
  8623. return angle * Math.PI / 180;
  8624. };
  8625. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8626. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8627. var output = "";
  8628. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8629. var i = 0;
  8630. var bytes = new Uint8Array(buffer);
  8631. while (i < bytes.length) {
  8632. chr1 = bytes[i++];
  8633. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8634. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8635. enc1 = chr1 >> 2;
  8636. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8637. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8638. enc4 = chr3 & 63;
  8639. if (isNaN(chr2)) {
  8640. enc3 = enc4 = 64;
  8641. }
  8642. else if (isNaN(chr3)) {
  8643. enc4 = 64;
  8644. }
  8645. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8646. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8647. }
  8648. return "data:image/png;base64," + output;
  8649. };
  8650. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8651. if (bias === void 0) { bias = null; }
  8652. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8653. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8654. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8655. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8656. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8657. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8658. }
  8659. if (bias) {
  8660. minimum.x -= minimum.x * bias.x + bias.y;
  8661. minimum.y -= minimum.y * bias.x + bias.y;
  8662. minimum.z -= minimum.z * bias.x + bias.y;
  8663. maximum.x += maximum.x * bias.x + bias.y;
  8664. maximum.y += maximum.y * bias.x + bias.y;
  8665. maximum.z += maximum.z * bias.x + bias.y;
  8666. }
  8667. return {
  8668. minimum: minimum,
  8669. maximum: maximum
  8670. };
  8671. };
  8672. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8673. if (bias === void 0) { bias = null; }
  8674. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8675. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8676. if (!stride) {
  8677. stride = 3;
  8678. }
  8679. for (var index = start; index < start + count; index++) {
  8680. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8681. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8682. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8683. }
  8684. if (bias) {
  8685. minimum.x -= minimum.x * bias.x + bias.y;
  8686. minimum.y -= minimum.y * bias.x + bias.y;
  8687. minimum.z -= minimum.z * bias.x + bias.y;
  8688. maximum.x += maximum.x * bias.x + bias.y;
  8689. maximum.y += maximum.y * bias.x + bias.y;
  8690. maximum.z += maximum.z * bias.x + bias.y;
  8691. }
  8692. return {
  8693. minimum: minimum,
  8694. maximum: maximum
  8695. };
  8696. };
  8697. Tools.Vector2ArrayFeeder = function (array) {
  8698. return function (index) {
  8699. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8700. var length = isFloatArray ? array.length / 2 : array.length;
  8701. if (index >= length) {
  8702. return null;
  8703. }
  8704. if (isFloatArray) {
  8705. var fa = array;
  8706. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8707. }
  8708. var a = array;
  8709. return a[index];
  8710. };
  8711. };
  8712. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8713. if (bias === void 0) { bias = null; }
  8714. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8715. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8716. var i = 0;
  8717. var cur = feeder(i++);
  8718. while (cur) {
  8719. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8720. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8721. cur = feeder(i++);
  8722. }
  8723. if (bias) {
  8724. minimum.x -= minimum.x * bias.x + bias.y;
  8725. minimum.y -= minimum.y * bias.x + bias.y;
  8726. maximum.x += maximum.x * bias.x + bias.y;
  8727. maximum.y += maximum.y * bias.x + bias.y;
  8728. }
  8729. return {
  8730. minimum: minimum,
  8731. maximum: maximum
  8732. };
  8733. };
  8734. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8735. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8736. return null;
  8737. return Array.isArray(obj) ? obj : [obj];
  8738. };
  8739. // Misc.
  8740. Tools.GetPointerPrefix = function () {
  8741. var eventPrefix = "pointer";
  8742. // Check if pointer events are supported
  8743. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8744. eventPrefix = "mouse";
  8745. }
  8746. return eventPrefix;
  8747. };
  8748. /**
  8749. * @param func - the function to be called
  8750. * @param requester - the object that will request the next frame. Falls back to window.
  8751. */
  8752. Tools.QueueNewFrame = function (func, requester) {
  8753. if (!Tools.IsWindowObjectExist()) {
  8754. return setTimeout(func, 16);
  8755. }
  8756. if (!requester) {
  8757. requester = window;
  8758. }
  8759. if (requester.requestAnimationFrame) {
  8760. return requester.requestAnimationFrame(func);
  8761. }
  8762. else if (requester.msRequestAnimationFrame) {
  8763. return requester.msRequestAnimationFrame(func);
  8764. }
  8765. else if (requester.webkitRequestAnimationFrame) {
  8766. return requester.webkitRequestAnimationFrame(func);
  8767. }
  8768. else if (requester.mozRequestAnimationFrame) {
  8769. return requester.mozRequestAnimationFrame(func);
  8770. }
  8771. else if (requester.oRequestAnimationFrame) {
  8772. return requester.oRequestAnimationFrame(func);
  8773. }
  8774. else {
  8775. return window.setTimeout(func, 16);
  8776. }
  8777. };
  8778. Tools.RequestFullscreen = function (element) {
  8779. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8780. if (!requestFunction)
  8781. return;
  8782. requestFunction.call(element);
  8783. };
  8784. Tools.ExitFullscreen = function () {
  8785. if (document.exitFullscreen) {
  8786. document.exitFullscreen();
  8787. }
  8788. else if (document.mozCancelFullScreen) {
  8789. document.mozCancelFullScreen();
  8790. }
  8791. else if (document.webkitCancelFullScreen) {
  8792. document.webkitCancelFullScreen();
  8793. }
  8794. else if (document.msCancelFullScreen) {
  8795. document.msCancelFullScreen();
  8796. }
  8797. };
  8798. Tools.SetCorsBehavior = function (url, element) {
  8799. if (url && url.indexOf("data:") === 0) {
  8800. return;
  8801. }
  8802. if (Tools.CorsBehavior) {
  8803. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8804. element.crossOrigin = Tools.CorsBehavior;
  8805. }
  8806. else {
  8807. var result = Tools.CorsBehavior(url);
  8808. if (result) {
  8809. element.crossOrigin = result;
  8810. }
  8811. }
  8812. }
  8813. };
  8814. // External files
  8815. Tools.CleanUrl = function (url) {
  8816. url = url.replace(/#/mg, "%23");
  8817. return url;
  8818. };
  8819. Tools.LoadImage = function (url, onLoad, onError, database) {
  8820. if (url instanceof ArrayBuffer) {
  8821. url = Tools.EncodeArrayBufferTobase64(url);
  8822. }
  8823. url = Tools.CleanUrl(url);
  8824. url = Tools.PreprocessUrl(url);
  8825. var img = new Image();
  8826. Tools.SetCorsBehavior(url, img);
  8827. var loadHandler = function () {
  8828. img.removeEventListener("load", loadHandler);
  8829. img.removeEventListener("error", errorHandler);
  8830. onLoad(img);
  8831. };
  8832. var errorHandler = function (err) {
  8833. img.removeEventListener("load", loadHandler);
  8834. img.removeEventListener("error", errorHandler);
  8835. Tools.Error("Error while trying to load image: " + url);
  8836. if (onError) {
  8837. onError("Error while trying to load image: " + url, err);
  8838. }
  8839. };
  8840. img.addEventListener("load", loadHandler);
  8841. img.addEventListener("error", errorHandler);
  8842. var noIndexedDB = function () {
  8843. img.src = url;
  8844. };
  8845. var loadFromIndexedDB = function () {
  8846. if (database) {
  8847. database.loadImageFromDB(url, img);
  8848. }
  8849. };
  8850. //ANY database to do!
  8851. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8852. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8853. }
  8854. else {
  8855. if (url.indexOf("file:") !== -1) {
  8856. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8857. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8858. try {
  8859. var blobURL;
  8860. try {
  8861. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8862. }
  8863. catch (ex) {
  8864. // Chrome doesn't support oneTimeOnly parameter
  8865. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8866. }
  8867. img.src = blobURL;
  8868. }
  8869. catch (e) {
  8870. img.src = "";
  8871. }
  8872. return img;
  8873. }
  8874. }
  8875. noIndexedDB();
  8876. }
  8877. return img;
  8878. };
  8879. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8880. url = Tools.CleanUrl(url);
  8881. url = Tools.PreprocessUrl(url);
  8882. // If file and file input are set
  8883. if (url.indexOf("file:") !== -1) {
  8884. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8885. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8886. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8887. }
  8888. }
  8889. var loadUrl = Tools.BaseUrl + url;
  8890. var aborted = false;
  8891. var fileRequest = {
  8892. onCompleteObservable: new BABYLON.Observable(),
  8893. abort: function () { return aborted = true; },
  8894. };
  8895. var requestFile = function () {
  8896. var request = new XMLHttpRequest();
  8897. var retryHandle = null;
  8898. fileRequest.abort = function () {
  8899. aborted = true;
  8900. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8901. request.abort();
  8902. }
  8903. if (retryHandle !== null) {
  8904. clearTimeout(retryHandle);
  8905. retryHandle = null;
  8906. }
  8907. };
  8908. var retryLoop = function (retryIndex) {
  8909. request.open('GET', loadUrl, true);
  8910. if (useArrayBuffer) {
  8911. request.responseType = "arraybuffer";
  8912. }
  8913. if (onProgress) {
  8914. request.addEventListener("progress", onProgress);
  8915. }
  8916. var onLoadEnd = function () {
  8917. request.removeEventListener("loadend", onLoadEnd);
  8918. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8919. fileRequest.onCompleteObservable.clear();
  8920. };
  8921. request.addEventListener("loadend", onLoadEnd);
  8922. var onReadyStateChange = function () {
  8923. if (aborted) {
  8924. return;
  8925. }
  8926. // In case of undefined state in some browsers.
  8927. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8928. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8929. request.removeEventListener("readystatechange", onReadyStateChange);
  8930. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8931. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8932. return;
  8933. }
  8934. var retryStrategy = Tools.DefaultRetryStrategy;
  8935. if (retryStrategy) {
  8936. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8937. if (waitTime !== -1) {
  8938. // Prevent the request from completing for retry.
  8939. request.removeEventListener("loadend", onLoadEnd);
  8940. request = new XMLHttpRequest();
  8941. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8942. return;
  8943. }
  8944. }
  8945. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8946. if (onError) {
  8947. onError(request, e);
  8948. }
  8949. else {
  8950. throw e;
  8951. }
  8952. }
  8953. };
  8954. request.addEventListener("readystatechange", onReadyStateChange);
  8955. request.send();
  8956. };
  8957. retryLoop(0);
  8958. };
  8959. // Caching all files
  8960. if (database && database.enableSceneOffline) {
  8961. var noIndexedDB_1 = function () {
  8962. if (!aborted) {
  8963. requestFile();
  8964. }
  8965. };
  8966. var loadFromIndexedDB = function () {
  8967. // TODO: database needs to support aborting and should return a IFileRequest
  8968. if (aborted) {
  8969. return;
  8970. }
  8971. if (database) {
  8972. database.loadFileFromDB(url, function (data) {
  8973. if (!aborted) {
  8974. onSuccess(data);
  8975. }
  8976. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8977. }, onProgress ? function (event) {
  8978. if (!aborted) {
  8979. onProgress(event);
  8980. }
  8981. } : undefined, noIndexedDB_1, useArrayBuffer);
  8982. }
  8983. };
  8984. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8985. }
  8986. else {
  8987. requestFile();
  8988. }
  8989. return fileRequest;
  8990. };
  8991. /**
  8992. * Load a script (identified by an url). When the url returns, the
  8993. * content of this file is added into a new script element, attached to the DOM (body element)
  8994. */
  8995. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8996. var head = document.getElementsByTagName('head')[0];
  8997. var script = document.createElement('script');
  8998. script.type = 'text/javascript';
  8999. script.src = scriptUrl;
  9000. script.onload = function () {
  9001. if (onSuccess) {
  9002. onSuccess();
  9003. }
  9004. };
  9005. script.onerror = function (e) {
  9006. if (onError) {
  9007. onError("Unable to load script '" + scriptUrl + "'", e);
  9008. }
  9009. };
  9010. head.appendChild(script);
  9011. };
  9012. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9013. var reader = new FileReader();
  9014. var request = {
  9015. onCompleteObservable: new BABYLON.Observable(),
  9016. abort: function () { return reader.abort(); },
  9017. };
  9018. reader.onloadend = function (e) {
  9019. request.onCompleteObservable.notifyObservers(request);
  9020. };
  9021. reader.onload = function (e) {
  9022. //target doesn't have result from ts 1.3
  9023. callback(e.target['result']);
  9024. };
  9025. reader.onprogress = progressCallback;
  9026. reader.readAsDataURL(fileToLoad);
  9027. return request;
  9028. };
  9029. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9030. var reader = new FileReader();
  9031. var request = {
  9032. onCompleteObservable: new BABYLON.Observable(),
  9033. abort: function () { return reader.abort(); },
  9034. };
  9035. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9036. reader.onerror = function (e) {
  9037. Tools.Log("Error while reading file: " + fileToLoad.name);
  9038. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9039. };
  9040. reader.onload = function (e) {
  9041. //target doesn't have result from ts 1.3
  9042. callback(e.target['result']);
  9043. };
  9044. if (progressCallBack) {
  9045. reader.onprogress = progressCallBack;
  9046. }
  9047. if (!useArrayBuffer) {
  9048. // Asynchronous read
  9049. reader.readAsText(fileToLoad);
  9050. }
  9051. else {
  9052. reader.readAsArrayBuffer(fileToLoad);
  9053. }
  9054. return request;
  9055. };
  9056. //returns a downloadable url to a file content.
  9057. Tools.FileAsURL = function (content) {
  9058. var fileBlob = new Blob([content]);
  9059. var url = window.URL || window.webkitURL;
  9060. var link = url.createObjectURL(fileBlob);
  9061. return link;
  9062. };
  9063. // Misc.
  9064. Tools.Format = function (value, decimals) {
  9065. if (decimals === void 0) { decimals = 2; }
  9066. return value.toFixed(decimals);
  9067. };
  9068. Tools.CheckExtends = function (v, min, max) {
  9069. if (v.x < min.x)
  9070. min.x = v.x;
  9071. if (v.y < min.y)
  9072. min.y = v.y;
  9073. if (v.z < min.z)
  9074. min.z = v.z;
  9075. if (v.x > max.x)
  9076. max.x = v.x;
  9077. if (v.y > max.y)
  9078. max.y = v.y;
  9079. if (v.z > max.z)
  9080. max.z = v.z;
  9081. };
  9082. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9083. for (var prop in source) {
  9084. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9085. continue;
  9086. }
  9087. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9088. continue;
  9089. }
  9090. var sourceValue = source[prop];
  9091. var typeOfSourceValue = typeof sourceValue;
  9092. if (typeOfSourceValue === "function") {
  9093. continue;
  9094. }
  9095. try {
  9096. if (typeOfSourceValue === "object") {
  9097. if (sourceValue instanceof Array) {
  9098. destination[prop] = [];
  9099. if (sourceValue.length > 0) {
  9100. if (typeof sourceValue[0] == "object") {
  9101. for (var index = 0; index < sourceValue.length; index++) {
  9102. var clonedValue = cloneValue(sourceValue[index], destination);
  9103. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9104. destination[prop].push(clonedValue);
  9105. }
  9106. }
  9107. }
  9108. else {
  9109. destination[prop] = sourceValue.slice(0);
  9110. }
  9111. }
  9112. }
  9113. else {
  9114. destination[prop] = cloneValue(sourceValue, destination);
  9115. }
  9116. }
  9117. else {
  9118. destination[prop] = sourceValue;
  9119. }
  9120. }
  9121. catch (e) {
  9122. // Just ignore error (it could be because of a read-only property)
  9123. }
  9124. }
  9125. };
  9126. Tools.IsEmpty = function (obj) {
  9127. for (var i in obj) {
  9128. if (obj.hasOwnProperty(i)) {
  9129. return false;
  9130. }
  9131. }
  9132. return true;
  9133. };
  9134. Tools.RegisterTopRootEvents = function (events) {
  9135. for (var index = 0; index < events.length; index++) {
  9136. var event = events[index];
  9137. window.addEventListener(event.name, event.handler, false);
  9138. try {
  9139. if (window.parent) {
  9140. window.parent.addEventListener(event.name, event.handler, false);
  9141. }
  9142. }
  9143. catch (e) {
  9144. // Silently fails...
  9145. }
  9146. }
  9147. };
  9148. Tools.UnregisterTopRootEvents = function (events) {
  9149. for (var index = 0; index < events.length; index++) {
  9150. var event = events[index];
  9151. window.removeEventListener(event.name, event.handler);
  9152. try {
  9153. if (window.parent) {
  9154. window.parent.removeEventListener(event.name, event.handler);
  9155. }
  9156. }
  9157. catch (e) {
  9158. // Silently fails...
  9159. }
  9160. }
  9161. };
  9162. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9163. if (mimeType === void 0) { mimeType = "image/png"; }
  9164. // Read the contents of the framebuffer
  9165. var numberOfChannelsByLine = width * 4;
  9166. var halfHeight = height / 2;
  9167. //Reading datas from WebGL
  9168. var data = engine.readPixels(0, 0, width, height);
  9169. //To flip image on Y axis.
  9170. for (var i = 0; i < halfHeight; i++) {
  9171. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9172. var currentCell = j + i * numberOfChannelsByLine;
  9173. var targetLine = height - i - 1;
  9174. var targetCell = j + targetLine * numberOfChannelsByLine;
  9175. var temp = data[currentCell];
  9176. data[currentCell] = data[targetCell];
  9177. data[targetCell] = temp;
  9178. }
  9179. }
  9180. // Create a 2D canvas to store the result
  9181. if (!screenshotCanvas) {
  9182. screenshotCanvas = document.createElement('canvas');
  9183. }
  9184. screenshotCanvas.width = width;
  9185. screenshotCanvas.height = height;
  9186. var context = screenshotCanvas.getContext('2d');
  9187. if (context) {
  9188. // Copy the pixels to a 2D canvas
  9189. var imageData = context.createImageData(width, height);
  9190. var castData = (imageData.data);
  9191. castData.set(data);
  9192. context.putImageData(imageData, 0, 0);
  9193. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9194. }
  9195. };
  9196. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9197. if (mimeType === void 0) { mimeType = "image/png"; }
  9198. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9199. if (successCallback) {
  9200. successCallback(base64Image);
  9201. }
  9202. else {
  9203. // We need HTMLCanvasElement.toBlob for HD screenshots
  9204. if (!screenshotCanvas.toBlob) {
  9205. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9206. screenshotCanvas.toBlob = function (callback, type, quality) {
  9207. var _this = this;
  9208. setTimeout(function () {
  9209. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9210. for (var i = 0; i < len; i++) {
  9211. arr[i] = binStr.charCodeAt(i);
  9212. }
  9213. callback(new Blob([arr], { type: type || 'image/png' }));
  9214. });
  9215. };
  9216. }
  9217. screenshotCanvas.toBlob(function (blob) {
  9218. var url = URL.createObjectURL(blob);
  9219. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9220. if (("download" in document.createElement("a"))) {
  9221. var a = window.document.createElement("a");
  9222. a.href = url;
  9223. if (fileName) {
  9224. a.setAttribute("download", fileName);
  9225. }
  9226. else {
  9227. var date = new Date();
  9228. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9229. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9230. }
  9231. window.document.body.appendChild(a);
  9232. a.addEventListener("click", function () {
  9233. if (a.parentElement) {
  9234. a.parentElement.removeChild(a);
  9235. }
  9236. });
  9237. a.click();
  9238. }
  9239. else {
  9240. var newWindow = window.open("");
  9241. if (!newWindow)
  9242. return;
  9243. var img = newWindow.document.createElement("img");
  9244. img.onload = function () {
  9245. // no longer need to read the blob so it's revoked
  9246. URL.revokeObjectURL(url);
  9247. };
  9248. img.src = url;
  9249. newWindow.document.body.appendChild(img);
  9250. }
  9251. });
  9252. }
  9253. };
  9254. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9255. if (mimeType === void 0) { mimeType = "image/png"; }
  9256. var width;
  9257. var height;
  9258. // If a precision value is specified
  9259. if (size.precision) {
  9260. width = Math.round(engine.getRenderWidth() * size.precision);
  9261. height = Math.round(width / engine.getAspectRatio(camera));
  9262. }
  9263. else if (size.width && size.height) {
  9264. width = size.width;
  9265. height = size.height;
  9266. }
  9267. //If passing only width, computing height to keep display canvas ratio.
  9268. else if (size.width && !size.height) {
  9269. width = size.width;
  9270. height = Math.round(width / engine.getAspectRatio(camera));
  9271. }
  9272. //If passing only height, computing width to keep display canvas ratio.
  9273. else if (size.height && !size.width) {
  9274. height = size.height;
  9275. width = Math.round(height * engine.getAspectRatio(camera));
  9276. }
  9277. //Assuming here that "size" parameter is a number
  9278. else if (!isNaN(size)) {
  9279. height = size;
  9280. width = size;
  9281. }
  9282. else {
  9283. Tools.Error("Invalid 'size' parameter !");
  9284. return;
  9285. }
  9286. if (!screenshotCanvas) {
  9287. screenshotCanvas = document.createElement('canvas');
  9288. }
  9289. screenshotCanvas.width = width;
  9290. screenshotCanvas.height = height;
  9291. var renderContext = screenshotCanvas.getContext("2d");
  9292. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9293. var newWidth = width;
  9294. var newHeight = newWidth / ratio;
  9295. if (newHeight > height) {
  9296. newHeight = height;
  9297. newWidth = newHeight * ratio;
  9298. }
  9299. var offsetX = Math.max(0, width - newWidth) / 2;
  9300. var offsetY = Math.max(0, height - newHeight) / 2;
  9301. var renderingCanvas = engine.getRenderingCanvas();
  9302. if (renderContext && renderingCanvas) {
  9303. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9304. }
  9305. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9306. };
  9307. /**
  9308. * Generates an image screenshot from the specified camera.
  9309. *
  9310. * @param engine The engine to use for rendering
  9311. * @param camera The camera to use for rendering
  9312. * @param size This parameter can be set to a single number or to an object with the
  9313. * following (optional) properties: precision, width, height. If a single number is passed,
  9314. * it will be used for both width and height. If an object is passed, the screenshot size
  9315. * will be derived from the parameters. The precision property is a multiplier allowing
  9316. * rendering at a higher or lower resolution.
  9317. * @param successCallback The callback receives a single parameter which contains the
  9318. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9319. * src parameter of an <img> to display it.
  9320. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9321. * Check your browser for supported MIME types.
  9322. * @param samples Texture samples (default: 1)
  9323. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9324. * @param fileName A name for for the downloaded file.
  9325. * @constructor
  9326. */
  9327. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9328. if (mimeType === void 0) { mimeType = "image/png"; }
  9329. if (samples === void 0) { samples = 1; }
  9330. if (antialiasing === void 0) { antialiasing = false; }
  9331. var width;
  9332. var height;
  9333. //If a precision value is specified
  9334. if (size.precision) {
  9335. width = Math.round(engine.getRenderWidth() * size.precision);
  9336. height = Math.round(width / engine.getAspectRatio(camera));
  9337. size = { width: width, height: height };
  9338. }
  9339. else if (size.width && size.height) {
  9340. width = size.width;
  9341. height = size.height;
  9342. }
  9343. //If passing only width, computing height to keep display canvas ratio.
  9344. else if (size.width && !size.height) {
  9345. width = size.width;
  9346. height = Math.round(width / engine.getAspectRatio(camera));
  9347. size = { width: width, height: height };
  9348. }
  9349. //If passing only height, computing width to keep display canvas ratio.
  9350. else if (size.height && !size.width) {
  9351. height = size.height;
  9352. width = Math.round(height * engine.getAspectRatio(camera));
  9353. size = { width: width, height: height };
  9354. }
  9355. //Assuming here that "size" parameter is a number
  9356. else if (!isNaN(size)) {
  9357. height = size;
  9358. width = size;
  9359. }
  9360. else {
  9361. Tools.Error("Invalid 'size' parameter !");
  9362. return;
  9363. }
  9364. var scene = camera.getScene();
  9365. var previousCamera = null;
  9366. if (scene.activeCamera !== camera) {
  9367. previousCamera = scene.activeCamera;
  9368. scene.activeCamera = camera;
  9369. }
  9370. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9371. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9372. texture.renderList = null;
  9373. texture.samples = samples;
  9374. if (antialiasing) {
  9375. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9376. }
  9377. texture.onAfterRenderObservable.add(function () {
  9378. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9379. });
  9380. scene.incrementRenderId();
  9381. scene.resetCachedMaterial();
  9382. texture.render(true);
  9383. texture.dispose();
  9384. if (previousCamera) {
  9385. scene.activeCamera = previousCamera;
  9386. }
  9387. camera.getProjectionMatrix(true); // Force cache refresh;
  9388. };
  9389. // XHR response validator for local file scenario
  9390. Tools.ValidateXHRData = function (xhr, dataType) {
  9391. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9392. if (dataType === void 0) { dataType = 7; }
  9393. try {
  9394. if (dataType & 1) {
  9395. if (xhr.responseText && xhr.responseText.length > 0) {
  9396. return true;
  9397. }
  9398. else if (dataType === 1) {
  9399. return false;
  9400. }
  9401. }
  9402. if (dataType & 2) {
  9403. // Check header width and height since there is no "TGA" magic number
  9404. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9405. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9406. return true;
  9407. }
  9408. else if (dataType === 2) {
  9409. return false;
  9410. }
  9411. }
  9412. if (dataType & 4) {
  9413. // Check for the "DDS" magic number
  9414. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9415. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9416. return true;
  9417. }
  9418. else {
  9419. return false;
  9420. }
  9421. }
  9422. }
  9423. catch (e) {
  9424. // Global protection
  9425. }
  9426. return false;
  9427. };
  9428. /**
  9429. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9430. * Be aware Math.random() could cause collisions, but:
  9431. * "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"
  9432. */
  9433. Tools.RandomId = function () {
  9434. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9435. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9436. return v.toString(16);
  9437. });
  9438. };
  9439. /**
  9440. * Test if the given uri is a base64 string.
  9441. * @param uri The uri to test
  9442. * @return True if the uri is a base64 string or false otherwise.
  9443. */
  9444. Tools.IsBase64 = function (uri) {
  9445. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9446. };
  9447. /**
  9448. * Decode the given base64 uri.
  9449. * @param uri The uri to decode
  9450. * @return The decoded base64 data.
  9451. */
  9452. Tools.DecodeBase64 = function (uri) {
  9453. var decodedString = atob(uri.split(",")[1]);
  9454. var bufferLength = decodedString.length;
  9455. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9456. for (var i = 0; i < bufferLength; i++) {
  9457. bufferView[i] = decodedString.charCodeAt(i);
  9458. }
  9459. return bufferView.buffer;
  9460. };
  9461. Object.defineProperty(Tools, "NoneLogLevel", {
  9462. get: function () {
  9463. return Tools._NoneLogLevel;
  9464. },
  9465. enumerable: true,
  9466. configurable: true
  9467. });
  9468. Object.defineProperty(Tools, "MessageLogLevel", {
  9469. get: function () {
  9470. return Tools._MessageLogLevel;
  9471. },
  9472. enumerable: true,
  9473. configurable: true
  9474. });
  9475. Object.defineProperty(Tools, "WarningLogLevel", {
  9476. get: function () {
  9477. return Tools._WarningLogLevel;
  9478. },
  9479. enumerable: true,
  9480. configurable: true
  9481. });
  9482. Object.defineProperty(Tools, "ErrorLogLevel", {
  9483. get: function () {
  9484. return Tools._ErrorLogLevel;
  9485. },
  9486. enumerable: true,
  9487. configurable: true
  9488. });
  9489. Object.defineProperty(Tools, "AllLogLevel", {
  9490. get: function () {
  9491. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9492. },
  9493. enumerable: true,
  9494. configurable: true
  9495. });
  9496. Tools._AddLogEntry = function (entry) {
  9497. Tools._LogCache = entry + Tools._LogCache;
  9498. if (Tools.OnNewCacheEntry) {
  9499. Tools.OnNewCacheEntry(entry);
  9500. }
  9501. };
  9502. Tools._FormatMessage = function (message) {
  9503. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9504. var date = new Date();
  9505. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9506. };
  9507. Tools._LogDisabled = function (message) {
  9508. // nothing to do
  9509. };
  9510. Tools._LogEnabled = function (message) {
  9511. var formattedMessage = Tools._FormatMessage(message);
  9512. console.log("BJS - " + formattedMessage);
  9513. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9514. Tools._AddLogEntry(entry);
  9515. };
  9516. Tools._WarnDisabled = function (message) {
  9517. // nothing to do
  9518. };
  9519. Tools._WarnEnabled = function (message) {
  9520. var formattedMessage = Tools._FormatMessage(message);
  9521. console.warn("BJS - " + formattedMessage);
  9522. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9523. Tools._AddLogEntry(entry);
  9524. };
  9525. Tools._ErrorDisabled = function (message) {
  9526. // nothing to do
  9527. };
  9528. Tools._ErrorEnabled = function (message) {
  9529. Tools.errorsCount++;
  9530. var formattedMessage = Tools._FormatMessage(message);
  9531. console.error("BJS - " + formattedMessage);
  9532. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9533. Tools._AddLogEntry(entry);
  9534. };
  9535. Object.defineProperty(Tools, "LogCache", {
  9536. get: function () {
  9537. return Tools._LogCache;
  9538. },
  9539. enumerable: true,
  9540. configurable: true
  9541. });
  9542. Tools.ClearLogCache = function () {
  9543. Tools._LogCache = "";
  9544. Tools.errorsCount = 0;
  9545. };
  9546. Object.defineProperty(Tools, "LogLevels", {
  9547. set: function (level) {
  9548. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9549. Tools.Log = Tools._LogEnabled;
  9550. }
  9551. else {
  9552. Tools.Log = Tools._LogDisabled;
  9553. }
  9554. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9555. Tools.Warn = Tools._WarnEnabled;
  9556. }
  9557. else {
  9558. Tools.Warn = Tools._WarnDisabled;
  9559. }
  9560. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9561. Tools.Error = Tools._ErrorEnabled;
  9562. }
  9563. else {
  9564. Tools.Error = Tools._ErrorDisabled;
  9565. }
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Tools.IsWindowObjectExist = function () {
  9571. return (typeof window) !== "undefined";
  9572. };
  9573. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9574. get: function () {
  9575. return Tools._PerformanceNoneLogLevel;
  9576. },
  9577. enumerable: true,
  9578. configurable: true
  9579. });
  9580. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9581. get: function () {
  9582. return Tools._PerformanceUserMarkLogLevel;
  9583. },
  9584. enumerable: true,
  9585. configurable: true
  9586. });
  9587. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9588. get: function () {
  9589. return Tools._PerformanceConsoleLogLevel;
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9595. set: function (level) {
  9596. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9597. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9598. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9599. return;
  9600. }
  9601. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9602. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9603. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9604. return;
  9605. }
  9606. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9607. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9608. },
  9609. enumerable: true,
  9610. configurable: true
  9611. });
  9612. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9613. };
  9614. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9615. };
  9616. Tools._StartUserMark = function (counterName, condition) {
  9617. if (condition === void 0) { condition = true; }
  9618. if (!Tools._performance) {
  9619. if (!Tools.IsWindowObjectExist()) {
  9620. return;
  9621. }
  9622. Tools._performance = window.performance;
  9623. }
  9624. if (!condition || !Tools._performance.mark) {
  9625. return;
  9626. }
  9627. Tools._performance.mark(counterName + "-Begin");
  9628. };
  9629. Tools._EndUserMark = function (counterName, condition) {
  9630. if (condition === void 0) { condition = true; }
  9631. if (!condition || !Tools._performance.mark) {
  9632. return;
  9633. }
  9634. Tools._performance.mark(counterName + "-End");
  9635. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9636. };
  9637. Tools._StartPerformanceConsole = function (counterName, condition) {
  9638. if (condition === void 0) { condition = true; }
  9639. if (!condition) {
  9640. return;
  9641. }
  9642. Tools._StartUserMark(counterName, condition);
  9643. if (console.time) {
  9644. console.time(counterName);
  9645. }
  9646. };
  9647. Tools._EndPerformanceConsole = function (counterName, condition) {
  9648. if (condition === void 0) { condition = true; }
  9649. if (!condition) {
  9650. return;
  9651. }
  9652. Tools._EndUserMark(counterName, condition);
  9653. if (console.time) {
  9654. console.timeEnd(counterName);
  9655. }
  9656. };
  9657. Object.defineProperty(Tools, "Now", {
  9658. get: function () {
  9659. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9660. return window.performance.now();
  9661. }
  9662. return Date.now();
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. /**
  9668. * This method will return the name of the class used to create the instance of the given object.
  9669. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9670. * @param object the object to get the class name from
  9671. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9672. */
  9673. Tools.GetClassName = function (object, isType) {
  9674. if (isType === void 0) { isType = false; }
  9675. var name = null;
  9676. if (!isType && object.getClassName) {
  9677. name = object.getClassName();
  9678. }
  9679. else {
  9680. if (object instanceof Object) {
  9681. var classObj = isType ? object : Object.getPrototypeOf(object);
  9682. name = classObj.constructor["__bjsclassName__"];
  9683. }
  9684. if (!name) {
  9685. name = typeof object;
  9686. }
  9687. }
  9688. return name;
  9689. };
  9690. Tools.First = function (array, predicate) {
  9691. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9692. var el = array_1[_i];
  9693. if (predicate(el)) {
  9694. return el;
  9695. }
  9696. }
  9697. return null;
  9698. };
  9699. /**
  9700. * This method will return the name of the full name of the class, including its owning module (if any).
  9701. * 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).
  9702. * @param object the object to get the class name from
  9703. * @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.
  9704. */
  9705. Tools.getFullClassName = function (object, isType) {
  9706. if (isType === void 0) { isType = false; }
  9707. var className = null;
  9708. var moduleName = null;
  9709. if (!isType && object.getClassName) {
  9710. className = object.getClassName();
  9711. }
  9712. else {
  9713. if (object instanceof Object) {
  9714. var classObj = isType ? object : Object.getPrototypeOf(object);
  9715. className = classObj.constructor["__bjsclassName__"];
  9716. moduleName = classObj.constructor["__bjsmoduleName__"];
  9717. }
  9718. if (!className) {
  9719. className = typeof object;
  9720. }
  9721. }
  9722. if (!className) {
  9723. return null;
  9724. }
  9725. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9726. };
  9727. /**
  9728. * 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.
  9729. * @param array
  9730. */
  9731. Tools.arrayOrStringFeeder = function (array) {
  9732. return function (index) {
  9733. if (index >= array.length) {
  9734. return null;
  9735. }
  9736. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9737. if (val && val.getHashCode) {
  9738. val = val.getHashCode();
  9739. }
  9740. if (typeof val === "string") {
  9741. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9742. }
  9743. return val;
  9744. };
  9745. };
  9746. /**
  9747. * Compute the hashCode of a stream of number
  9748. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9749. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9750. * @return the hash code computed
  9751. */
  9752. Tools.hashCodeFromStream = function (feeder) {
  9753. // Based from here: http://stackoverflow.com/a/7616484/802124
  9754. var hash = 0;
  9755. var index = 0;
  9756. var chr = feeder(index++);
  9757. while (chr != null) {
  9758. hash = ((hash << 5) - hash) + chr;
  9759. hash |= 0; // Convert to 32bit integer
  9760. chr = feeder(index++);
  9761. }
  9762. return hash;
  9763. };
  9764. /**
  9765. * Returns a promise that resolves after the given amount of time.
  9766. * @param delay Number of milliseconds to delay
  9767. * @returns Promise that resolves after the given amount of time
  9768. */
  9769. Tools.DelayAsync = function (delay) {
  9770. return new Promise(function (resolve) {
  9771. setTimeout(function () {
  9772. resolve();
  9773. }, delay);
  9774. });
  9775. };
  9776. Tools.BaseUrl = "";
  9777. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9778. /**
  9779. * Default behaviour for cors in the application.
  9780. * It can be a string if the expected behavior is identical in the entire app.
  9781. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9782. */
  9783. Tools.CorsBehavior = "anonymous";
  9784. Tools.UseFallbackTexture = true;
  9785. /**
  9786. * Use this object to register external classes like custom textures or material
  9787. * to allow the laoders to instantiate them
  9788. */
  9789. Tools.RegisteredExternalClasses = {};
  9790. // Used in case of a texture loading problem
  9791. 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";
  9792. Tools._tmpFloatArray = new Float32Array(1);
  9793. Tools.PreprocessUrl = function (url) {
  9794. return url;
  9795. };
  9796. // Logs
  9797. Tools._NoneLogLevel = 0;
  9798. Tools._MessageLogLevel = 1;
  9799. Tools._WarningLogLevel = 2;
  9800. Tools._ErrorLogLevel = 4;
  9801. Tools._LogCache = "";
  9802. Tools.errorsCount = 0;
  9803. Tools.Log = Tools._LogEnabled;
  9804. Tools.Warn = Tools._WarnEnabled;
  9805. Tools.Error = Tools._ErrorEnabled;
  9806. // Performances
  9807. Tools._PerformanceNoneLogLevel = 0;
  9808. Tools._PerformanceUserMarkLogLevel = 1;
  9809. Tools._PerformanceConsoleLogLevel = 2;
  9810. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9811. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9812. return Tools;
  9813. }());
  9814. BABYLON.Tools = Tools;
  9815. /**
  9816. * This class is used to track a performance counter which is number based.
  9817. * The user has access to many properties which give statistics of different nature
  9818. *
  9819. * The implementer can track two kinds of Performance Counter: time and count
  9820. * 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.
  9821. * 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.
  9822. */
  9823. var PerfCounter = /** @class */ (function () {
  9824. function PerfCounter() {
  9825. this._startMonitoringTime = 0;
  9826. this._min = 0;
  9827. this._max = 0;
  9828. this._average = 0;
  9829. this._lastSecAverage = 0;
  9830. this._current = 0;
  9831. this._totalValueCount = 0;
  9832. this._totalAccumulated = 0;
  9833. this._lastSecAccumulated = 0;
  9834. this._lastSecTime = 0;
  9835. this._lastSecValueCount = 0;
  9836. }
  9837. Object.defineProperty(PerfCounter.prototype, "min", {
  9838. /**
  9839. * Returns the smallest value ever
  9840. */
  9841. get: function () {
  9842. return this._min;
  9843. },
  9844. enumerable: true,
  9845. configurable: true
  9846. });
  9847. Object.defineProperty(PerfCounter.prototype, "max", {
  9848. /**
  9849. * Returns the biggest value ever
  9850. */
  9851. get: function () {
  9852. return this._max;
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. Object.defineProperty(PerfCounter.prototype, "average", {
  9858. /**
  9859. * Returns the average value since the performance counter is running
  9860. */
  9861. get: function () {
  9862. return this._average;
  9863. },
  9864. enumerable: true,
  9865. configurable: true
  9866. });
  9867. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9868. /**
  9869. * Returns the average value of the last second the counter was monitored
  9870. */
  9871. get: function () {
  9872. return this._lastSecAverage;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(PerfCounter.prototype, "current", {
  9878. /**
  9879. * Returns the current value
  9880. */
  9881. get: function () {
  9882. return this._current;
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Object.defineProperty(PerfCounter.prototype, "total", {
  9888. get: function () {
  9889. return this._totalAccumulated;
  9890. },
  9891. enumerable: true,
  9892. configurable: true
  9893. });
  9894. Object.defineProperty(PerfCounter.prototype, "count", {
  9895. get: function () {
  9896. return this._totalValueCount;
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. /**
  9902. * Call this method to start monitoring a new frame.
  9903. * 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.
  9904. */
  9905. PerfCounter.prototype.fetchNewFrame = function () {
  9906. this._totalValueCount++;
  9907. this._current = 0;
  9908. this._lastSecValueCount++;
  9909. };
  9910. /**
  9911. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9912. * @param newCount the count value to add to the monitored count
  9913. * @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.
  9914. */
  9915. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9916. if (!PerfCounter.Enabled) {
  9917. return;
  9918. }
  9919. this._current += newCount;
  9920. if (fetchResult) {
  9921. this._fetchResult();
  9922. }
  9923. };
  9924. /**
  9925. * Start monitoring this performance counter
  9926. */
  9927. PerfCounter.prototype.beginMonitoring = function () {
  9928. if (!PerfCounter.Enabled) {
  9929. return;
  9930. }
  9931. this._startMonitoringTime = Tools.Now;
  9932. };
  9933. /**
  9934. * Compute the time lapsed since the previous beginMonitoring() call.
  9935. * @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
  9936. */
  9937. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9938. if (newFrame === void 0) { newFrame = true; }
  9939. if (!PerfCounter.Enabled) {
  9940. return;
  9941. }
  9942. if (newFrame) {
  9943. this.fetchNewFrame();
  9944. }
  9945. var currentTime = Tools.Now;
  9946. this._current = currentTime - this._startMonitoringTime;
  9947. if (newFrame) {
  9948. this._fetchResult();
  9949. }
  9950. };
  9951. PerfCounter.prototype._fetchResult = function () {
  9952. this._totalAccumulated += this._current;
  9953. this._lastSecAccumulated += this._current;
  9954. // Min/Max update
  9955. this._min = Math.min(this._min, this._current);
  9956. this._max = Math.max(this._max, this._current);
  9957. this._average = this._totalAccumulated / this._totalValueCount;
  9958. // Reset last sec?
  9959. var now = Tools.Now;
  9960. if ((now - this._lastSecTime) > 1000) {
  9961. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9962. this._lastSecTime = now;
  9963. this._lastSecAccumulated = 0;
  9964. this._lastSecValueCount = 0;
  9965. }
  9966. };
  9967. PerfCounter.Enabled = true;
  9968. return PerfCounter;
  9969. }());
  9970. BABYLON.PerfCounter = PerfCounter;
  9971. /**
  9972. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9973. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9974. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9975. * @param name The name of the class, case should be preserved
  9976. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9977. */
  9978. function className(name, module) {
  9979. return function (target) {
  9980. target["__bjsclassName__"] = name;
  9981. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9982. };
  9983. }
  9984. BABYLON.className = className;
  9985. /**
  9986. * An implementation of a loop for asynchronous functions.
  9987. */
  9988. var AsyncLoop = /** @class */ (function () {
  9989. /**
  9990. * Constroctor.
  9991. * @param iterations the number of iterations.
  9992. * @param _fn the function to run each iteration
  9993. * @param _successCallback the callback that will be called upon succesful execution
  9994. * @param offset starting offset.
  9995. */
  9996. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9997. if (offset === void 0) { offset = 0; }
  9998. this.iterations = iterations;
  9999. this._fn = _fn;
  10000. this._successCallback = _successCallback;
  10001. this.index = offset - 1;
  10002. this._done = false;
  10003. }
  10004. /**
  10005. * Execute the next iteration. Must be called after the last iteration was finished.
  10006. */
  10007. AsyncLoop.prototype.executeNext = function () {
  10008. if (!this._done) {
  10009. if (this.index + 1 < this.iterations) {
  10010. ++this.index;
  10011. this._fn(this);
  10012. }
  10013. else {
  10014. this.breakLoop();
  10015. }
  10016. }
  10017. };
  10018. /**
  10019. * Break the loop and run the success callback.
  10020. */
  10021. AsyncLoop.prototype.breakLoop = function () {
  10022. this._done = true;
  10023. this._successCallback();
  10024. };
  10025. /**
  10026. * Helper function
  10027. */
  10028. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10029. if (offset === void 0) { offset = 0; }
  10030. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10031. loop.executeNext();
  10032. return loop;
  10033. };
  10034. /**
  10035. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10036. * @param iterations total number of iterations
  10037. * @param syncedIterations number of synchronous iterations in each async iteration.
  10038. * @param fn the function to call each iteration.
  10039. * @param callback a success call back that will be called when iterating stops.
  10040. * @param breakFunction a break condition (optional)
  10041. * @param timeout timeout settings for the setTimeout function. default - 0.
  10042. * @constructor
  10043. */
  10044. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10045. if (timeout === void 0) { timeout = 0; }
  10046. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10047. if (breakFunction && breakFunction())
  10048. loop.breakLoop();
  10049. else {
  10050. setTimeout(function () {
  10051. for (var i = 0; i < syncedIterations; ++i) {
  10052. var iteration = (loop.index * syncedIterations) + i;
  10053. if (iteration >= iterations)
  10054. break;
  10055. fn(iteration);
  10056. if (breakFunction && breakFunction()) {
  10057. loop.breakLoop();
  10058. break;
  10059. }
  10060. }
  10061. loop.executeNext();
  10062. }, timeout);
  10063. }
  10064. }, callback);
  10065. };
  10066. return AsyncLoop;
  10067. }());
  10068. BABYLON.AsyncLoop = AsyncLoop;
  10069. })(BABYLON || (BABYLON = {}));
  10070. //# sourceMappingURL=babylon.tools.js.map
  10071. var BABYLON;
  10072. (function (BABYLON) {
  10073. var PromiseStates;
  10074. (function (PromiseStates) {
  10075. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10076. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10077. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10078. })(PromiseStates || (PromiseStates = {}));
  10079. var FulFillmentAgregator = /** @class */ (function () {
  10080. function FulFillmentAgregator() {
  10081. this.count = 0;
  10082. this.target = 0;
  10083. this.results = [];
  10084. }
  10085. return FulFillmentAgregator;
  10086. }());
  10087. var InternalPromise = /** @class */ (function () {
  10088. function InternalPromise(resolver) {
  10089. var _this = this;
  10090. this._state = PromiseStates.Pending;
  10091. this._children = new Array();
  10092. this._rejectWasConsumed = false;
  10093. if (!resolver) {
  10094. return;
  10095. }
  10096. try {
  10097. resolver(function (value) {
  10098. _this._resolve(value);
  10099. }, function (reason) {
  10100. _this._reject(reason);
  10101. });
  10102. }
  10103. catch (e) {
  10104. this._reject(e);
  10105. }
  10106. }
  10107. Object.defineProperty(InternalPromise.prototype, "_result", {
  10108. get: function () {
  10109. return this._resultValue;
  10110. },
  10111. set: function (value) {
  10112. this._resultValue = value;
  10113. if (this._parent && this._parent._result === undefined) {
  10114. this._parent._result = value;
  10115. }
  10116. },
  10117. enumerable: true,
  10118. configurable: true
  10119. });
  10120. InternalPromise.prototype.catch = function (onRejected) {
  10121. return this.then(undefined, onRejected);
  10122. };
  10123. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10124. var _this = this;
  10125. var newPromise = new InternalPromise();
  10126. newPromise._onFulfilled = onFulfilled;
  10127. newPromise._onRejected = onRejected;
  10128. // Composition
  10129. this._children.push(newPromise);
  10130. newPromise._parent = this;
  10131. if (this._state !== PromiseStates.Pending) {
  10132. BABYLON.Tools.SetImmediate(function () {
  10133. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10134. var returnedValue = newPromise._resolve(_this._result);
  10135. if (returnedValue !== undefined && returnedValue !== null) {
  10136. if (returnedValue._state !== undefined) {
  10137. var returnedPromise = returnedValue;
  10138. newPromise._children.push(returnedPromise);
  10139. returnedPromise._parent = newPromise;
  10140. newPromise = returnedPromise;
  10141. }
  10142. else {
  10143. newPromise._result = returnedValue;
  10144. }
  10145. }
  10146. }
  10147. else {
  10148. newPromise._reject(_this._reason);
  10149. }
  10150. });
  10151. }
  10152. return newPromise;
  10153. };
  10154. InternalPromise.prototype._moveChildren = function (children) {
  10155. var _this = this;
  10156. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10157. this._children.forEach(function (child) {
  10158. child._parent = _this;
  10159. });
  10160. if (this._state === PromiseStates.Fulfilled) {
  10161. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10162. var child = _b[_i];
  10163. child._resolve(this._result);
  10164. }
  10165. }
  10166. else if (this._state === PromiseStates.Rejected) {
  10167. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10168. var child = _d[_c];
  10169. child._reject(this._reason);
  10170. }
  10171. }
  10172. var _a;
  10173. };
  10174. InternalPromise.prototype._resolve = function (value) {
  10175. try {
  10176. this._state = PromiseStates.Fulfilled;
  10177. var returnedValue = null;
  10178. if (this._onFulfilled) {
  10179. returnedValue = this._onFulfilled(value);
  10180. }
  10181. if (returnedValue !== undefined && returnedValue !== null) {
  10182. if (returnedValue._state !== undefined) {
  10183. // Transmit children
  10184. var returnedPromise = returnedValue;
  10185. returnedPromise._parent = this;
  10186. returnedPromise._moveChildren(this._children);
  10187. value = returnedPromise._result;
  10188. }
  10189. else {
  10190. value = returnedValue;
  10191. }
  10192. }
  10193. this._result = value;
  10194. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10195. var child = _a[_i];
  10196. child._resolve(value);
  10197. }
  10198. this._children.length = 0;
  10199. delete this._onFulfilled;
  10200. delete this._onRejected;
  10201. }
  10202. catch (e) {
  10203. this._reject(e, true);
  10204. }
  10205. };
  10206. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10207. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10208. this._state = PromiseStates.Rejected;
  10209. this._reason = reason;
  10210. if (this._onRejected && !onLocalThrow) {
  10211. try {
  10212. this._onRejected(reason);
  10213. this._rejectWasConsumed = true;
  10214. }
  10215. catch (e) {
  10216. reason = e;
  10217. }
  10218. }
  10219. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10220. var child = _a[_i];
  10221. if (this._rejectWasConsumed) {
  10222. child._resolve(null);
  10223. }
  10224. else {
  10225. child._reject(reason);
  10226. }
  10227. }
  10228. this._children.length = 0;
  10229. delete this._onFulfilled;
  10230. delete this._onRejected;
  10231. };
  10232. InternalPromise.resolve = function (value) {
  10233. var newPromise = new InternalPromise();
  10234. newPromise._resolve(value);
  10235. return newPromise;
  10236. };
  10237. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10238. promise.then(function (value) {
  10239. agregator.results[index] = value;
  10240. agregator.count++;
  10241. if (agregator.count === agregator.target) {
  10242. agregator.rootPromise._resolve(agregator.results);
  10243. }
  10244. return null;
  10245. }, function (reason) {
  10246. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10247. agregator.rootPromise._reject(reason);
  10248. }
  10249. });
  10250. };
  10251. InternalPromise.all = function (promises) {
  10252. var newPromise = new InternalPromise();
  10253. var agregator = new FulFillmentAgregator();
  10254. agregator.target = promises.length;
  10255. agregator.rootPromise = newPromise;
  10256. if (promises.length) {
  10257. for (var index = 0; index < promises.length; index++) {
  10258. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10259. }
  10260. }
  10261. else {
  10262. newPromise._resolve([]);
  10263. }
  10264. return newPromise;
  10265. };
  10266. InternalPromise.race = function (promises) {
  10267. var newPromise = new InternalPromise();
  10268. if (promises.length) {
  10269. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10270. var promise = promises_1[_i];
  10271. promise.then(function (value) {
  10272. if (newPromise) {
  10273. newPromise._resolve(value);
  10274. newPromise = null;
  10275. }
  10276. return null;
  10277. }, function (reason) {
  10278. if (newPromise) {
  10279. newPromise._reject(reason);
  10280. newPromise = null;
  10281. }
  10282. });
  10283. }
  10284. }
  10285. return newPromise;
  10286. };
  10287. return InternalPromise;
  10288. }());
  10289. /**
  10290. * Helper class that provides a small promise polyfill
  10291. */
  10292. var PromisePolyfill = /** @class */ (function () {
  10293. function PromisePolyfill() {
  10294. }
  10295. /**
  10296. * Static function used to check if the polyfill is required
  10297. * If this is the case then the function will inject the polyfill to window.Promise
  10298. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10299. */
  10300. PromisePolyfill.Apply = function (force) {
  10301. if (force === void 0) { force = false; }
  10302. if (force || typeof Promise === 'undefined') {
  10303. var root = window;
  10304. root.Promise = InternalPromise;
  10305. }
  10306. };
  10307. return PromisePolyfill;
  10308. }());
  10309. BABYLON.PromisePolyfill = PromisePolyfill;
  10310. })(BABYLON || (BABYLON = {}));
  10311. //# sourceMappingURL=babylon.promise.js.map
  10312. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10313. var BABYLON;
  10314. (function (BABYLON) {
  10315. /**
  10316. * Helper class to push actions to a pool of workers.
  10317. */
  10318. var WorkerPool = /** @class */ (function () {
  10319. /**
  10320. * Constructor
  10321. * @param workers Array of workers to use for actions
  10322. */
  10323. function WorkerPool(workers) {
  10324. this._pendingActions = new Array();
  10325. this._workerInfos = workers.map(function (worker) { return ({
  10326. worker: worker,
  10327. active: false
  10328. }); });
  10329. }
  10330. /**
  10331. * Terminates all workers and clears any pending actions.
  10332. */
  10333. WorkerPool.prototype.dispose = function () {
  10334. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10335. var workerInfo = _a[_i];
  10336. workerInfo.worker.terminate();
  10337. }
  10338. delete this._workerInfos;
  10339. delete this._pendingActions;
  10340. };
  10341. /**
  10342. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10343. * pended until a worker has completed its action.
  10344. * @param action The action to perform. Call onComplete when the action is complete.
  10345. */
  10346. WorkerPool.prototype.push = function (action) {
  10347. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10348. var workerInfo = _a[_i];
  10349. if (!workerInfo.active) {
  10350. this._execute(workerInfo, action);
  10351. return;
  10352. }
  10353. }
  10354. this._pendingActions.push(action);
  10355. };
  10356. WorkerPool.prototype._execute = function (workerInfo, action) {
  10357. var _this = this;
  10358. workerInfo.active = true;
  10359. action(workerInfo.worker, function () {
  10360. workerInfo.active = false;
  10361. var nextAction = _this._pendingActions.shift();
  10362. if (nextAction) {
  10363. _this._execute(workerInfo, nextAction);
  10364. }
  10365. });
  10366. };
  10367. return WorkerPool;
  10368. }());
  10369. BABYLON.WorkerPool = WorkerPool;
  10370. })(BABYLON || (BABYLON = {}));
  10371. //# sourceMappingURL=babylon.workerPool.js.map
  10372. var BABYLON;
  10373. (function (BABYLON) {
  10374. /**
  10375. * @hidden
  10376. **/
  10377. var _AlphaState = /** @class */ (function () {
  10378. /**
  10379. * Initializes the state.
  10380. */
  10381. function _AlphaState() {
  10382. this._isAlphaBlendDirty = false;
  10383. this._isBlendFunctionParametersDirty = false;
  10384. this._isBlendEquationParametersDirty = false;
  10385. this._isBlendConstantsDirty = false;
  10386. this._alphaBlend = false;
  10387. this._blendFunctionParameters = new Array(4);
  10388. this._blendEquationParameters = new Array(2);
  10389. this._blendConstants = new Array(4);
  10390. this.reset();
  10391. }
  10392. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10393. get: function () {
  10394. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10395. },
  10396. enumerable: true,
  10397. configurable: true
  10398. });
  10399. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10400. get: function () {
  10401. return this._alphaBlend;
  10402. },
  10403. set: function (value) {
  10404. if (this._alphaBlend === value) {
  10405. return;
  10406. }
  10407. this._alphaBlend = value;
  10408. this._isAlphaBlendDirty = true;
  10409. },
  10410. enumerable: true,
  10411. configurable: true
  10412. });
  10413. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10414. if (this._blendConstants[0] === r &&
  10415. this._blendConstants[1] === g &&
  10416. this._blendConstants[2] === b &&
  10417. this._blendConstants[3] === a) {
  10418. return;
  10419. }
  10420. this._blendConstants[0] = r;
  10421. this._blendConstants[1] = g;
  10422. this._blendConstants[2] = b;
  10423. this._blendConstants[3] = a;
  10424. this._isBlendConstantsDirty = true;
  10425. };
  10426. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10427. if (this._blendFunctionParameters[0] === value0 &&
  10428. this._blendFunctionParameters[1] === value1 &&
  10429. this._blendFunctionParameters[2] === value2 &&
  10430. this._blendFunctionParameters[3] === value3) {
  10431. return;
  10432. }
  10433. this._blendFunctionParameters[0] = value0;
  10434. this._blendFunctionParameters[1] = value1;
  10435. this._blendFunctionParameters[2] = value2;
  10436. this._blendFunctionParameters[3] = value3;
  10437. this._isBlendFunctionParametersDirty = true;
  10438. };
  10439. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10440. if (this._blendEquationParameters[0] === rgb &&
  10441. this._blendEquationParameters[1] === alpha) {
  10442. return;
  10443. }
  10444. this._blendEquationParameters[0] = rgb;
  10445. this._blendEquationParameters[1] = alpha;
  10446. this._isBlendEquationParametersDirty = true;
  10447. };
  10448. _AlphaState.prototype.reset = function () {
  10449. this._alphaBlend = false;
  10450. this._blendFunctionParameters[0] = null;
  10451. this._blendFunctionParameters[1] = null;
  10452. this._blendFunctionParameters[2] = null;
  10453. this._blendFunctionParameters[3] = null;
  10454. this._blendEquationParameters[0] = null;
  10455. this._blendEquationParameters[1] = null;
  10456. this._blendConstants[0] = null;
  10457. this._blendConstants[1] = null;
  10458. this._blendConstants[2] = null;
  10459. this._blendConstants[3] = null;
  10460. this._isAlphaBlendDirty = true;
  10461. this._isBlendFunctionParametersDirty = false;
  10462. this._isBlendEquationParametersDirty = false;
  10463. this._isBlendConstantsDirty = false;
  10464. };
  10465. _AlphaState.prototype.apply = function (gl) {
  10466. if (!this.isDirty) {
  10467. return;
  10468. }
  10469. // Alpha blend
  10470. if (this._isAlphaBlendDirty) {
  10471. if (this._alphaBlend) {
  10472. gl.enable(gl.BLEND);
  10473. }
  10474. else {
  10475. gl.disable(gl.BLEND);
  10476. }
  10477. this._isAlphaBlendDirty = false;
  10478. }
  10479. // Alpha function
  10480. if (this._isBlendFunctionParametersDirty) {
  10481. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10482. this._isBlendFunctionParametersDirty = false;
  10483. }
  10484. // Alpha equation
  10485. if (this._isBlendEquationParametersDirty) {
  10486. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10487. this._isBlendEquationParametersDirty = false;
  10488. }
  10489. // Constants
  10490. if (this._isBlendConstantsDirty) {
  10491. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10492. this._isBlendConstantsDirty = false;
  10493. }
  10494. };
  10495. return _AlphaState;
  10496. }());
  10497. BABYLON._AlphaState = _AlphaState;
  10498. })(BABYLON || (BABYLON = {}));
  10499. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10500. var BABYLON;
  10501. (function (BABYLON) {
  10502. /**
  10503. * @hidden
  10504. **/
  10505. var _DepthCullingState = /** @class */ (function () {
  10506. /**
  10507. * Initializes the state.
  10508. */
  10509. function _DepthCullingState() {
  10510. this._isDepthTestDirty = false;
  10511. this._isDepthMaskDirty = false;
  10512. this._isDepthFuncDirty = false;
  10513. this._isCullFaceDirty = false;
  10514. this._isCullDirty = false;
  10515. this._isZOffsetDirty = false;
  10516. this._isFrontFaceDirty = false;
  10517. this.reset();
  10518. }
  10519. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10520. get: function () {
  10521. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10522. },
  10523. enumerable: true,
  10524. configurable: true
  10525. });
  10526. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10527. get: function () {
  10528. return this._zOffset;
  10529. },
  10530. set: function (value) {
  10531. if (this._zOffset === value) {
  10532. return;
  10533. }
  10534. this._zOffset = value;
  10535. this._isZOffsetDirty = true;
  10536. },
  10537. enumerable: true,
  10538. configurable: true
  10539. });
  10540. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10541. get: function () {
  10542. return this._cullFace;
  10543. },
  10544. set: function (value) {
  10545. if (this._cullFace === value) {
  10546. return;
  10547. }
  10548. this._cullFace = value;
  10549. this._isCullFaceDirty = true;
  10550. },
  10551. enumerable: true,
  10552. configurable: true
  10553. });
  10554. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10555. get: function () {
  10556. return this._cull;
  10557. },
  10558. set: function (value) {
  10559. if (this._cull === value) {
  10560. return;
  10561. }
  10562. this._cull = value;
  10563. this._isCullDirty = true;
  10564. },
  10565. enumerable: true,
  10566. configurable: true
  10567. });
  10568. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10569. get: function () {
  10570. return this._depthFunc;
  10571. },
  10572. set: function (value) {
  10573. if (this._depthFunc === value) {
  10574. return;
  10575. }
  10576. this._depthFunc = value;
  10577. this._isDepthFuncDirty = true;
  10578. },
  10579. enumerable: true,
  10580. configurable: true
  10581. });
  10582. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10583. get: function () {
  10584. return this._depthMask;
  10585. },
  10586. set: function (value) {
  10587. if (this._depthMask === value) {
  10588. return;
  10589. }
  10590. this._depthMask = value;
  10591. this._isDepthMaskDirty = true;
  10592. },
  10593. enumerable: true,
  10594. configurable: true
  10595. });
  10596. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10597. get: function () {
  10598. return this._depthTest;
  10599. },
  10600. set: function (value) {
  10601. if (this._depthTest === value) {
  10602. return;
  10603. }
  10604. this._depthTest = value;
  10605. this._isDepthTestDirty = true;
  10606. },
  10607. enumerable: true,
  10608. configurable: true
  10609. });
  10610. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10611. get: function () {
  10612. return this._frontFace;
  10613. },
  10614. set: function (value) {
  10615. if (this._frontFace === value) {
  10616. return;
  10617. }
  10618. this._frontFace = value;
  10619. this._isFrontFaceDirty = true;
  10620. },
  10621. enumerable: true,
  10622. configurable: true
  10623. });
  10624. _DepthCullingState.prototype.reset = function () {
  10625. this._depthMask = true;
  10626. this._depthTest = true;
  10627. this._depthFunc = null;
  10628. this._cullFace = null;
  10629. this._cull = null;
  10630. this._zOffset = 0;
  10631. this._frontFace = null;
  10632. this._isDepthTestDirty = true;
  10633. this._isDepthMaskDirty = true;
  10634. this._isDepthFuncDirty = false;
  10635. this._isCullFaceDirty = false;
  10636. this._isCullDirty = false;
  10637. this._isZOffsetDirty = false;
  10638. this._isFrontFaceDirty = false;
  10639. };
  10640. _DepthCullingState.prototype.apply = function (gl) {
  10641. if (!this.isDirty) {
  10642. return;
  10643. }
  10644. // Cull
  10645. if (this._isCullDirty) {
  10646. if (this.cull) {
  10647. gl.enable(gl.CULL_FACE);
  10648. }
  10649. else {
  10650. gl.disable(gl.CULL_FACE);
  10651. }
  10652. this._isCullDirty = false;
  10653. }
  10654. // Cull face
  10655. if (this._isCullFaceDirty) {
  10656. gl.cullFace(this.cullFace);
  10657. this._isCullFaceDirty = false;
  10658. }
  10659. // Depth mask
  10660. if (this._isDepthMaskDirty) {
  10661. gl.depthMask(this.depthMask);
  10662. this._isDepthMaskDirty = false;
  10663. }
  10664. // Depth test
  10665. if (this._isDepthTestDirty) {
  10666. if (this.depthTest) {
  10667. gl.enable(gl.DEPTH_TEST);
  10668. }
  10669. else {
  10670. gl.disable(gl.DEPTH_TEST);
  10671. }
  10672. this._isDepthTestDirty = false;
  10673. }
  10674. // Depth func
  10675. if (this._isDepthFuncDirty) {
  10676. gl.depthFunc(this.depthFunc);
  10677. this._isDepthFuncDirty = false;
  10678. }
  10679. // zOffset
  10680. if (this._isZOffsetDirty) {
  10681. if (this.zOffset) {
  10682. gl.enable(gl.POLYGON_OFFSET_FILL);
  10683. gl.polygonOffset(this.zOffset, 0);
  10684. }
  10685. else {
  10686. gl.disable(gl.POLYGON_OFFSET_FILL);
  10687. }
  10688. this._isZOffsetDirty = false;
  10689. }
  10690. // Front face
  10691. if (this._isFrontFaceDirty) {
  10692. gl.frontFace(this.frontFace);
  10693. this._isFrontFaceDirty = false;
  10694. }
  10695. };
  10696. return _DepthCullingState;
  10697. }());
  10698. BABYLON._DepthCullingState = _DepthCullingState;
  10699. })(BABYLON || (BABYLON = {}));
  10700. //# sourceMappingURL=babylon.depthCullingState.js.map
  10701. var BABYLON;
  10702. (function (BABYLON) {
  10703. /**
  10704. * @hidden
  10705. **/
  10706. var _StencilState = /** @class */ (function () {
  10707. function _StencilState() {
  10708. this._isStencilTestDirty = false;
  10709. this._isStencilMaskDirty = false;
  10710. this._isStencilFuncDirty = false;
  10711. this._isStencilOpDirty = false;
  10712. this.reset();
  10713. }
  10714. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10715. get: function () {
  10716. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10722. get: function () {
  10723. return this._stencilFunc;
  10724. },
  10725. set: function (value) {
  10726. if (this._stencilFunc === value) {
  10727. return;
  10728. }
  10729. this._stencilFunc = value;
  10730. this._isStencilFuncDirty = true;
  10731. },
  10732. enumerable: true,
  10733. configurable: true
  10734. });
  10735. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10736. get: function () {
  10737. return this._stencilFuncRef;
  10738. },
  10739. set: function (value) {
  10740. if (this._stencilFuncRef === value) {
  10741. return;
  10742. }
  10743. this._stencilFuncRef = value;
  10744. this._isStencilFuncDirty = true;
  10745. },
  10746. enumerable: true,
  10747. configurable: true
  10748. });
  10749. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10750. get: function () {
  10751. return this._stencilFuncMask;
  10752. },
  10753. set: function (value) {
  10754. if (this._stencilFuncMask === value) {
  10755. return;
  10756. }
  10757. this._stencilFuncMask = value;
  10758. this._isStencilFuncDirty = true;
  10759. },
  10760. enumerable: true,
  10761. configurable: true
  10762. });
  10763. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10764. get: function () {
  10765. return this._stencilOpStencilFail;
  10766. },
  10767. set: function (value) {
  10768. if (this._stencilOpStencilFail === value) {
  10769. return;
  10770. }
  10771. this._stencilOpStencilFail = value;
  10772. this._isStencilOpDirty = true;
  10773. },
  10774. enumerable: true,
  10775. configurable: true
  10776. });
  10777. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10778. get: function () {
  10779. return this._stencilOpDepthFail;
  10780. },
  10781. set: function (value) {
  10782. if (this._stencilOpDepthFail === value) {
  10783. return;
  10784. }
  10785. this._stencilOpDepthFail = value;
  10786. this._isStencilOpDirty = true;
  10787. },
  10788. enumerable: true,
  10789. configurable: true
  10790. });
  10791. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10792. get: function () {
  10793. return this._stencilOpStencilDepthPass;
  10794. },
  10795. set: function (value) {
  10796. if (this._stencilOpStencilDepthPass === value) {
  10797. return;
  10798. }
  10799. this._stencilOpStencilDepthPass = value;
  10800. this._isStencilOpDirty = true;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10806. get: function () {
  10807. return this._stencilMask;
  10808. },
  10809. set: function (value) {
  10810. if (this._stencilMask === value) {
  10811. return;
  10812. }
  10813. this._stencilMask = value;
  10814. this._isStencilMaskDirty = true;
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10820. get: function () {
  10821. return this._stencilTest;
  10822. },
  10823. set: function (value) {
  10824. if (this._stencilTest === value) {
  10825. return;
  10826. }
  10827. this._stencilTest = value;
  10828. this._isStencilTestDirty = true;
  10829. },
  10830. enumerable: true,
  10831. configurable: true
  10832. });
  10833. _StencilState.prototype.reset = function () {
  10834. this._stencilTest = false;
  10835. this._stencilMask = 0xFF;
  10836. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10837. this._stencilFuncRef = 1;
  10838. this._stencilFuncMask = 0xFF;
  10839. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10840. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10841. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10842. this._isStencilTestDirty = true;
  10843. this._isStencilMaskDirty = true;
  10844. this._isStencilFuncDirty = true;
  10845. this._isStencilOpDirty = true;
  10846. };
  10847. _StencilState.prototype.apply = function (gl) {
  10848. if (!this.isDirty) {
  10849. return;
  10850. }
  10851. // Stencil test
  10852. if (this._isStencilTestDirty) {
  10853. if (this.stencilTest) {
  10854. gl.enable(gl.STENCIL_TEST);
  10855. }
  10856. else {
  10857. gl.disable(gl.STENCIL_TEST);
  10858. }
  10859. this._isStencilTestDirty = false;
  10860. }
  10861. // Stencil mask
  10862. if (this._isStencilMaskDirty) {
  10863. gl.stencilMask(this.stencilMask);
  10864. this._isStencilMaskDirty = false;
  10865. }
  10866. // Stencil func
  10867. if (this._isStencilFuncDirty) {
  10868. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10869. this._isStencilFuncDirty = false;
  10870. }
  10871. // Stencil op
  10872. if (this._isStencilOpDirty) {
  10873. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10874. this._isStencilOpDirty = false;
  10875. }
  10876. };
  10877. return _StencilState;
  10878. }());
  10879. BABYLON._StencilState = _StencilState;
  10880. })(BABYLON || (BABYLON = {}));
  10881. //# sourceMappingURL=babylon.stencilState.js.map
  10882. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10883. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10884. s = arguments[i];
  10885. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10886. t[p] = s[p];
  10887. }
  10888. return t;
  10889. };
  10890. var BABYLON;
  10891. (function (BABYLON) {
  10892. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10893. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10894. };
  10895. var compileRawShader = function (gl, source, type) {
  10896. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10897. gl.shaderSource(shader, source);
  10898. gl.compileShader(shader);
  10899. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10900. var log = gl.getShaderInfoLog(shader);
  10901. if (log) {
  10902. throw new Error(log);
  10903. }
  10904. }
  10905. if (!shader) {
  10906. throw new Error("Something went wrong while compile the shader.");
  10907. }
  10908. return shader;
  10909. };
  10910. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10911. var magFilter = gl.NEAREST;
  10912. var minFilter = gl.NEAREST;
  10913. switch (samplingMode) {
  10914. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10915. magFilter = gl.LINEAR;
  10916. if (generateMipMaps) {
  10917. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10918. }
  10919. else {
  10920. minFilter = gl.LINEAR;
  10921. }
  10922. break;
  10923. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10924. magFilter = gl.LINEAR;
  10925. if (generateMipMaps) {
  10926. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10927. }
  10928. else {
  10929. minFilter = gl.LINEAR;
  10930. }
  10931. break;
  10932. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10933. magFilter = gl.NEAREST;
  10934. if (generateMipMaps) {
  10935. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10936. }
  10937. else {
  10938. minFilter = gl.NEAREST;
  10939. }
  10940. break;
  10941. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10942. magFilter = gl.NEAREST;
  10943. if (generateMipMaps) {
  10944. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10945. }
  10946. else {
  10947. minFilter = gl.NEAREST;
  10948. }
  10949. break;
  10950. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10951. magFilter = gl.NEAREST;
  10952. if (generateMipMaps) {
  10953. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10954. }
  10955. else {
  10956. minFilter = gl.LINEAR;
  10957. }
  10958. break;
  10959. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10960. magFilter = gl.NEAREST;
  10961. if (generateMipMaps) {
  10962. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10963. }
  10964. else {
  10965. minFilter = gl.LINEAR;
  10966. }
  10967. break;
  10968. case BABYLON.Texture.NEAREST_LINEAR:
  10969. magFilter = gl.NEAREST;
  10970. minFilter = gl.LINEAR;
  10971. break;
  10972. case BABYLON.Texture.NEAREST_NEAREST:
  10973. magFilter = gl.NEAREST;
  10974. minFilter = gl.NEAREST;
  10975. break;
  10976. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10977. magFilter = gl.LINEAR;
  10978. if (generateMipMaps) {
  10979. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10980. }
  10981. else {
  10982. minFilter = gl.NEAREST;
  10983. }
  10984. break;
  10985. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10986. magFilter = gl.LINEAR;
  10987. if (generateMipMaps) {
  10988. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10989. }
  10990. else {
  10991. minFilter = gl.NEAREST;
  10992. }
  10993. break;
  10994. case BABYLON.Texture.LINEAR_LINEAR:
  10995. magFilter = gl.LINEAR;
  10996. minFilter = gl.LINEAR;
  10997. break;
  10998. case BABYLON.Texture.LINEAR_NEAREST:
  10999. magFilter = gl.LINEAR;
  11000. minFilter = gl.NEAREST;
  11001. break;
  11002. }
  11003. return {
  11004. min: minFilter,
  11005. mag: magFilter
  11006. };
  11007. };
  11008. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11009. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11010. var img;
  11011. var onload = function () {
  11012. loadedImages[index] = img;
  11013. loadedImages._internalCount++;
  11014. if (scene) {
  11015. scene._removePendingData(img);
  11016. }
  11017. if (loadedImages._internalCount === 6) {
  11018. onfinish(loadedImages);
  11019. }
  11020. };
  11021. var onerror = function (message, exception) {
  11022. if (scene) {
  11023. scene._removePendingData(img);
  11024. }
  11025. if (onErrorCallBack) {
  11026. onErrorCallBack(message, exception);
  11027. }
  11028. };
  11029. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11030. if (scene) {
  11031. scene._addPendingData(img);
  11032. }
  11033. };
  11034. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11035. if (onError === void 0) { onError = null; }
  11036. var loadedImages = [];
  11037. loadedImages._internalCount = 0;
  11038. for (var index = 0; index < 6; index++) {
  11039. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11040. }
  11041. };
  11042. var BufferPointer = /** @class */ (function () {
  11043. function BufferPointer() {
  11044. }
  11045. return BufferPointer;
  11046. }());
  11047. /**
  11048. * Interface for attribute information associated with buffer instanciation
  11049. */
  11050. var InstancingAttributeInfo = /** @class */ (function () {
  11051. function InstancingAttributeInfo() {
  11052. }
  11053. return InstancingAttributeInfo;
  11054. }());
  11055. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11056. /**
  11057. * Define options used to create a render target texture
  11058. */
  11059. var RenderTargetCreationOptions = /** @class */ (function () {
  11060. function RenderTargetCreationOptions() {
  11061. }
  11062. return RenderTargetCreationOptions;
  11063. }());
  11064. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11065. /**
  11066. * Define options used to create a depth texture
  11067. */
  11068. var DepthTextureCreationOptions = /** @class */ (function () {
  11069. function DepthTextureCreationOptions() {
  11070. }
  11071. return DepthTextureCreationOptions;
  11072. }());
  11073. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11074. /**
  11075. * Class used to describe the capabilities of the engine relatively to the current browser
  11076. */
  11077. var EngineCapabilities = /** @class */ (function () {
  11078. function EngineCapabilities() {
  11079. }
  11080. return EngineCapabilities;
  11081. }());
  11082. BABYLON.EngineCapabilities = EngineCapabilities;
  11083. /**
  11084. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11085. */
  11086. var Engine = /** @class */ (function () {
  11087. /**
  11088. * Creates a new engine
  11089. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11090. * @param antialias defines enable antialiasing (default: false)
  11091. * @param options defines further options to be sent to the getContext() function
  11092. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11093. */
  11094. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11095. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11096. var _this = this;
  11097. // Public members
  11098. /**
  11099. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11100. */
  11101. this.forcePOTTextures = false;
  11102. /**
  11103. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11104. */
  11105. this.isFullscreen = false;
  11106. /**
  11107. * Gets a boolean indicating if the pointer is currently locked
  11108. */
  11109. this.isPointerLock = false;
  11110. /**
  11111. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11112. */
  11113. this.cullBackFaces = true;
  11114. /**
  11115. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11116. */
  11117. this.renderEvenInBackground = true;
  11118. /**
  11119. * Gets or sets a boolean indicating that cache can be kept between frames
  11120. */
  11121. this.preventCacheWipeBetweenFrames = false;
  11122. /**
  11123. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11124. **/
  11125. this.enableOfflineSupport = false;
  11126. /**
  11127. * 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)
  11128. **/
  11129. this.disableManifestCheck = false;
  11130. /**
  11131. * Gets the list of created scenes
  11132. */
  11133. this.scenes = new Array();
  11134. /**
  11135. * Gets the list of created postprocesses
  11136. */
  11137. this.postProcesses = new Array();
  11138. // Observables
  11139. /**
  11140. * Observable event triggered each time the rendering canvas is resized
  11141. */
  11142. this.onResizeObservable = new BABYLON.Observable();
  11143. /**
  11144. * Observable event triggered each time the canvas loses focus
  11145. */
  11146. this.onCanvasBlurObservable = new BABYLON.Observable();
  11147. /**
  11148. * Observable event triggered each time the canvas gains focus
  11149. */
  11150. this.onCanvasFocusObservable = new BABYLON.Observable();
  11151. /**
  11152. * Observable event triggered each time the canvas receives pointerout event
  11153. */
  11154. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11155. /**
  11156. * Observable event triggered before each texture is initialized
  11157. */
  11158. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11159. //WebVR
  11160. this._vrDisplay = undefined;
  11161. this._vrSupported = false;
  11162. this._vrExclusivePointerMode = false;
  11163. // Uniform buffers list
  11164. /**
  11165. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11166. */
  11167. this.disableUniformBuffers = false;
  11168. /** @hidden */
  11169. this._uniformBuffers = new Array();
  11170. // Observables
  11171. /**
  11172. * Observable raised when the engine begins a new frame
  11173. */
  11174. this.onBeginFrameObservable = new BABYLON.Observable();
  11175. /**
  11176. * Observable raised when the engine ends the current frame
  11177. */
  11178. this.onEndFrameObservable = new BABYLON.Observable();
  11179. /**
  11180. * Observable raised when the engine is about to compile a shader
  11181. */
  11182. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11183. /**
  11184. * Observable raised when the engine has jsut compiled a shader
  11185. */
  11186. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11187. this._windowIsBackground = false;
  11188. this._webGLVersion = 1.0;
  11189. /** @hidden */
  11190. this._badOS = false;
  11191. /** @hidden */
  11192. this._badDesktopOS = false;
  11193. /**
  11194. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11195. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11196. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11197. */
  11198. this.disableTextureBindingOptimization = false;
  11199. /**
  11200. * Observable signaled when VR display mode changes
  11201. */
  11202. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11203. /**
  11204. * Observable signaled when VR request present is complete
  11205. */
  11206. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11207. /**
  11208. * Observable signaled when VR request present starts
  11209. */
  11210. this.onVRRequestPresentStart = new BABYLON.Observable();
  11211. this._colorWrite = true;
  11212. /** @hidden */
  11213. this._drawCalls = new BABYLON.PerfCounter();
  11214. /** @hidden */
  11215. this._textureCollisions = new BABYLON.PerfCounter();
  11216. this._renderingQueueLaunched = false;
  11217. this._activeRenderLoops = new Array();
  11218. // Deterministic lockstepMaxSteps
  11219. this._deterministicLockstep = false;
  11220. this._lockstepMaxSteps = 4;
  11221. // Lost context
  11222. /**
  11223. * Observable signaled when a context lost event is raised
  11224. */
  11225. this.onContextLostObservable = new BABYLON.Observable();
  11226. /**
  11227. * Observable signaled when a context restored event is raised
  11228. */
  11229. this.onContextRestoredObservable = new BABYLON.Observable();
  11230. this._contextWasLost = false;
  11231. this._doNotHandleContextLost = false;
  11232. // FPS
  11233. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11234. this._fps = 60;
  11235. this._deltaTime = 0;
  11236. /**
  11237. * Turn this value on if you want to pause FPS computation when in background
  11238. */
  11239. this.disablePerformanceMonitorInBackground = false;
  11240. // States
  11241. /** @hidden */
  11242. this._depthCullingState = new BABYLON._DepthCullingState();
  11243. /** @hidden */
  11244. this._stencilState = new BABYLON._StencilState();
  11245. /** @hidden */
  11246. this._alphaState = new BABYLON._AlphaState();
  11247. /** @hidden */
  11248. this._alphaMode = Engine.ALPHA_DISABLE;
  11249. // Cache
  11250. this._internalTexturesCache = new Array();
  11251. /** @hidden */
  11252. this._activeChannel = 0;
  11253. this._currentTextureChannel = -1;
  11254. /** @hidden */
  11255. this._boundTexturesCache = {};
  11256. this._compiledEffects = {};
  11257. this._vertexAttribArraysEnabled = [];
  11258. this._uintIndicesCurrentlySet = false;
  11259. this._currentBoundBuffer = new Array();
  11260. this._currentBufferPointers = new Array();
  11261. this._currentInstanceLocations = new Array();
  11262. this._currentInstanceBuffers = new Array();
  11263. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11264. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11265. this._vaoRecordInProgress = false;
  11266. this._mustWipeVertexAttributes = false;
  11267. this._nextFreeTextureSlots = new Array();
  11268. this._maxSimultaneousTextures = 0;
  11269. this._activeRequests = new Array();
  11270. // Hardware supported Compressed Textures
  11271. this._texturesSupported = new Array();
  11272. this._onVRFullScreenTriggered = function () {
  11273. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11274. //get the old size before we change
  11275. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11276. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11277. //get the width and height, change the render size
  11278. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11279. _this.setHardwareScalingLevel(1);
  11280. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11281. }
  11282. else {
  11283. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11284. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11285. }
  11286. };
  11287. this._boundUniforms = {};
  11288. // Register promises
  11289. BABYLON.PromisePolyfill.Apply();
  11290. var canvas = null;
  11291. Engine.Instances.push(this);
  11292. if (!canvasOrContext) {
  11293. return;
  11294. }
  11295. options = options || {};
  11296. if (canvasOrContext.getContext) {
  11297. canvas = canvasOrContext;
  11298. this._renderingCanvas = canvas;
  11299. if (antialias != null) {
  11300. options.antialias = antialias;
  11301. }
  11302. if (options.deterministicLockstep === undefined) {
  11303. options.deterministicLockstep = false;
  11304. }
  11305. if (options.lockstepMaxSteps === undefined) {
  11306. options.lockstepMaxSteps = 4;
  11307. }
  11308. if (options.preserveDrawingBuffer === undefined) {
  11309. options.preserveDrawingBuffer = false;
  11310. }
  11311. if (options.audioEngine === undefined) {
  11312. options.audioEngine = true;
  11313. }
  11314. if (options.stencil === undefined) {
  11315. options.stencil = true;
  11316. }
  11317. this._deterministicLockstep = options.deterministicLockstep;
  11318. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11319. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11320. // Exceptions
  11321. if (navigator && navigator.userAgent) {
  11322. var ua = navigator.userAgent;
  11323. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11324. var exception = _a[_i];
  11325. var key = exception.key;
  11326. var targets = exception.targets;
  11327. if (ua.indexOf(key) > -1) {
  11328. if (exception.capture && exception.captureConstraint) {
  11329. var capture = exception.capture;
  11330. var constraint = exception.captureConstraint;
  11331. var regex = new RegExp(capture);
  11332. var matches = regex.exec(ua);
  11333. if (matches && matches.length > 0) {
  11334. var capturedValue = parseInt(matches[matches.length - 1]);
  11335. if (capturedValue >= constraint) {
  11336. continue;
  11337. }
  11338. }
  11339. }
  11340. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11341. var target = targets_1[_b];
  11342. switch (target) {
  11343. case "uniformBuffer":
  11344. this.disableUniformBuffers = true;
  11345. break;
  11346. case "textureBindingOptimization":
  11347. this.disableTextureBindingOptimization = true;
  11348. break;
  11349. }
  11350. }
  11351. }
  11352. }
  11353. }
  11354. // GL
  11355. if (!options.disableWebGL2Support) {
  11356. try {
  11357. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11358. if (this._gl) {
  11359. this._webGLVersion = 2.0;
  11360. }
  11361. }
  11362. catch (e) {
  11363. // Do nothing
  11364. }
  11365. }
  11366. if (!this._gl) {
  11367. if (!canvas) {
  11368. throw new Error("The provided canvas is null or undefined.");
  11369. }
  11370. try {
  11371. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11372. }
  11373. catch (e) {
  11374. throw new Error("WebGL not supported");
  11375. }
  11376. }
  11377. if (!this._gl) {
  11378. throw new Error("WebGL not supported");
  11379. }
  11380. this._onCanvasFocus = function () {
  11381. _this.onCanvasFocusObservable.notifyObservers(_this);
  11382. };
  11383. this._onCanvasBlur = function () {
  11384. _this.onCanvasBlurObservable.notifyObservers(_this);
  11385. };
  11386. canvas.addEventListener("focus", this._onCanvasFocus);
  11387. canvas.addEventListener("blur", this._onCanvasBlur);
  11388. this._onBlur = function () {
  11389. if (_this.disablePerformanceMonitorInBackground) {
  11390. _this._performanceMonitor.disable();
  11391. }
  11392. _this._windowIsBackground = true;
  11393. };
  11394. this._onFocus = function () {
  11395. if (_this.disablePerformanceMonitorInBackground) {
  11396. _this._performanceMonitor.enable();
  11397. }
  11398. _this._windowIsBackground = false;
  11399. };
  11400. this._onCanvasPointerOut = function (ev) {
  11401. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11402. };
  11403. window.addEventListener("blur", this._onBlur);
  11404. window.addEventListener("focus", this._onFocus);
  11405. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11406. // Context lost
  11407. if (!this._doNotHandleContextLost) {
  11408. this._onContextLost = function (evt) {
  11409. evt.preventDefault();
  11410. _this._contextWasLost = true;
  11411. BABYLON.Tools.Warn("WebGL context lost.");
  11412. _this.onContextLostObservable.notifyObservers(_this);
  11413. };
  11414. this._onContextRestored = function (evt) {
  11415. // Adding a timeout to avoid race condition at browser level
  11416. setTimeout(function () {
  11417. // Rebuild gl context
  11418. _this._initGLContext();
  11419. // Rebuild effects
  11420. _this._rebuildEffects();
  11421. // Rebuild textures
  11422. _this._rebuildInternalTextures();
  11423. // Rebuild buffers
  11424. _this._rebuildBuffers();
  11425. // Cache
  11426. _this.wipeCaches(true);
  11427. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11428. _this.onContextRestoredObservable.notifyObservers(_this);
  11429. _this._contextWasLost = false;
  11430. }, 0);
  11431. };
  11432. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11433. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11434. }
  11435. }
  11436. else {
  11437. this._gl = canvasOrContext;
  11438. this._renderingCanvas = this._gl.canvas;
  11439. if (this._gl.renderbufferStorageMultisample) {
  11440. this._webGLVersion = 2.0;
  11441. }
  11442. options.stencil = this._gl.getContextAttributes().stencil;
  11443. }
  11444. // Viewport
  11445. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11446. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11447. this.resize();
  11448. this._isStencilEnable = options.stencil ? true : false;
  11449. this._initGLContext();
  11450. if (canvas) {
  11451. // Fullscreen
  11452. this._onFullscreenChange = function () {
  11453. if (document.fullscreen !== undefined) {
  11454. _this.isFullscreen = document.fullscreen;
  11455. }
  11456. else if (document.mozFullScreen !== undefined) {
  11457. _this.isFullscreen = document.mozFullScreen;
  11458. }
  11459. else if (document.webkitIsFullScreen !== undefined) {
  11460. _this.isFullscreen = document.webkitIsFullScreen;
  11461. }
  11462. else if (document.msIsFullScreen !== undefined) {
  11463. _this.isFullscreen = document.msIsFullScreen;
  11464. }
  11465. // Pointer lock
  11466. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11467. canvas.requestPointerLock = canvas.requestPointerLock ||
  11468. canvas.msRequestPointerLock ||
  11469. canvas.mozRequestPointerLock ||
  11470. canvas.webkitRequestPointerLock;
  11471. if (canvas.requestPointerLock) {
  11472. canvas.requestPointerLock();
  11473. }
  11474. }
  11475. };
  11476. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11477. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11478. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11479. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11480. // Pointer lock
  11481. this._onPointerLockChange = function () {
  11482. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11483. document.webkitPointerLockElement === canvas ||
  11484. document.msPointerLockElement === canvas ||
  11485. document.pointerLockElement === canvas);
  11486. };
  11487. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11488. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11489. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11490. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11491. this._onVRDisplayPointerRestricted = function () {
  11492. if (canvas) {
  11493. canvas.requestPointerLock();
  11494. }
  11495. };
  11496. this._onVRDisplayPointerUnrestricted = function () {
  11497. document.exitPointerLock();
  11498. };
  11499. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11500. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11501. }
  11502. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11503. Engine.audioEngine = new BABYLON.AudioEngine();
  11504. }
  11505. // Prepare buffer pointers
  11506. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11507. this._currentBufferPointers[i] = new BufferPointer();
  11508. }
  11509. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11510. // Load WebVR Devices
  11511. if (options.autoEnableWebVR) {
  11512. this.initWebVR();
  11513. }
  11514. // Detect if we are running on a faulty buggy OS.
  11515. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11516. // Detect if we are running on a faulty buggy desktop OS.
  11517. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11518. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11519. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11520. }
  11521. Object.defineProperty(Engine, "LastCreatedEngine", {
  11522. /**
  11523. * Gets the latest created engine
  11524. */
  11525. get: function () {
  11526. if (Engine.Instances.length === 0) {
  11527. return null;
  11528. }
  11529. return Engine.Instances[Engine.Instances.length - 1];
  11530. },
  11531. enumerable: true,
  11532. configurable: true
  11533. });
  11534. Object.defineProperty(Engine, "LastCreatedScene", {
  11535. /**
  11536. * Gets the latest created scene
  11537. */
  11538. get: function () {
  11539. var lastCreatedEngine = Engine.LastCreatedEngine;
  11540. if (!lastCreatedEngine) {
  11541. return null;
  11542. }
  11543. if (lastCreatedEngine.scenes.length === 0) {
  11544. return null;
  11545. }
  11546. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11547. },
  11548. enumerable: true,
  11549. configurable: true
  11550. });
  11551. /**
  11552. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11553. * @param flag defines which part of the materials must be marked as dirty
  11554. * @param predicate defines a predicate used to filter which materials should be affected
  11555. */
  11556. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11557. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11558. var engine = Engine.Instances[engineIndex];
  11559. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11560. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11561. }
  11562. }
  11563. };
  11564. Object.defineProperty(Engine, "NEVER", {
  11565. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11566. get: function () {
  11567. return Engine._NEVER;
  11568. },
  11569. enumerable: true,
  11570. configurable: true
  11571. });
  11572. Object.defineProperty(Engine, "ALWAYS", {
  11573. /** 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 */
  11574. get: function () {
  11575. return Engine._ALWAYS;
  11576. },
  11577. enumerable: true,
  11578. configurable: true
  11579. });
  11580. Object.defineProperty(Engine, "LESS", {
  11581. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11582. get: function () {
  11583. return Engine._LESS;
  11584. },
  11585. enumerable: true,
  11586. configurable: true
  11587. });
  11588. Object.defineProperty(Engine, "EQUAL", {
  11589. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11590. get: function () {
  11591. return Engine._EQUAL;
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(Engine, "LEQUAL", {
  11597. /** 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 */
  11598. get: function () {
  11599. return Engine._LEQUAL;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Object.defineProperty(Engine, "GREATER", {
  11605. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11606. get: function () {
  11607. return Engine._GREATER;
  11608. },
  11609. enumerable: true,
  11610. configurable: true
  11611. });
  11612. Object.defineProperty(Engine, "GEQUAL", {
  11613. /** 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 */
  11614. get: function () {
  11615. return Engine._GEQUAL;
  11616. },
  11617. enumerable: true,
  11618. configurable: true
  11619. });
  11620. Object.defineProperty(Engine, "NOTEQUAL", {
  11621. /** 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 */
  11622. get: function () {
  11623. return Engine._NOTEQUAL;
  11624. },
  11625. enumerable: true,
  11626. configurable: true
  11627. });
  11628. Object.defineProperty(Engine, "KEEP", {
  11629. /** Passed to stencilOperation to specify that stencil value must be kept */
  11630. get: function () {
  11631. return Engine._KEEP;
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. Object.defineProperty(Engine, "REPLACE", {
  11637. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11638. get: function () {
  11639. return Engine._REPLACE;
  11640. },
  11641. enumerable: true,
  11642. configurable: true
  11643. });
  11644. Object.defineProperty(Engine, "INCR", {
  11645. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11646. get: function () {
  11647. return Engine._INCR;
  11648. },
  11649. enumerable: true,
  11650. configurable: true
  11651. });
  11652. Object.defineProperty(Engine, "DECR", {
  11653. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11654. get: function () {
  11655. return Engine._DECR;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Engine, "INVERT", {
  11661. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11662. get: function () {
  11663. return Engine._INVERT;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine, "INCR_WRAP", {
  11669. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11670. get: function () {
  11671. return Engine._INCR_WRAP;
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Engine, "DECR_WRAP", {
  11677. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11678. get: function () {
  11679. return Engine._DECR_WRAP;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11685. // Alpha
  11686. /** Defines that alpha blending is disabled */
  11687. get: function () {
  11688. return Engine._ALPHA_DISABLE;
  11689. },
  11690. enumerable: true,
  11691. configurable: true
  11692. });
  11693. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11694. /** Defines that alpha blending to SRC + DEST */
  11695. get: function () {
  11696. return Engine._ALPHA_ONEONE;
  11697. },
  11698. enumerable: true,
  11699. configurable: true
  11700. });
  11701. Object.defineProperty(Engine, "ALPHA_ADD", {
  11702. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11703. get: function () {
  11704. return Engine._ALPHA_ADD;
  11705. },
  11706. enumerable: true,
  11707. configurable: true
  11708. });
  11709. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11710. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11711. get: function () {
  11712. return Engine._ALPHA_COMBINE;
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11718. /** Defines that alpha blending to DEST - SRC * DEST */
  11719. get: function () {
  11720. return Engine._ALPHA_SUBTRACT;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11726. /** Defines that alpha blending to SRC * DEST */
  11727. get: function () {
  11728. return Engine._ALPHA_MULTIPLY;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11734. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11735. get: function () {
  11736. return Engine._ALPHA_MAXIMIZED;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11742. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11743. get: function () {
  11744. return Engine._ALPHA_PREMULTIPLIED;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11750. /**
  11751. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11752. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11753. */
  11754. get: function () {
  11755. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11756. },
  11757. enumerable: true,
  11758. configurable: true
  11759. });
  11760. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11761. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11762. get: function () {
  11763. return Engine._ALPHA_INTERPOLATE;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11769. /**
  11770. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11771. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11772. */
  11773. get: function () {
  11774. return Engine._ALPHA_SCREENMODE;
  11775. },
  11776. enumerable: true,
  11777. configurable: true
  11778. });
  11779. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11780. // Delays
  11781. /** Defines that the ressource is not delayed*/
  11782. get: function () {
  11783. return Engine._DELAYLOADSTATE_NONE;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11789. /** Defines that the ressource was successfully delay loaded */
  11790. get: function () {
  11791. return Engine._DELAYLOADSTATE_LOADED;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11797. /** Defines that the ressource is currently delay loading */
  11798. get: function () {
  11799. return Engine._DELAYLOADSTATE_LOADING;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11805. /** Defines that the ressource is delayed and has not started loading */
  11806. get: function () {
  11807. return Engine._DELAYLOADSTATE_NOTLOADED;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11813. /** ALPHA */
  11814. get: function () {
  11815. return Engine._TEXTUREFORMAT_ALPHA;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11821. /** LUMINANCE */
  11822. get: function () {
  11823. return Engine._TEXTUREFORMAT_LUMINANCE;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11829. /**
  11830. * R32F
  11831. */
  11832. get: function () {
  11833. return Engine._TEXTUREFORMAT_R32F;
  11834. },
  11835. enumerable: true,
  11836. configurable: true
  11837. });
  11838. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11839. /**
  11840. * RG32F
  11841. */
  11842. get: function () {
  11843. return Engine._TEXTUREFORMAT_RG32F;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11849. /**
  11850. * RGB32F
  11851. */
  11852. get: function () {
  11853. return Engine._TEXTUREFORMAT_RGB32F;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11859. /**
  11860. * RGBA32F
  11861. */
  11862. get: function () {
  11863. return Engine._TEXTUREFORMAT_RGBA32F;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11869. /** LUMINANCE_ALPHA */
  11870. get: function () {
  11871. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11877. /** RGB */
  11878. get: function () {
  11879. return Engine._TEXTUREFORMAT_RGB;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11885. /** RGBA */
  11886. get: function () {
  11887. return Engine._TEXTUREFORMAT_RGBA;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11893. /** UNSIGNED_INT */
  11894. get: function () {
  11895. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11901. /** FLOAT */
  11902. get: function () {
  11903. return Engine._TEXTURETYPE_FLOAT;
  11904. },
  11905. enumerable: true,
  11906. configurable: true
  11907. });
  11908. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11909. /** HALF_FLOAT */
  11910. get: function () {
  11911. return Engine._TEXTURETYPE_HALF_FLOAT;
  11912. },
  11913. enumerable: true,
  11914. configurable: true
  11915. });
  11916. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11917. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11918. get: function () {
  11919. return Engine._SCALEMODE_FLOOR;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11925. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11926. get: function () {
  11927. return Engine._SCALEMODE_NEAREST;
  11928. },
  11929. enumerable: true,
  11930. configurable: true
  11931. });
  11932. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11933. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11934. get: function () {
  11935. return Engine._SCALEMODE_CEILING;
  11936. },
  11937. enumerable: true,
  11938. configurable: true
  11939. });
  11940. Object.defineProperty(Engine, "Version", {
  11941. /**
  11942. * Returns the current version of the framework
  11943. */
  11944. get: function () {
  11945. return "3.2.0-rc.2";
  11946. },
  11947. enumerable: true,
  11948. configurable: true
  11949. });
  11950. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11951. /**
  11952. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11953. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11954. */
  11955. get: function () {
  11956. return this._vrExclusivePointerMode;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11962. /**
  11963. * Gets a boolean indicating that the engine supports uniform buffers
  11964. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11965. */
  11966. get: function () {
  11967. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11973. /**
  11974. * Gets a boolean indicating that only power of 2 textures are supported
  11975. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11976. */
  11977. get: function () {
  11978. return this._webGLVersion < 2 || this.forcePOTTextures;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11984. /**
  11985. * Gets the performance monitor attached to this engine
  11986. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11987. */
  11988. get: function () {
  11989. return this._performanceMonitor;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11995. /**
  11996. * Gets the list of texture formats supported
  11997. */
  11998. get: function () {
  11999. return this._texturesSupported;
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12005. /**
  12006. * Gets the list of texture formats in use
  12007. */
  12008. get: function () {
  12009. return this._textureFormatInUse;
  12010. },
  12011. enumerable: true,
  12012. configurable: true
  12013. });
  12014. Object.defineProperty(Engine.prototype, "currentViewport", {
  12015. /**
  12016. * Gets the current viewport
  12017. */
  12018. get: function () {
  12019. return this._cachedViewport;
  12020. },
  12021. enumerable: true,
  12022. configurable: true
  12023. });
  12024. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12025. /**
  12026. * Gets the default empty texture
  12027. */
  12028. get: function () {
  12029. if (!this._emptyTexture) {
  12030. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12031. }
  12032. return this._emptyTexture;
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12038. /**
  12039. * Gets the default empty 3D texture
  12040. */
  12041. get: function () {
  12042. if (!this._emptyTexture3D) {
  12043. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12044. }
  12045. return this._emptyTexture3D;
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12051. /**
  12052. * Gets the default empty cube texture
  12053. */
  12054. get: function () {
  12055. if (!this._emptyCubeTexture) {
  12056. var faceData = new Uint8Array(4);
  12057. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12058. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12059. }
  12060. return this._emptyCubeTexture;
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Engine.prototype._rebuildInternalTextures = function () {
  12066. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12067. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12068. var internalTexture = currentState_1[_i];
  12069. internalTexture._rebuild();
  12070. }
  12071. };
  12072. Engine.prototype._rebuildEffects = function () {
  12073. for (var key in this._compiledEffects) {
  12074. var effect = this._compiledEffects[key];
  12075. effect._prepareEffect();
  12076. }
  12077. BABYLON.Effect.ResetCache();
  12078. };
  12079. Engine.prototype._rebuildBuffers = function () {
  12080. // Index / Vertex
  12081. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12082. var scene = _a[_i];
  12083. scene.resetCachedMaterial();
  12084. scene._rebuildGeometries();
  12085. scene._rebuildTextures();
  12086. }
  12087. // Uniforms
  12088. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12089. var uniformBuffer = _c[_b];
  12090. uniformBuffer._rebuild();
  12091. }
  12092. };
  12093. Engine.prototype._initGLContext = function () {
  12094. // Caps
  12095. this._caps = new EngineCapabilities();
  12096. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12097. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12098. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12099. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12100. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12101. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12102. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12103. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12104. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12105. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12106. // Infos
  12107. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12108. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12109. if (rendererInfo != null) {
  12110. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12111. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12112. }
  12113. if (!this._glVendor) {
  12114. this._glVendor = "Unknown vendor";
  12115. }
  12116. if (!this._glRenderer) {
  12117. this._glRenderer = "Unknown renderer";
  12118. }
  12119. // Constants
  12120. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12121. if (this._gl.RGBA16F !== 0x881A) {
  12122. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12123. }
  12124. if (this._gl.RGBA32F !== 0x8814) {
  12125. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12126. }
  12127. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12128. this._gl.DEPTH24_STENCIL8 = 35056;
  12129. }
  12130. // Extensions
  12131. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12132. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12133. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12134. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12135. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12136. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12137. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12138. 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');
  12139. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12140. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12141. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12142. this._caps.highPrecisionShaderSupported = true;
  12143. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12144. if (this._caps.timerQuery) {
  12145. if (this._webGLVersion === 1) {
  12146. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12147. }
  12148. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12149. }
  12150. // Checks if some of the format renders first to allow the use of webgl inspector.
  12151. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12152. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12153. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12154. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12155. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12156. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12157. if (this._webGLVersion > 1) {
  12158. this._gl.HALF_FLOAT_OES = 0x140B;
  12159. }
  12160. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12161. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12162. // Draw buffers
  12163. if (this._webGLVersion > 1) {
  12164. this._caps.drawBuffersExtension = true;
  12165. }
  12166. else {
  12167. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12168. if (drawBuffersExtension !== null) {
  12169. this._caps.drawBuffersExtension = true;
  12170. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12171. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12172. for (var i = 0; i < 16; i++) {
  12173. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12174. }
  12175. }
  12176. else {
  12177. this._caps.drawBuffersExtension = false;
  12178. }
  12179. }
  12180. // Depth Texture
  12181. if (this._webGLVersion > 1) {
  12182. this._caps.depthTextureExtension = true;
  12183. }
  12184. else {
  12185. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12186. if (depthTextureExtension != null) {
  12187. this._caps.depthTextureExtension = true;
  12188. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12189. }
  12190. }
  12191. // Vertex array object
  12192. if (this._webGLVersion > 1) {
  12193. this._caps.vertexArrayObject = true;
  12194. }
  12195. else {
  12196. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12197. if (vertexArrayObjectExtension != null) {
  12198. this._caps.vertexArrayObject = true;
  12199. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12200. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12201. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12202. }
  12203. else {
  12204. this._caps.vertexArrayObject = false;
  12205. }
  12206. }
  12207. // Instances count
  12208. if (this._webGLVersion > 1) {
  12209. this._caps.instancedArrays = true;
  12210. }
  12211. else {
  12212. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12213. if (instanceExtension != null) {
  12214. this._caps.instancedArrays = true;
  12215. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12216. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12217. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12218. }
  12219. else {
  12220. this._caps.instancedArrays = false;
  12221. }
  12222. }
  12223. // Intelligently add supported compressed formats in order to check for.
  12224. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12225. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12226. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12227. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12228. if (this._caps.astc)
  12229. this.texturesSupported.push('-astc.ktx');
  12230. if (this._caps.s3tc)
  12231. this.texturesSupported.push('-dxt.ktx');
  12232. if (this._caps.pvrtc)
  12233. this.texturesSupported.push('-pvrtc.ktx');
  12234. if (this._caps.etc2)
  12235. this.texturesSupported.push('-etc2.ktx');
  12236. if (this._caps.etc1)
  12237. this.texturesSupported.push('-etc1.ktx');
  12238. if (this._gl.getShaderPrecisionFormat) {
  12239. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12240. if (highp) {
  12241. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12242. }
  12243. }
  12244. // Depth buffer
  12245. this.setDepthBuffer(true);
  12246. this.setDepthFunctionToLessOrEqual();
  12247. this.setDepthWrite(true);
  12248. // Texture maps
  12249. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12250. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12251. this._nextFreeTextureSlots.push(slot);
  12252. }
  12253. };
  12254. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12255. /**
  12256. * Gets version of the current webGL context
  12257. */
  12258. get: function () {
  12259. return this._webGLVersion;
  12260. },
  12261. enumerable: true,
  12262. configurable: true
  12263. });
  12264. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12265. /**
  12266. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12267. */
  12268. get: function () {
  12269. return this._isStencilEnable;
  12270. },
  12271. enumerable: true,
  12272. configurable: true
  12273. });
  12274. Engine.prototype._prepareWorkingCanvas = function () {
  12275. if (this._workingCanvas) {
  12276. return;
  12277. }
  12278. this._workingCanvas = document.createElement("canvas");
  12279. var context = this._workingCanvas.getContext("2d");
  12280. if (context) {
  12281. this._workingContext = context;
  12282. }
  12283. };
  12284. /**
  12285. * Reset the texture cache to empty state
  12286. */
  12287. Engine.prototype.resetTextureCache = function () {
  12288. for (var key in this._boundTexturesCache) {
  12289. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12290. continue;
  12291. }
  12292. var boundTexture = this._boundTexturesCache[key];
  12293. if (boundTexture) {
  12294. this._removeDesignatedSlot(boundTexture);
  12295. }
  12296. this._boundTexturesCache[key] = null;
  12297. }
  12298. if (!this.disableTextureBindingOptimization) {
  12299. this._nextFreeTextureSlots = [];
  12300. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12301. this._nextFreeTextureSlots.push(slot);
  12302. }
  12303. }
  12304. this._currentTextureChannel = -1;
  12305. };
  12306. /**
  12307. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12308. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12309. * @returns true if engine is in deterministic lock step mode
  12310. */
  12311. Engine.prototype.isDeterministicLockStep = function () {
  12312. return this._deterministicLockstep;
  12313. };
  12314. /**
  12315. * Gets the max steps when engine is running in deterministic lock step
  12316. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12317. * @returns the max steps
  12318. */
  12319. Engine.prototype.getLockstepMaxSteps = function () {
  12320. return this._lockstepMaxSteps;
  12321. };
  12322. /**
  12323. * Gets an object containing information about the current webGL context
  12324. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12325. */
  12326. Engine.prototype.getGlInfo = function () {
  12327. return {
  12328. vendor: this._glVendor,
  12329. renderer: this._glRenderer,
  12330. version: this._glVersion
  12331. };
  12332. };
  12333. /**
  12334. * Gets current aspect ratio
  12335. * @param camera defines the camera to use to get the aspect ratio
  12336. * @param useScreen defines if screen size must be used (or the current render target if any)
  12337. * @returns a number defining the aspect ratio
  12338. */
  12339. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12340. if (useScreen === void 0) { useScreen = false; }
  12341. var viewport = camera.viewport;
  12342. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12343. };
  12344. /**
  12345. * Gets the current render width
  12346. * @param useScreen defines if screen size must be used (or the current render target if any)
  12347. * @returns a number defining the current render width
  12348. */
  12349. Engine.prototype.getRenderWidth = function (useScreen) {
  12350. if (useScreen === void 0) { useScreen = false; }
  12351. if (!useScreen && this._currentRenderTarget) {
  12352. return this._currentRenderTarget.width;
  12353. }
  12354. return this._gl.drawingBufferWidth;
  12355. };
  12356. /**
  12357. * Gets the current render height
  12358. * @param useScreen defines if screen size must be used (or the current render target if any)
  12359. * @returns a number defining the current render height
  12360. */
  12361. Engine.prototype.getRenderHeight = function (useScreen) {
  12362. if (useScreen === void 0) { useScreen = false; }
  12363. if (!useScreen && this._currentRenderTarget) {
  12364. return this._currentRenderTarget.height;
  12365. }
  12366. return this._gl.drawingBufferHeight;
  12367. };
  12368. /**
  12369. * Gets the HTML canvas attached with the current webGL context
  12370. * @returns a HTML canvas
  12371. */
  12372. Engine.prototype.getRenderingCanvas = function () {
  12373. return this._renderingCanvas;
  12374. };
  12375. /**
  12376. * Gets the client rect of the HTML canvas attached with the current webGL context
  12377. * @returns a client rectanglee
  12378. */
  12379. Engine.prototype.getRenderingCanvasClientRect = function () {
  12380. if (!this._renderingCanvas) {
  12381. return null;
  12382. }
  12383. return this._renderingCanvas.getBoundingClientRect();
  12384. };
  12385. /**
  12386. * Defines the hardware scaling level.
  12387. * By default the hardware scaling level is computed from the window device ratio.
  12388. * 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.
  12389. * @param level defines the level to use
  12390. */
  12391. Engine.prototype.setHardwareScalingLevel = function (level) {
  12392. this._hardwareScalingLevel = level;
  12393. this.resize();
  12394. };
  12395. /**
  12396. * Gets the current hardware scaling level.
  12397. * By default the hardware scaling level is computed from the window device ratio.
  12398. * 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.
  12399. * @returns a number indicating the current hardware scaling level
  12400. */
  12401. Engine.prototype.getHardwareScalingLevel = function () {
  12402. return this._hardwareScalingLevel;
  12403. };
  12404. /**
  12405. * Gets the list of loaded textures
  12406. * @returns an array containing all loaded textures
  12407. */
  12408. Engine.prototype.getLoadedTexturesCache = function () {
  12409. return this._internalTexturesCache;
  12410. };
  12411. /**
  12412. * Gets the object containing all engine capabilities
  12413. * @returns the EngineCapabilities object
  12414. */
  12415. Engine.prototype.getCaps = function () {
  12416. return this._caps;
  12417. };
  12418. Object.defineProperty(Engine.prototype, "drawCalls", {
  12419. /** @hidden */
  12420. get: function () {
  12421. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12422. return 0;
  12423. },
  12424. enumerable: true,
  12425. configurable: true
  12426. });
  12427. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12428. /** @hidden */
  12429. get: function () {
  12430. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12431. return null;
  12432. },
  12433. enumerable: true,
  12434. configurable: true
  12435. });
  12436. /**
  12437. * Gets the current depth function
  12438. * @returns a number defining the depth function
  12439. */
  12440. Engine.prototype.getDepthFunction = function () {
  12441. return this._depthCullingState.depthFunc;
  12442. };
  12443. /**
  12444. * Sets the current depth function
  12445. * @param depthFunc defines the function to use
  12446. */
  12447. Engine.prototype.setDepthFunction = function (depthFunc) {
  12448. this._depthCullingState.depthFunc = depthFunc;
  12449. };
  12450. /**
  12451. * Sets the current depth function to GREATER
  12452. */
  12453. Engine.prototype.setDepthFunctionToGreater = function () {
  12454. this._depthCullingState.depthFunc = this._gl.GREATER;
  12455. };
  12456. /**
  12457. * Sets the current depth function to GEQUAL
  12458. */
  12459. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12460. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12461. };
  12462. /**
  12463. * Sets the current depth function to LESS
  12464. */
  12465. Engine.prototype.setDepthFunctionToLess = function () {
  12466. this._depthCullingState.depthFunc = this._gl.LESS;
  12467. };
  12468. /**
  12469. * Sets the current depth function to LEQUAL
  12470. */
  12471. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12472. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12473. };
  12474. /**
  12475. * Gets a boolean indicating if stencil buffer is enabled
  12476. * @returns the current stencil buffer state
  12477. */
  12478. Engine.prototype.getStencilBuffer = function () {
  12479. return this._stencilState.stencilTest;
  12480. };
  12481. /**
  12482. * Enable or disable the stencil buffer
  12483. * @param enable defines if the stencil buffer must be enabled or disabled
  12484. */
  12485. Engine.prototype.setStencilBuffer = function (enable) {
  12486. this._stencilState.stencilTest = enable;
  12487. };
  12488. /**
  12489. * Gets the current stencil mask
  12490. * @returns a number defining the new stencil mask to use
  12491. */
  12492. Engine.prototype.getStencilMask = function () {
  12493. return this._stencilState.stencilMask;
  12494. };
  12495. /**
  12496. * Sets the current stencil mask
  12497. * @param mask defines the new stencil mask to use
  12498. */
  12499. Engine.prototype.setStencilMask = function (mask) {
  12500. this._stencilState.stencilMask = mask;
  12501. };
  12502. /**
  12503. * Gets the current stencil function
  12504. * @returns a number defining the stencil function to use
  12505. */
  12506. Engine.prototype.getStencilFunction = function () {
  12507. return this._stencilState.stencilFunc;
  12508. };
  12509. /**
  12510. * Gets the current stencil reference value
  12511. * @returns a number defining the stencil reference value to use
  12512. */
  12513. Engine.prototype.getStencilFunctionReference = function () {
  12514. return this._stencilState.stencilFuncRef;
  12515. };
  12516. /**
  12517. * Gets the current stencil mask
  12518. * @returns a number defining the stencil mask to use
  12519. */
  12520. Engine.prototype.getStencilFunctionMask = function () {
  12521. return this._stencilState.stencilFuncMask;
  12522. };
  12523. /**
  12524. * Sets the current stencil function
  12525. * @param stencilFunc defines the new stencil function to use
  12526. */
  12527. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12528. this._stencilState.stencilFunc = stencilFunc;
  12529. };
  12530. /**
  12531. * Sets the current stencil reference
  12532. * @param reference defines the new stencil reference to use
  12533. */
  12534. Engine.prototype.setStencilFunctionReference = function (reference) {
  12535. this._stencilState.stencilFuncRef = reference;
  12536. };
  12537. /**
  12538. * Sets the current stencil mask
  12539. * @param mask defines the new stencil mask to use
  12540. */
  12541. Engine.prototype.setStencilFunctionMask = function (mask) {
  12542. this._stencilState.stencilFuncMask = mask;
  12543. };
  12544. /**
  12545. * Gets the current stencil operation when stencil fails
  12546. * @returns a number defining stencil operation to use when stencil fails
  12547. */
  12548. Engine.prototype.getStencilOperationFail = function () {
  12549. return this._stencilState.stencilOpStencilFail;
  12550. };
  12551. /**
  12552. * Gets the current stencil operation when depth fails
  12553. * @returns a number defining stencil operation to use when depth fails
  12554. */
  12555. Engine.prototype.getStencilOperationDepthFail = function () {
  12556. return this._stencilState.stencilOpDepthFail;
  12557. };
  12558. /**
  12559. * Gets the current stencil operation when stencil passes
  12560. * @returns a number defining stencil operation to use when stencil passes
  12561. */
  12562. Engine.prototype.getStencilOperationPass = function () {
  12563. return this._stencilState.stencilOpStencilDepthPass;
  12564. };
  12565. /**
  12566. * Sets the stencil operation to use when stencil fails
  12567. * @param operation defines the stencil operation to use when stencil fails
  12568. */
  12569. Engine.prototype.setStencilOperationFail = function (operation) {
  12570. this._stencilState.stencilOpStencilFail = operation;
  12571. };
  12572. /**
  12573. * Sets the stencil operation to use when depth fails
  12574. * @param operation defines the stencil operation to use when depth fails
  12575. */
  12576. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12577. this._stencilState.stencilOpDepthFail = operation;
  12578. };
  12579. /**
  12580. * Sets the stencil operation to use when stencil passes
  12581. * @param operation defines the stencil operation to use when stencil passes
  12582. */
  12583. Engine.prototype.setStencilOperationPass = function (operation) {
  12584. this._stencilState.stencilOpStencilDepthPass = operation;
  12585. };
  12586. /**
  12587. * Sets a boolean indicating if the dithering state is enabled or disabled
  12588. * @param value defines the dithering state
  12589. */
  12590. Engine.prototype.setDitheringState = function (value) {
  12591. if (value) {
  12592. this._gl.enable(this._gl.DITHER);
  12593. }
  12594. else {
  12595. this._gl.disable(this._gl.DITHER);
  12596. }
  12597. };
  12598. /**
  12599. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12600. * @param value defines the rasterizer state
  12601. */
  12602. Engine.prototype.setRasterizerState = function (value) {
  12603. if (value) {
  12604. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12605. }
  12606. else {
  12607. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12608. }
  12609. };
  12610. /**
  12611. * stop executing a render loop function and remove it from the execution array
  12612. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12613. */
  12614. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12615. if (!renderFunction) {
  12616. this._activeRenderLoops = [];
  12617. return;
  12618. }
  12619. var index = this._activeRenderLoops.indexOf(renderFunction);
  12620. if (index >= 0) {
  12621. this._activeRenderLoops.splice(index, 1);
  12622. }
  12623. };
  12624. /** @hidden */
  12625. Engine.prototype._renderLoop = function () {
  12626. if (!this._contextWasLost) {
  12627. var shouldRender = true;
  12628. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12629. shouldRender = false;
  12630. }
  12631. if (shouldRender) {
  12632. // Start new frame
  12633. this.beginFrame();
  12634. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12635. var renderFunction = this._activeRenderLoops[index];
  12636. renderFunction();
  12637. }
  12638. // Present
  12639. this.endFrame();
  12640. }
  12641. }
  12642. if (this._activeRenderLoops.length > 0) {
  12643. // Register new frame
  12644. var requester = null;
  12645. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12646. requester = this._vrDisplay;
  12647. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12648. }
  12649. else {
  12650. this._renderingQueueLaunched = false;
  12651. }
  12652. };
  12653. /**
  12654. * Register and execute a render loop. The engine can have more than one render function
  12655. * @param renderFunction defines the function to continuously execute
  12656. */
  12657. Engine.prototype.runRenderLoop = function (renderFunction) {
  12658. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12659. return;
  12660. }
  12661. this._activeRenderLoops.push(renderFunction);
  12662. if (!this._renderingQueueLaunched) {
  12663. this._renderingQueueLaunched = true;
  12664. this._bindedRenderFunction = this._renderLoop.bind(this);
  12665. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12666. }
  12667. };
  12668. /**
  12669. * Toggle full screen mode
  12670. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12671. * @param options defines an option object to be sent to the requestFullscreen function
  12672. */
  12673. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12674. if (this.isFullscreen) {
  12675. BABYLON.Tools.ExitFullscreen();
  12676. }
  12677. else {
  12678. this._pointerLockRequested = requestPointerLock;
  12679. if (this._renderingCanvas) {
  12680. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12681. }
  12682. }
  12683. };
  12684. /**
  12685. * Clear the current render buffer or the current render target (if any is set up)
  12686. * @param color defines the color to use
  12687. * @param backBuffer defines if the back buffer must be cleared
  12688. * @param depth defines if the depth buffer must be cleared
  12689. * @param stencil defines if the stencil buffer must be cleared
  12690. */
  12691. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12692. if (stencil === void 0) { stencil = false; }
  12693. this.applyStates();
  12694. var mode = 0;
  12695. if (backBuffer && color) {
  12696. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12697. mode |= this._gl.COLOR_BUFFER_BIT;
  12698. }
  12699. if (depth) {
  12700. this._gl.clearDepth(1.0);
  12701. mode |= this._gl.DEPTH_BUFFER_BIT;
  12702. }
  12703. if (stencil) {
  12704. this._gl.clearStencil(0);
  12705. mode |= this._gl.STENCIL_BUFFER_BIT;
  12706. }
  12707. this._gl.clear(mode);
  12708. };
  12709. /**
  12710. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12711. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12712. * @param y defines the y-coordinate of the corner of the clear rectangle
  12713. * @param width defines the width of the clear rectangle
  12714. * @param height defines the height of the clear rectangle
  12715. * @param clearColor defines the clear color
  12716. */
  12717. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12718. var gl = this._gl;
  12719. // Save state
  12720. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12721. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12722. // Change state
  12723. gl.enable(gl.SCISSOR_TEST);
  12724. gl.scissor(x, y, width, height);
  12725. // Clear
  12726. this.clear(clearColor, true, true, true);
  12727. // Restore state
  12728. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12729. if (curScissor === true) {
  12730. gl.enable(gl.SCISSOR_TEST);
  12731. }
  12732. else {
  12733. gl.disable(gl.SCISSOR_TEST);
  12734. }
  12735. };
  12736. /**
  12737. * Set the WebGL's viewport
  12738. * @param viewport defines the viewport element to be used
  12739. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12740. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12741. */
  12742. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12743. var width = requiredWidth || this.getRenderWidth();
  12744. var height = requiredHeight || this.getRenderHeight();
  12745. var x = viewport.x || 0;
  12746. var y = viewport.y || 0;
  12747. this._cachedViewport = viewport;
  12748. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12749. };
  12750. /**
  12751. * Directly set the WebGL Viewport
  12752. * @param x defines the x coordinate of the viewport (in screen space)
  12753. * @param y defines the y coordinate of the viewport (in screen space)
  12754. * @param width defines the width of the viewport (in screen space)
  12755. * @param height defines the height of the viewport (in screen space)
  12756. * @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
  12757. */
  12758. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12759. var currentViewport = this._cachedViewport;
  12760. this._cachedViewport = null;
  12761. this._gl.viewport(x, y, width, height);
  12762. return currentViewport;
  12763. };
  12764. /**
  12765. * Begin a new frame
  12766. */
  12767. Engine.prototype.beginFrame = function () {
  12768. this.onBeginFrameObservable.notifyObservers(this);
  12769. this._measureFps();
  12770. };
  12771. /**
  12772. * Enf the current frame
  12773. */
  12774. Engine.prototype.endFrame = function () {
  12775. // Force a flush in case we are using a bad OS.
  12776. if (this._badOS) {
  12777. this.flushFramebuffer();
  12778. }
  12779. // Submit frame to the vr device, if enabled
  12780. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12781. // TODO: We should only submit the frame if we read frameData successfully.
  12782. this._vrDisplay.submitFrame();
  12783. }
  12784. this.onEndFrameObservable.notifyObservers(this);
  12785. };
  12786. /**
  12787. * Resize the view according to the canvas' size
  12788. */
  12789. Engine.prototype.resize = function () {
  12790. // We're not resizing the size of the canvas while in VR mode & presenting
  12791. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12792. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12793. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12794. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12795. }
  12796. };
  12797. /**
  12798. * Force a specific size of the canvas
  12799. * @param width defines the new canvas' width
  12800. * @param height defines the new canvas' height
  12801. */
  12802. Engine.prototype.setSize = function (width, height) {
  12803. if (!this._renderingCanvas) {
  12804. return;
  12805. }
  12806. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12807. return;
  12808. }
  12809. this._renderingCanvas.width = width;
  12810. this._renderingCanvas.height = height;
  12811. for (var index = 0; index < this.scenes.length; index++) {
  12812. var scene = this.scenes[index];
  12813. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12814. var cam = scene.cameras[camIndex];
  12815. cam._currentRenderId = 0;
  12816. }
  12817. }
  12818. if (this.onResizeObservable.hasObservers) {
  12819. this.onResizeObservable.notifyObservers(this);
  12820. }
  12821. };
  12822. // WebVR functions
  12823. /**
  12824. * Gets a boolean indicating if a webVR device was detected
  12825. * @returns true if a webVR device was detected
  12826. */
  12827. Engine.prototype.isVRDevicePresent = function () {
  12828. return !!this._vrDisplay;
  12829. };
  12830. /**
  12831. * Gets the current webVR device
  12832. * @returns the current webVR device (or null)
  12833. */
  12834. Engine.prototype.getVRDevice = function () {
  12835. return this._vrDisplay;
  12836. };
  12837. /**
  12838. * Initializes a webVR display and starts listening to display change events
  12839. * The onVRDisplayChangedObservable will be notified upon these changes
  12840. * @returns The onVRDisplayChangedObservable
  12841. */
  12842. Engine.prototype.initWebVR = function () {
  12843. this.initWebVRAsync();
  12844. return this.onVRDisplayChangedObservable;
  12845. };
  12846. /**
  12847. * Initializes a webVR display and starts listening to display change events
  12848. * The onVRDisplayChangedObservable will be notified upon these changes
  12849. * @returns A promise containing a VRDisplay and if vr is supported
  12850. */
  12851. Engine.prototype.initWebVRAsync = function () {
  12852. var _this = this;
  12853. var notifyObservers = function () {
  12854. var eventArgs = {
  12855. vrDisplay: _this._vrDisplay,
  12856. vrSupported: _this._vrSupported
  12857. };
  12858. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12859. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12860. };
  12861. if (!this._onVrDisplayConnect) {
  12862. this._onVrDisplayConnect = function (event) {
  12863. _this._vrDisplay = event.display;
  12864. notifyObservers();
  12865. };
  12866. this._onVrDisplayDisconnect = function () {
  12867. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12868. _this._vrDisplay = undefined;
  12869. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12870. notifyObservers();
  12871. };
  12872. this._onVrDisplayPresentChange = function () {
  12873. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12874. };
  12875. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12876. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12877. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12878. }
  12879. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12880. this._webVRInitPromise.then(notifyObservers);
  12881. return this._webVRInitPromise;
  12882. };
  12883. /**
  12884. * Call this function to switch to webVR mode
  12885. * Will do nothing if webVR is not supported or if there is no webVR device
  12886. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12887. */
  12888. Engine.prototype.enableVR = function () {
  12889. var _this = this;
  12890. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12891. var onResolved = function () {
  12892. _this.onVRRequestPresentComplete.notifyObservers(true);
  12893. _this._onVRFullScreenTriggered();
  12894. };
  12895. var onRejected = function () {
  12896. _this.onVRRequestPresentComplete.notifyObservers(false);
  12897. };
  12898. this.onVRRequestPresentStart.notifyObservers(this);
  12899. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12900. }
  12901. };
  12902. /**
  12903. * Call this function to leave webVR mode
  12904. * Will do nothing if webVR is not supported or if there is no webVR device
  12905. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12906. */
  12907. Engine.prototype.disableVR = function () {
  12908. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12909. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12910. }
  12911. };
  12912. Engine.prototype._getVRDisplaysAsync = function () {
  12913. var _this = this;
  12914. return new Promise(function (res, rej) {
  12915. if (navigator.getVRDisplays) {
  12916. navigator.getVRDisplays().then(function (devices) {
  12917. _this._vrSupported = true;
  12918. // note that devices may actually be an empty array. This is fine;
  12919. // we expect this._vrDisplay to be undefined in this case.
  12920. _this._vrDisplay = devices[0];
  12921. res({
  12922. vrDisplay: _this._vrDisplay,
  12923. vrSupported: _this._vrSupported
  12924. });
  12925. });
  12926. }
  12927. else {
  12928. _this._vrDisplay = undefined;
  12929. _this._vrSupported = false;
  12930. res({
  12931. vrDisplay: _this._vrDisplay,
  12932. vrSupported: _this._vrSupported
  12933. });
  12934. }
  12935. });
  12936. };
  12937. /**
  12938. * Binds the frame buffer to the specified texture.
  12939. * @param texture The texture to render to or null for the default canvas
  12940. * @param faceIndex The face of the texture to render to in case of cube texture
  12941. * @param requiredWidth The width of the target to render to
  12942. * @param requiredHeight The height of the target to render to
  12943. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12944. * @param depthStencilTexture The depth stencil texture to use to render
  12945. */
  12946. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12947. if (this._currentRenderTarget) {
  12948. this.unBindFramebuffer(this._currentRenderTarget);
  12949. }
  12950. this._currentRenderTarget = texture;
  12951. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12952. var gl = this._gl;
  12953. if (texture.isCube) {
  12954. if (faceIndex === undefined) {
  12955. faceIndex = 0;
  12956. }
  12957. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12958. if (depthStencilTexture) {
  12959. if (depthStencilTexture._generateStencilBuffer) {
  12960. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12961. }
  12962. else {
  12963. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12964. }
  12965. }
  12966. }
  12967. if (this._cachedViewport && !forceFullscreenViewport) {
  12968. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12969. }
  12970. else {
  12971. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  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. /**
  13805. * Create an effect to use with particle systems
  13806. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13807. * @param uniformsNames defines a list of attribute names
  13808. * @param samplers defines an array of string used to represent textures
  13809. * @param defines defines the string containing the defines to use to compile the shaders
  13810. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13811. * @param onCompiled defines a function to call when the effect creation is successful
  13812. * @param onError defines a function to call when the effect creation has failed
  13813. * @returns the new Effect
  13814. */
  13815. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13816. if (uniformsNames === void 0) { uniformsNames = []; }
  13817. if (samplers === void 0) { samplers = []; }
  13818. if (defines === void 0) { defines = ""; }
  13819. return this.createEffect({
  13820. vertex: "particles",
  13821. fragmentElement: fragmentName
  13822. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13823. };
  13824. /**
  13825. * Directly creates a webGL program
  13826. * @param vertexCode defines the vertex shader code to use
  13827. * @param fragmentCode defines the fragment shader code to use
  13828. * @param context defines the webGL context to use (if not set, the current one will be used)
  13829. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13830. * @returns the new webGL program
  13831. */
  13832. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13833. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13834. context = context || this._gl;
  13835. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13836. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13837. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13838. };
  13839. /**
  13840. * Creates a webGL program
  13841. * @param vertexCode defines the vertex shader code to use
  13842. * @param fragmentCode defines the fragment shader code to use
  13843. * @param defines defines the string containing the defines to use to compile the shaders
  13844. * @param context defines the webGL context to use (if not set, the current one will be used)
  13845. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13846. * @returns the new webGL program
  13847. */
  13848. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13849. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13850. context = context || this._gl;
  13851. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13852. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13853. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13854. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13855. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13856. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13857. return program;
  13858. };
  13859. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13860. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13861. var shaderProgram = context.createProgram();
  13862. if (!shaderProgram) {
  13863. throw new Error("Unable to create program");
  13864. }
  13865. context.attachShader(shaderProgram, vertexShader);
  13866. context.attachShader(shaderProgram, fragmentShader);
  13867. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13868. var transformFeedback = this.createTransformFeedback();
  13869. this.bindTransformFeedback(transformFeedback);
  13870. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13871. shaderProgram.transformFeedback = transformFeedback;
  13872. }
  13873. context.linkProgram(shaderProgram);
  13874. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13875. this.bindTransformFeedback(null);
  13876. }
  13877. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13878. if (!linked) {
  13879. context.validateProgram(shaderProgram);
  13880. var error = context.getProgramInfoLog(shaderProgram);
  13881. if (error) {
  13882. throw new Error(error);
  13883. }
  13884. }
  13885. context.deleteShader(vertexShader);
  13886. context.deleteShader(fragmentShader);
  13887. return shaderProgram;
  13888. };
  13889. /**
  13890. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13891. * @param shaderProgram defines the webGL program to use
  13892. * @param uniformsNames defines the list of uniform names
  13893. * @returns an array of webGL uniform locations
  13894. */
  13895. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13896. var results = new Array();
  13897. for (var index = 0; index < uniformsNames.length; index++) {
  13898. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13899. }
  13900. return results;
  13901. };
  13902. /**
  13903. * Gets the lsit of active attributes for a given webGL program
  13904. * @param shaderProgram defines the webGL program to use
  13905. * @param attributesNames defines the list of attribute names to get
  13906. * @returns an array of indices indicating the offset of each attribute
  13907. */
  13908. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13909. var results = [];
  13910. for (var index = 0; index < attributesNames.length; index++) {
  13911. try {
  13912. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13913. }
  13914. catch (e) {
  13915. results.push(-1);
  13916. }
  13917. }
  13918. return results;
  13919. };
  13920. /**
  13921. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13922. * @param effect defines the effect to activate
  13923. */
  13924. Engine.prototype.enableEffect = function (effect) {
  13925. if (!effect) {
  13926. return;
  13927. }
  13928. // Use program
  13929. this.bindSamplers(effect);
  13930. this._currentEffect = effect;
  13931. if (effect.onBind) {
  13932. effect.onBind(effect);
  13933. }
  13934. effect.onBindObservable.notifyObservers(effect);
  13935. };
  13936. /**
  13937. * Set the value of an uniform to an array of int32
  13938. * @param uniform defines the webGL uniform location where to store the value
  13939. * @param array defines the array of int32 to store
  13940. */
  13941. Engine.prototype.setIntArray = function (uniform, array) {
  13942. if (!uniform)
  13943. return;
  13944. this._gl.uniform1iv(uniform, array);
  13945. };
  13946. /**
  13947. * Set the value of an uniform to an array of int32 (stored as vec2)
  13948. * @param uniform defines the webGL uniform location where to store the value
  13949. * @param array defines the array of int32 to store
  13950. */
  13951. Engine.prototype.setIntArray2 = function (uniform, array) {
  13952. if (!uniform || array.length % 2 !== 0)
  13953. return;
  13954. this._gl.uniform2iv(uniform, array);
  13955. };
  13956. /**
  13957. * Set the value of an uniform to an array of int32 (stored as vec3)
  13958. * @param uniform defines the webGL uniform location where to store the value
  13959. * @param array defines the array of int32 to store
  13960. */
  13961. Engine.prototype.setIntArray3 = function (uniform, array) {
  13962. if (!uniform || array.length % 3 !== 0)
  13963. return;
  13964. this._gl.uniform3iv(uniform, array);
  13965. };
  13966. /**
  13967. * Set the value of an uniform to an array of int32 (stored as vec4)
  13968. * @param uniform defines the webGL uniform location where to store the value
  13969. * @param array defines the array of int32 to store
  13970. */
  13971. Engine.prototype.setIntArray4 = function (uniform, array) {
  13972. if (!uniform || array.length % 4 !== 0)
  13973. return;
  13974. this._gl.uniform4iv(uniform, array);
  13975. };
  13976. /**
  13977. * Set the value of an uniform to an array of float32
  13978. * @param uniform defines the webGL uniform location where to store the value
  13979. * @param array defines the array of float32 to store
  13980. */
  13981. Engine.prototype.setFloatArray = function (uniform, array) {
  13982. if (!uniform)
  13983. return;
  13984. this._gl.uniform1fv(uniform, array);
  13985. };
  13986. /**
  13987. * Set the value of an uniform to an array of float32 (stored as vec2)
  13988. * @param uniform defines the webGL uniform location where to store the value
  13989. * @param array defines the array of float32 to store
  13990. */
  13991. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13992. if (!uniform || array.length % 2 !== 0)
  13993. return;
  13994. this._gl.uniform2fv(uniform, array);
  13995. };
  13996. /**
  13997. * Set the value of an uniform to an array of float32 (stored as vec3)
  13998. * @param uniform defines the webGL uniform location where to store the value
  13999. * @param array defines the array of float32 to store
  14000. */
  14001. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14002. if (!uniform || array.length % 3 !== 0)
  14003. return;
  14004. this._gl.uniform3fv(uniform, array);
  14005. };
  14006. /**
  14007. * Set the value of an uniform to an array of float32 (stored as vec4)
  14008. * @param uniform defines the webGL uniform location where to store the value
  14009. * @param array defines the array of float32 to store
  14010. */
  14011. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14012. if (!uniform || array.length % 4 !== 0)
  14013. return;
  14014. this._gl.uniform4fv(uniform, array);
  14015. };
  14016. /**
  14017. * Set the value of an uniform to an array of number
  14018. * @param uniform defines the webGL uniform location where to store the value
  14019. * @param array defines the array of number to store
  14020. */
  14021. Engine.prototype.setArray = function (uniform, array) {
  14022. if (!uniform)
  14023. return;
  14024. this._gl.uniform1fv(uniform, array);
  14025. };
  14026. /**
  14027. * Set the value of an uniform to an array of number (stored as vec2)
  14028. * @param uniform defines the webGL uniform location where to store the value
  14029. * @param array defines the array of number to store
  14030. */
  14031. Engine.prototype.setArray2 = function (uniform, array) {
  14032. if (!uniform || array.length % 2 !== 0)
  14033. return;
  14034. this._gl.uniform2fv(uniform, array);
  14035. };
  14036. /**
  14037. * Set the value of an uniform to an array of number (stored as vec3)
  14038. * @param uniform defines the webGL uniform location where to store the value
  14039. * @param array defines the array of number to store
  14040. */
  14041. Engine.prototype.setArray3 = function (uniform, array) {
  14042. if (!uniform || array.length % 3 !== 0)
  14043. return;
  14044. this._gl.uniform3fv(uniform, array);
  14045. };
  14046. /**
  14047. * Set the value of an uniform to an array of number (stored as vec4)
  14048. * @param uniform defines the webGL uniform location where to store the value
  14049. * @param array defines the array of number to store
  14050. */
  14051. Engine.prototype.setArray4 = function (uniform, array) {
  14052. if (!uniform || array.length % 4 !== 0)
  14053. return;
  14054. this._gl.uniform4fv(uniform, array);
  14055. };
  14056. /**
  14057. * Set the value of an uniform to an array of float32 (stored as matrices)
  14058. * @param uniform defines the webGL uniform location where to store the value
  14059. * @param matrices defines the array of float32 to store
  14060. */
  14061. Engine.prototype.setMatrices = function (uniform, matrices) {
  14062. if (!uniform)
  14063. return;
  14064. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14065. };
  14066. /**
  14067. * Set the value of an uniform to a matrix
  14068. * @param uniform defines the webGL uniform location where to store the value
  14069. * @param matrix defines the matrix to store
  14070. */
  14071. Engine.prototype.setMatrix = function (uniform, matrix) {
  14072. if (!uniform)
  14073. return;
  14074. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14075. };
  14076. /**
  14077. * Set the value of an uniform to a matrix (3x3)
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14080. */
  14081. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14082. if (!uniform)
  14083. return;
  14084. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to a matrix (2x2)
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14090. */
  14091. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14092. if (!uniform)
  14093. return;
  14094. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14095. };
  14096. /**
  14097. * Set the value of an uniform to a number (int)
  14098. * @param uniform defines the webGL uniform location where to store the value
  14099. * @param value defines the int number to store
  14100. */
  14101. Engine.prototype.setInt = function (uniform, value) {
  14102. if (!uniform)
  14103. return;
  14104. this._gl.uniform1i(uniform, value);
  14105. };
  14106. /**
  14107. * Set the value of an uniform to a number (float)
  14108. * @param uniform defines the webGL uniform location where to store the value
  14109. * @param value defines the float number to store
  14110. */
  14111. Engine.prototype.setFloat = function (uniform, value) {
  14112. if (!uniform)
  14113. return;
  14114. this._gl.uniform1f(uniform, value);
  14115. };
  14116. /**
  14117. * Set the value of an uniform to a vec2
  14118. * @param uniform defines the webGL uniform location where to store the value
  14119. * @param x defines the 1st component of the value
  14120. * @param y defines the 2nd component of the value
  14121. */
  14122. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14123. if (!uniform)
  14124. return;
  14125. this._gl.uniform2f(uniform, x, y);
  14126. };
  14127. /**
  14128. * Set the value of an uniform to a vec3
  14129. * @param uniform defines the webGL uniform location where to store the value
  14130. * @param x defines the 1st component of the value
  14131. * @param y defines the 2nd component of the value
  14132. * @param z defines the 3rd component of the value
  14133. */
  14134. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14135. if (!uniform)
  14136. return;
  14137. this._gl.uniform3f(uniform, x, y, z);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to a boolean
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param bool defines the boolean to store
  14143. */
  14144. Engine.prototype.setBool = function (uniform, bool) {
  14145. if (!uniform)
  14146. return;
  14147. this._gl.uniform1i(uniform, bool);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to a vec4
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param x defines the 1st component of the value
  14153. * @param y defines the 2nd component of the value
  14154. * @param z defines the 3rd component of the value
  14155. * @param w defines the 4th component of the value
  14156. */
  14157. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14158. if (!uniform)
  14159. return;
  14160. this._gl.uniform4f(uniform, x, y, z, w);
  14161. };
  14162. /**
  14163. * Set the value of an uniform to a Color3
  14164. * @param uniform defines the webGL uniform location where to store the value
  14165. * @param color3 defines the color to store
  14166. */
  14167. Engine.prototype.setColor3 = function (uniform, color3) {
  14168. if (!uniform)
  14169. return;
  14170. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14171. };
  14172. /**
  14173. * Set the value of an uniform to a Color3 and an alpha value
  14174. * @param uniform defines the webGL uniform location where to store the value
  14175. * @param color3 defines the color to store
  14176. * @param alpha defines the alpha component to store
  14177. */
  14178. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14179. if (!uniform)
  14180. return;
  14181. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14182. };
  14183. /**
  14184. * Sets a Color4 on a uniform variable
  14185. * @param uniform defines the uniform location
  14186. * @param color4 defines the value to be set
  14187. */
  14188. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14189. if (!uniform)
  14190. return;
  14191. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14192. };
  14193. // States
  14194. /**
  14195. * Set various states to the webGL context
  14196. * @param culling defines backface culling state
  14197. * @param zOffset defines the value to apply to zOffset (0 by default)
  14198. * @param force defines if states must be applied even if cache is up to date
  14199. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14200. */
  14201. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14202. if (zOffset === void 0) { zOffset = 0; }
  14203. if (reverseSide === void 0) { reverseSide = false; }
  14204. // Culling
  14205. if (this._depthCullingState.cull !== culling || force) {
  14206. this._depthCullingState.cull = culling;
  14207. }
  14208. // Cull face
  14209. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14210. if (this._depthCullingState.cullFace !== cullFace || force) {
  14211. this._depthCullingState.cullFace = cullFace;
  14212. }
  14213. // Z offset
  14214. this.setZOffset(zOffset);
  14215. // Front face
  14216. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14217. if (this._depthCullingState.frontFace !== frontFace || force) {
  14218. this._depthCullingState.frontFace = frontFace;
  14219. }
  14220. };
  14221. /**
  14222. * Set the z offset to apply to current rendering
  14223. * @param value defines the offset to apply
  14224. */
  14225. Engine.prototype.setZOffset = function (value) {
  14226. this._depthCullingState.zOffset = value;
  14227. };
  14228. /**
  14229. * Gets the current value of the zOffset
  14230. * @returns the current zOffset state
  14231. */
  14232. Engine.prototype.getZOffset = function () {
  14233. return this._depthCullingState.zOffset;
  14234. };
  14235. /**
  14236. * Enable or disable depth buffering
  14237. * @param enable defines the state to set
  14238. */
  14239. Engine.prototype.setDepthBuffer = function (enable) {
  14240. this._depthCullingState.depthTest = enable;
  14241. };
  14242. /**
  14243. * Gets a boolean indicating if depth writing is enabled
  14244. * @returns the current depth writing state
  14245. */
  14246. Engine.prototype.getDepthWrite = function () {
  14247. return this._depthCullingState.depthMask;
  14248. };
  14249. /**
  14250. * Enable or disable depth writing
  14251. * @param enable defines the state to set
  14252. */
  14253. Engine.prototype.setDepthWrite = function (enable) {
  14254. this._depthCullingState.depthMask = enable;
  14255. };
  14256. /**
  14257. * Enable or disable color writing
  14258. * @param enable defines the state to set
  14259. */
  14260. Engine.prototype.setColorWrite = function (enable) {
  14261. this._gl.colorMask(enable, enable, enable, enable);
  14262. this._colorWrite = enable;
  14263. };
  14264. /**
  14265. * Gets a boolean indicating if color writing is enabled
  14266. * @returns the current color writing state
  14267. */
  14268. Engine.prototype.getColorWrite = function () {
  14269. return this._colorWrite;
  14270. };
  14271. /**
  14272. * Sets alpha constants used by some alpha blending modes
  14273. * @param r defines the red component
  14274. * @param g defines the green component
  14275. * @param b defines the blue component
  14276. * @param a defines the alpha component
  14277. */
  14278. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14279. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14280. };
  14281. /**
  14282. * Sets the current alpha mode
  14283. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14284. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14285. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14286. */
  14287. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14288. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14289. if (this._alphaMode === mode) {
  14290. return;
  14291. }
  14292. switch (mode) {
  14293. case Engine.ALPHA_DISABLE:
  14294. this._alphaState.alphaBlend = false;
  14295. break;
  14296. case Engine.ALPHA_PREMULTIPLIED:
  14297. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14298. this._alphaState.alphaBlend = true;
  14299. break;
  14300. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14301. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14302. this._alphaState.alphaBlend = true;
  14303. break;
  14304. case Engine.ALPHA_COMBINE:
  14305. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14306. this._alphaState.alphaBlend = true;
  14307. break;
  14308. case Engine.ALPHA_ONEONE:
  14309. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14310. this._alphaState.alphaBlend = true;
  14311. break;
  14312. case Engine.ALPHA_ADD:
  14313. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14314. this._alphaState.alphaBlend = true;
  14315. break;
  14316. case Engine.ALPHA_SUBTRACT:
  14317. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14318. this._alphaState.alphaBlend = true;
  14319. break;
  14320. case Engine.ALPHA_MULTIPLY:
  14321. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14322. this._alphaState.alphaBlend = true;
  14323. break;
  14324. case Engine.ALPHA_MAXIMIZED:
  14325. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14326. this._alphaState.alphaBlend = true;
  14327. break;
  14328. case Engine.ALPHA_INTERPOLATE:
  14329. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14330. this._alphaState.alphaBlend = true;
  14331. break;
  14332. case Engine.ALPHA_SCREENMODE:
  14333. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14334. this._alphaState.alphaBlend = true;
  14335. break;
  14336. }
  14337. if (!noDepthWriteChange) {
  14338. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14339. }
  14340. this._alphaMode = mode;
  14341. };
  14342. /**
  14343. * Gets the current alpha mode
  14344. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14345. * @returns the current alpha mode
  14346. */
  14347. Engine.prototype.getAlphaMode = function () {
  14348. return this._alphaMode;
  14349. };
  14350. // Textures
  14351. /**
  14352. * Force the entire cache to be cleared
  14353. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14354. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14355. */
  14356. Engine.prototype.wipeCaches = function (bruteForce) {
  14357. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14358. return;
  14359. }
  14360. this._currentEffect = null;
  14361. if (bruteForce) {
  14362. this.resetTextureCache();
  14363. this._currentProgram = null;
  14364. this._stencilState.reset();
  14365. this._depthCullingState.reset();
  14366. this.setDepthFunctionToLessOrEqual();
  14367. this._alphaState.reset();
  14368. }
  14369. this._resetVertexBufferBinding();
  14370. this._cachedIndexBuffer = null;
  14371. this._cachedEffectForVertexBuffers = null;
  14372. this._unbindVertexArrayObject();
  14373. this.bindIndexBuffer(null);
  14374. };
  14375. /**
  14376. * Set the compressed texture format to use, based on the formats you have, and the formats
  14377. * supported by the hardware / browser.
  14378. *
  14379. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14380. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14381. * to API arguments needed to compressed textures. This puts the burden on the container
  14382. * generator to house the arcane code for determining these for current & future formats.
  14383. *
  14384. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14385. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14386. *
  14387. * Note: The result of this call is not taken into account when a texture is base64.
  14388. *
  14389. * @param formatsAvailable defines the list of those format families you have created
  14390. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14391. *
  14392. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14393. * @returns The extension selected.
  14394. */
  14395. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14396. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14397. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14398. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14399. return this._textureFormatInUse = this._texturesSupported[i];
  14400. }
  14401. }
  14402. }
  14403. // actively set format to nothing, to allow this to be called more than once
  14404. // and possibly fail the 2nd time
  14405. this._textureFormatInUse = null;
  14406. return null;
  14407. };
  14408. /** @hidden */
  14409. Engine.prototype._createTexture = function () {
  14410. var texture = this._gl.createTexture();
  14411. if (!texture) {
  14412. throw new Error("Unable to create texture");
  14413. }
  14414. return texture;
  14415. };
  14416. /**
  14417. * Usually called from BABYLON.Texture.ts.
  14418. * Passed information to create a WebGLTexture
  14419. * @param urlArg defines a value which contains one of the following:
  14420. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14421. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14422. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14423. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14424. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14425. * @param scene needed for loading to the correct scene
  14426. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14427. * @param onLoad optional callback to be called upon successful completion
  14428. * @param onError optional callback to be called upon failure
  14429. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14430. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14431. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14432. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14433. */
  14434. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14435. var _this = this;
  14436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14437. if (onLoad === void 0) { onLoad = null; }
  14438. if (onError === void 0) { onError = null; }
  14439. if (buffer === void 0) { buffer = null; }
  14440. if (fallback === void 0) { fallback = null; }
  14441. if (format === void 0) { format = null; }
  14442. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14443. var fromData = url.substr(0, 5) === "data:";
  14444. var fromBlob = url.substr(0, 5) === "blob:";
  14445. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14446. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14447. // establish the file extension, if possible
  14448. var lastDot = url.lastIndexOf('.');
  14449. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14450. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14451. var isTGA = (extension.indexOf(".tga") === 0);
  14452. // determine if a ktx file should be substituted
  14453. var isKTX = false;
  14454. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14455. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14456. isKTX = true;
  14457. }
  14458. if (scene) {
  14459. scene._addPendingData(texture);
  14460. }
  14461. texture.url = url;
  14462. texture.generateMipMaps = !noMipmap;
  14463. texture.samplingMode = samplingMode;
  14464. texture.invertY = invertY;
  14465. if (!this._doNotHandleContextLost) {
  14466. // Keep a link to the buffer only if we plan to handle context lost
  14467. texture._buffer = buffer;
  14468. }
  14469. var onLoadObserver = null;
  14470. if (onLoad && !fallback) {
  14471. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14472. }
  14473. if (!fallback)
  14474. this._internalTexturesCache.push(texture);
  14475. var onerror = function (message, exception) {
  14476. if (scene) {
  14477. scene._removePendingData(texture);
  14478. }
  14479. if (onLoadObserver) {
  14480. texture.onLoadedObservable.remove(onLoadObserver);
  14481. }
  14482. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14483. if (isKTX) {
  14484. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14485. }
  14486. else if (BABYLON.Tools.UseFallbackTexture) {
  14487. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14488. }
  14489. if (onError) {
  14490. onError(message || "Unknown error", exception);
  14491. }
  14492. };
  14493. var callback = null;
  14494. // processing for non-image formats
  14495. if (isKTX || isTGA || isDDS) {
  14496. if (isKTX) {
  14497. callback = function (data) {
  14498. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14499. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14500. ktx.uploadLevels(_this._gl, !noMipmap);
  14501. return false;
  14502. }, samplingMode);
  14503. };
  14504. }
  14505. else if (isTGA) {
  14506. callback = function (arrayBuffer) {
  14507. var data = new Uint8Array(arrayBuffer);
  14508. var header = BABYLON.TGATools.GetTGAHeader(data);
  14509. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14510. BABYLON.TGATools.UploadContent(_this._gl, data);
  14511. return false;
  14512. }, samplingMode);
  14513. };
  14514. }
  14515. else if (isDDS) {
  14516. callback = function (data) {
  14517. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14518. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14519. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14520. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14521. return false;
  14522. }, samplingMode);
  14523. };
  14524. }
  14525. if (!buffer) {
  14526. this._loadFile(url, function (data) {
  14527. if (callback) {
  14528. callback(data);
  14529. }
  14530. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14531. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14532. });
  14533. }
  14534. else {
  14535. if (callback) {
  14536. callback(buffer);
  14537. }
  14538. }
  14539. // image format processing
  14540. }
  14541. else {
  14542. var onload = function (img) {
  14543. if (fromBlob && !_this._doNotHandleContextLost) {
  14544. // We need to store the image if we need to rebuild the texture
  14545. // in case of a webgl context lost
  14546. texture._buffer = img;
  14547. }
  14548. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14549. var gl = _this._gl;
  14550. var isPot = (img.width === potWidth && img.height === potHeight);
  14551. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14552. if (isPot) {
  14553. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14554. return false;
  14555. }
  14556. // Using shaders to rescale because canvas.drawImage is lossy
  14557. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14558. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14559. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14560. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14561. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14564. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14565. _this._releaseTexture(source);
  14566. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14567. continuationCallback();
  14568. });
  14569. return true;
  14570. }, samplingMode);
  14571. };
  14572. if (!fromData || isBase64)
  14573. if (buffer instanceof HTMLImageElement) {
  14574. onload(buffer);
  14575. }
  14576. else {
  14577. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14578. }
  14579. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14580. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14581. else
  14582. onload(buffer);
  14583. }
  14584. return texture;
  14585. };
  14586. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14587. var _this = this;
  14588. var rtt = this.createRenderTargetTexture({
  14589. width: destination.width,
  14590. height: destination.height,
  14591. }, {
  14592. generateMipMaps: false,
  14593. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14594. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14595. generateDepthBuffer: false,
  14596. generateStencilBuffer: false
  14597. });
  14598. if (!this._rescalePostProcess) {
  14599. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14600. }
  14601. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14602. _this._rescalePostProcess.onApply = function (effect) {
  14603. effect._bindTexture("textureSampler", source);
  14604. };
  14605. var hostingScene = scene;
  14606. if (!hostingScene) {
  14607. hostingScene = _this.scenes[_this.scenes.length - 1];
  14608. }
  14609. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14610. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14611. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14612. _this.unBindFramebuffer(rtt);
  14613. _this._releaseTexture(rtt);
  14614. if (onComplete) {
  14615. onComplete();
  14616. }
  14617. });
  14618. };
  14619. /**
  14620. * Update a raw texture
  14621. * @param texture defines the texture to update
  14622. * @param data defines the data to store in the texture
  14623. * @param format defines the format of the data
  14624. * @param invertY defines if data must be stored with Y axis inverted
  14625. * @param compression defines the compression used (null by default)
  14626. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14627. */
  14628. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14629. if (compression === void 0) { compression = null; }
  14630. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14631. if (!texture) {
  14632. return;
  14633. }
  14634. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14635. var internalFormat = this._getInternalFormat(format);
  14636. var textureType = this._getWebGLTextureType(type);
  14637. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14638. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14639. if (!this._doNotHandleContextLost) {
  14640. texture._bufferView = data;
  14641. texture.format = format;
  14642. texture.type = type;
  14643. texture.invertY = invertY;
  14644. texture._compression = compression;
  14645. }
  14646. if (texture.width % 4 !== 0) {
  14647. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14648. }
  14649. if (compression && data) {
  14650. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14651. }
  14652. else {
  14653. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14654. }
  14655. if (texture.generateMipMaps) {
  14656. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14657. }
  14658. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14659. // this.resetTextureCache();
  14660. texture.isReady = true;
  14661. };
  14662. /**
  14663. * Creates a raw texture
  14664. * @param data defines the data to store in the texture
  14665. * @param width defines the width of the texture
  14666. * @param height defines the height of the texture
  14667. * @param format defines the format of the data
  14668. * @param generateMipMaps defines if the engine should generate the mip levels
  14669. * @param invertY defines if data must be stored with Y axis inverted
  14670. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14671. * @param compression defines the compression used (null by default)
  14672. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14673. * @returns the raw texture inside an InternalTexture
  14674. */
  14675. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14676. if (compression === void 0) { compression = null; }
  14677. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14678. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14679. texture.baseWidth = width;
  14680. texture.baseHeight = height;
  14681. texture.width = width;
  14682. texture.height = height;
  14683. texture.format = format;
  14684. texture.generateMipMaps = generateMipMaps;
  14685. texture.samplingMode = samplingMode;
  14686. texture.invertY = invertY;
  14687. texture._compression = compression;
  14688. texture.type = type;
  14689. if (!this._doNotHandleContextLost) {
  14690. texture._bufferView = data;
  14691. }
  14692. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14693. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14694. // Filters
  14695. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14696. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14697. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14698. if (generateMipMaps) {
  14699. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14700. }
  14701. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14702. this._internalTexturesCache.push(texture);
  14703. return texture;
  14704. };
  14705. /**
  14706. * Creates a dynamic texture
  14707. * @param width defines the width of the texture
  14708. * @param height defines the height of the texture
  14709. * @param generateMipMaps defines if the engine should generate the mip levels
  14710. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14711. * @returns the dynamic texture inside an InternalTexture
  14712. */
  14713. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14714. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14715. texture.baseWidth = width;
  14716. texture.baseHeight = height;
  14717. if (generateMipMaps) {
  14718. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14719. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14720. }
  14721. // this.resetTextureCache();
  14722. texture.width = width;
  14723. texture.height = height;
  14724. texture.isReady = false;
  14725. texture.generateMipMaps = generateMipMaps;
  14726. texture.samplingMode = samplingMode;
  14727. this.updateTextureSamplingMode(samplingMode, texture);
  14728. this._internalTexturesCache.push(texture);
  14729. return texture;
  14730. };
  14731. /**
  14732. * Update the sampling mode of a given texture
  14733. * @param samplingMode defines the required sampling mode
  14734. * @param texture defines the texture to update
  14735. */
  14736. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14737. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14738. if (texture.isCube) {
  14739. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14740. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14741. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14742. }
  14743. else if (texture.is3D) {
  14744. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14745. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14746. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14747. }
  14748. else {
  14749. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14750. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14751. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14752. }
  14753. texture.samplingMode = samplingMode;
  14754. };
  14755. /**
  14756. * Update the content of a dynamic texture
  14757. * @param texture defines the texture to update
  14758. * @param canvas defines the canvas containing the source
  14759. * @param invertY defines if data must be stored with Y axis inverted
  14760. * @param premulAlpha defines if alpha is stored as premultiplied
  14761. * @param format defines the format of the data
  14762. */
  14763. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14764. if (premulAlpha === void 0) { premulAlpha = false; }
  14765. if (!texture) {
  14766. return;
  14767. }
  14768. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14769. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14770. if (premulAlpha) {
  14771. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14772. }
  14773. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14774. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14775. if (texture.generateMipMaps) {
  14776. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14777. }
  14778. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14779. if (premulAlpha) {
  14780. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14781. }
  14782. texture.isReady = true;
  14783. };
  14784. /**
  14785. * Update a video texture
  14786. * @param texture defines the texture to update
  14787. * @param video defines the video element to use
  14788. * @param invertY defines if data must be stored with Y axis inverted
  14789. */
  14790. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14791. if (!texture || texture._isDisabled) {
  14792. return;
  14793. }
  14794. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14795. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14796. try {
  14797. // Testing video texture support
  14798. if (this._videoTextureSupported === undefined) {
  14799. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14800. if (this._gl.getError() !== 0) {
  14801. this._videoTextureSupported = false;
  14802. }
  14803. else {
  14804. this._videoTextureSupported = true;
  14805. }
  14806. }
  14807. // Copy video through the current working canvas if video texture is not supported
  14808. if (!this._videoTextureSupported) {
  14809. if (!texture._workingCanvas) {
  14810. texture._workingCanvas = document.createElement("canvas");
  14811. var context = texture._workingCanvas.getContext("2d");
  14812. if (!context) {
  14813. throw new Error("Unable to get 2d context");
  14814. }
  14815. texture._workingContext = context;
  14816. texture._workingCanvas.width = texture.width;
  14817. texture._workingCanvas.height = texture.height;
  14818. }
  14819. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14820. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14821. }
  14822. else {
  14823. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14824. }
  14825. if (texture.generateMipMaps) {
  14826. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14827. }
  14828. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14829. // this.resetTextureCache();
  14830. texture.isReady = true;
  14831. }
  14832. catch (ex) {
  14833. // Something unexpected
  14834. // Let's disable the texture
  14835. texture._isDisabled = true;
  14836. }
  14837. };
  14838. /**
  14839. * Updates a depth texture Comparison Mode and Function.
  14840. * If the comparison Function is equal to 0, the mode will be set to none.
  14841. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14842. * @param texture The texture to set the comparison function for
  14843. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14844. */
  14845. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14846. if (this.webGLVersion === 1) {
  14847. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14848. return;
  14849. }
  14850. var gl = this._gl;
  14851. if (texture.isCube) {
  14852. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14853. if (comparisonFunction === 0) {
  14854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14856. }
  14857. else {
  14858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14859. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14860. }
  14861. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14862. }
  14863. else {
  14864. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14865. if (comparisonFunction === 0) {
  14866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14868. }
  14869. else {
  14870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14872. }
  14873. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14874. }
  14875. texture._comparisonFunction = comparisonFunction;
  14876. };
  14877. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14878. var width = size.width || size;
  14879. var height = size.height || size;
  14880. internalTexture.baseWidth = width;
  14881. internalTexture.baseHeight = height;
  14882. internalTexture.width = width;
  14883. internalTexture.height = height;
  14884. internalTexture.isReady = true;
  14885. internalTexture.samples = 1;
  14886. internalTexture.generateMipMaps = false;
  14887. internalTexture._generateDepthBuffer = true;
  14888. internalTexture._generateStencilBuffer = generateStencil;
  14889. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14890. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14891. internalTexture._comparisonFunction = comparisonFunction;
  14892. var gl = this._gl;
  14893. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14894. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14895. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14896. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14897. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14898. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14899. if (comparisonFunction === 0) {
  14900. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14901. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14902. }
  14903. else {
  14904. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14905. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14906. }
  14907. };
  14908. /**
  14909. * Creates a depth stencil texture.
  14910. * This is only available in WebGL 2 or with the depth texture extension available.
  14911. * @param size The size of face edge in the texture.
  14912. * @param options The options defining the texture.
  14913. * @returns The texture
  14914. */
  14915. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14916. if (options.isCube) {
  14917. var width = size.width || size;
  14918. return this._createDepthStencilCubeTexture(width, options);
  14919. }
  14920. else {
  14921. return this._createDepthStencilTexture(size, options);
  14922. }
  14923. };
  14924. /**
  14925. * Creates a depth stencil texture.
  14926. * This is only available in WebGL 2 or with the depth texture extension available.
  14927. * @param size The size of face edge in the texture.
  14928. * @param options The options defining the texture.
  14929. * @returns The texture
  14930. */
  14931. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14932. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14933. if (!this._caps.depthTextureExtension) {
  14934. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14935. return internalTexture;
  14936. }
  14937. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14938. var gl = this._gl;
  14939. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14940. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14941. if (this.webGLVersion > 1) {
  14942. if (internalOptions.generateStencil) {
  14943. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14944. }
  14945. else {
  14946. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14947. }
  14948. }
  14949. else {
  14950. if (internalOptions.generateStencil) {
  14951. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14952. }
  14953. else {
  14954. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14955. }
  14956. }
  14957. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14958. return internalTexture;
  14959. };
  14960. /**
  14961. * Creates a depth stencil cube texture.
  14962. * This is only available in WebGL 2.
  14963. * @param size The size of face edge in the cube texture.
  14964. * @param options The options defining the cube texture.
  14965. * @returns The cube texture
  14966. */
  14967. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14968. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14969. internalTexture.isCube = true;
  14970. if (this.webGLVersion === 1) {
  14971. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14972. return internalTexture;
  14973. }
  14974. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14975. var gl = this._gl;
  14976. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14977. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14978. // Create the depth/stencil buffer
  14979. for (var face = 0; face < 6; face++) {
  14980. if (internalOptions.generateStencil) {
  14981. 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);
  14982. }
  14983. else {
  14984. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14985. }
  14986. }
  14987. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14988. return internalTexture;
  14989. };
  14990. /**
  14991. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14992. * @param renderTarget The render target to set the frame buffer for
  14993. */
  14994. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14995. // Create the framebuffer
  14996. var internalTexture = renderTarget.getInternalTexture();
  14997. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14998. return;
  14999. }
  15000. var gl = this._gl;
  15001. var depthStencilTexture = renderTarget.depthStencilTexture;
  15002. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15003. if (depthStencilTexture.isCube) {
  15004. if (depthStencilTexture._generateStencilBuffer) {
  15005. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15006. }
  15007. else {
  15008. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15009. }
  15010. }
  15011. else {
  15012. if (depthStencilTexture._generateStencilBuffer) {
  15013. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15014. }
  15015. else {
  15016. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15017. }
  15018. }
  15019. this.bindUnboundFramebuffer(null);
  15020. };
  15021. /**
  15022. * Creates a new render target texture
  15023. * @param size defines the size of the texture
  15024. * @param options defines the options used to create the texture
  15025. * @returns a new render target texture stored in an InternalTexture
  15026. */
  15027. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15028. var fullOptions = new RenderTargetCreationOptions();
  15029. if (options !== undefined && typeof options === "object") {
  15030. fullOptions.generateMipMaps = options.generateMipMaps;
  15031. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15032. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15033. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15034. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15035. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15036. }
  15037. else {
  15038. fullOptions.generateMipMaps = options;
  15039. fullOptions.generateDepthBuffer = true;
  15040. fullOptions.generateStencilBuffer = false;
  15041. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15042. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15043. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15044. }
  15045. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15046. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15047. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15048. }
  15049. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15050. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15051. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15052. }
  15053. var gl = this._gl;
  15054. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15055. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15056. var width = size.width || size;
  15057. var height = size.height || size;
  15058. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15059. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15060. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15061. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15062. }
  15063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15067. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15068. // Create the framebuffer
  15069. var framebuffer = gl.createFramebuffer();
  15070. this.bindUnboundFramebuffer(framebuffer);
  15071. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15072. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15073. if (fullOptions.generateMipMaps) {
  15074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15075. }
  15076. // Unbind
  15077. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15078. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15079. this.bindUnboundFramebuffer(null);
  15080. texture._framebuffer = framebuffer;
  15081. texture.baseWidth = width;
  15082. texture.baseHeight = height;
  15083. texture.width = width;
  15084. texture.height = height;
  15085. texture.isReady = true;
  15086. texture.samples = 1;
  15087. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15088. texture.samplingMode = fullOptions.samplingMode;
  15089. texture.type = fullOptions.type;
  15090. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15091. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15092. // this.resetTextureCache();
  15093. this._internalTexturesCache.push(texture);
  15094. return texture;
  15095. };
  15096. /**
  15097. * Create a multi render target texture
  15098. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15099. * @param size defines the size of the texture
  15100. * @param options defines the creation options
  15101. * @returns the cube texture as an InternalTexture
  15102. */
  15103. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15104. var generateMipMaps = false;
  15105. var generateDepthBuffer = true;
  15106. var generateStencilBuffer = false;
  15107. var generateDepthTexture = false;
  15108. var textureCount = 1;
  15109. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15110. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15111. var types = new Array();
  15112. var samplingModes = new Array();
  15113. if (options !== undefined) {
  15114. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15115. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15116. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15117. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15118. textureCount = options.textureCount || 1;
  15119. if (options.types) {
  15120. types = options.types;
  15121. }
  15122. if (options.samplingModes) {
  15123. samplingModes = options.samplingModes;
  15124. }
  15125. }
  15126. var gl = this._gl;
  15127. // Create the framebuffer
  15128. var framebuffer = gl.createFramebuffer();
  15129. this.bindUnboundFramebuffer(framebuffer);
  15130. var width = size.width || size;
  15131. var height = size.height || size;
  15132. var textures = [];
  15133. var attachments = [];
  15134. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15135. for (var i = 0; i < textureCount; i++) {
  15136. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15137. var type = types[i] || defaultType;
  15138. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15139. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15140. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15141. }
  15142. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15143. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15144. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15145. }
  15146. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15147. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15148. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15149. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15150. }
  15151. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15152. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15153. textures.push(texture);
  15154. attachments.push(attachment);
  15155. gl.activeTexture(gl["TEXTURE" + i]);
  15156. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15157. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15158. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15159. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15161. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15162. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15163. if (generateMipMaps) {
  15164. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15165. }
  15166. // Unbind
  15167. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15168. texture._framebuffer = framebuffer;
  15169. texture._depthStencilBuffer = depthStencilBuffer;
  15170. texture.baseWidth = width;
  15171. texture.baseHeight = height;
  15172. texture.width = width;
  15173. texture.height = height;
  15174. texture.isReady = true;
  15175. texture.samples = 1;
  15176. texture.generateMipMaps = generateMipMaps;
  15177. texture.samplingMode = samplingMode;
  15178. texture.type = type;
  15179. texture._generateDepthBuffer = generateDepthBuffer;
  15180. texture._generateStencilBuffer = generateStencilBuffer;
  15181. texture._attachments = attachments;
  15182. this._internalTexturesCache.push(texture);
  15183. }
  15184. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15185. // Depth texture
  15186. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15187. gl.activeTexture(gl.TEXTURE0);
  15188. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15191. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15193. 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);
  15194. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15195. depthTexture._framebuffer = framebuffer;
  15196. depthTexture.baseWidth = width;
  15197. depthTexture.baseHeight = height;
  15198. depthTexture.width = width;
  15199. depthTexture.height = height;
  15200. depthTexture.isReady = true;
  15201. depthTexture.samples = 1;
  15202. depthTexture.generateMipMaps = generateMipMaps;
  15203. depthTexture.samplingMode = gl.NEAREST;
  15204. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15205. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15206. textures.push(depthTexture);
  15207. this._internalTexturesCache.push(depthTexture);
  15208. }
  15209. gl.drawBuffers(attachments);
  15210. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15211. this.bindUnboundFramebuffer(null);
  15212. this.resetTextureCache();
  15213. return textures;
  15214. };
  15215. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15216. if (samples === void 0) { samples = 1; }
  15217. var depthStencilBuffer = null;
  15218. var gl = this._gl;
  15219. // Create the depth/stencil buffer
  15220. if (generateStencilBuffer) {
  15221. depthStencilBuffer = gl.createRenderbuffer();
  15222. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15223. if (samples > 1) {
  15224. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15225. }
  15226. else {
  15227. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15228. }
  15229. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15230. }
  15231. else if (generateDepthBuffer) {
  15232. depthStencilBuffer = gl.createRenderbuffer();
  15233. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15234. if (samples > 1) {
  15235. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15236. }
  15237. else {
  15238. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15239. }
  15240. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15241. }
  15242. return depthStencilBuffer;
  15243. };
  15244. /**
  15245. * Updates the sample count of a render target texture
  15246. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15247. * @param texture defines the texture to update
  15248. * @param samples defines the sample count to set
  15249. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15250. */
  15251. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15252. if (this.webGLVersion < 2 || !texture) {
  15253. return 1;
  15254. }
  15255. if (texture.samples === samples) {
  15256. return samples;
  15257. }
  15258. var gl = this._gl;
  15259. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15260. // Dispose previous render buffers
  15261. if (texture._depthStencilBuffer) {
  15262. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15263. texture._depthStencilBuffer = null;
  15264. }
  15265. if (texture._MSAAFramebuffer) {
  15266. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15267. texture._MSAAFramebuffer = null;
  15268. }
  15269. if (texture._MSAARenderBuffer) {
  15270. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15271. texture._MSAARenderBuffer = null;
  15272. }
  15273. if (samples > 1) {
  15274. var framebuffer = gl.createFramebuffer();
  15275. if (!framebuffer) {
  15276. throw new Error("Unable to create multi sampled framebuffer");
  15277. }
  15278. texture._MSAAFramebuffer = framebuffer;
  15279. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15280. var colorRenderbuffer = gl.createRenderbuffer();
  15281. if (!colorRenderbuffer) {
  15282. throw new Error("Unable to create multi sampled framebuffer");
  15283. }
  15284. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15285. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15286. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15287. texture._MSAARenderBuffer = colorRenderbuffer;
  15288. }
  15289. else {
  15290. this.bindUnboundFramebuffer(texture._framebuffer);
  15291. }
  15292. texture.samples = samples;
  15293. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15294. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15295. this.bindUnboundFramebuffer(null);
  15296. return samples;
  15297. };
  15298. /**
  15299. * Update the sample count for a given multiple render target texture
  15300. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15301. * @param textures defines the textures to update
  15302. * @param samples defines the sample count to set
  15303. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15304. */
  15305. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15306. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15307. return 1;
  15308. }
  15309. if (textures[0].samples === samples) {
  15310. return samples;
  15311. }
  15312. var gl = this._gl;
  15313. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15314. // Dispose previous render buffers
  15315. if (textures[0]._depthStencilBuffer) {
  15316. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15317. textures[0]._depthStencilBuffer = null;
  15318. }
  15319. if (textures[0]._MSAAFramebuffer) {
  15320. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15321. textures[0]._MSAAFramebuffer = null;
  15322. }
  15323. for (var i = 0; i < textures.length; i++) {
  15324. if (textures[i]._MSAARenderBuffer) {
  15325. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15326. textures[i]._MSAARenderBuffer = null;
  15327. }
  15328. }
  15329. if (samples > 1) {
  15330. var framebuffer = gl.createFramebuffer();
  15331. if (!framebuffer) {
  15332. throw new Error("Unable to create multi sampled framebuffer");
  15333. }
  15334. this.bindUnboundFramebuffer(framebuffer);
  15335. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15336. var attachments = [];
  15337. for (var i = 0; i < textures.length; i++) {
  15338. var texture = textures[i];
  15339. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15340. var colorRenderbuffer = gl.createRenderbuffer();
  15341. if (!colorRenderbuffer) {
  15342. throw new Error("Unable to create multi sampled framebuffer");
  15343. }
  15344. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15345. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15346. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15347. texture._MSAAFramebuffer = framebuffer;
  15348. texture._MSAARenderBuffer = colorRenderbuffer;
  15349. texture.samples = samples;
  15350. texture._depthStencilBuffer = depthStencilBuffer;
  15351. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15352. attachments.push(attachment);
  15353. }
  15354. gl.drawBuffers(attachments);
  15355. }
  15356. else {
  15357. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15358. }
  15359. this.bindUnboundFramebuffer(null);
  15360. return samples;
  15361. };
  15362. /** @hidden */
  15363. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15364. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15365. };
  15366. /** @hidden */
  15367. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15368. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15369. };
  15370. /**
  15371. * Creates a new render target cube texture
  15372. * @param size defines the size of the texture
  15373. * @param options defines the options used to create the texture
  15374. * @returns a new render target cube texture stored in an InternalTexture
  15375. */
  15376. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15377. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15378. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15379. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15380. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15381. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15382. }
  15383. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15384. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15385. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15386. }
  15387. var gl = this._gl;
  15388. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15389. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15390. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15391. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15392. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15393. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15394. }
  15395. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15397. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15399. for (var face = 0; face < 6; face++) {
  15400. 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);
  15401. }
  15402. // Create the framebuffer
  15403. var framebuffer = gl.createFramebuffer();
  15404. this.bindUnboundFramebuffer(framebuffer);
  15405. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15406. // MipMaps
  15407. if (fullOptions.generateMipMaps) {
  15408. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15409. }
  15410. // Unbind
  15411. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15412. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15413. this.bindUnboundFramebuffer(null);
  15414. texture._framebuffer = framebuffer;
  15415. texture.width = size;
  15416. texture.height = size;
  15417. texture.isReady = true;
  15418. texture.isCube = true;
  15419. texture.samples = 1;
  15420. texture.generateMipMaps = fullOptions.generateMipMaps;
  15421. texture.samplingMode = fullOptions.samplingMode;
  15422. texture.type = fullOptions.type;
  15423. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15424. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15425. this._internalTexturesCache.push(texture);
  15426. return texture;
  15427. };
  15428. /**
  15429. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15430. * @param rootUrl defines the url where the file to load is located
  15431. * @param scene defines the current scene
  15432. * @param scale defines scale to apply to the mip map selection
  15433. * @param offset defines offset to apply to the mip map selection
  15434. * @param onLoad defines an optional callback raised when the texture is loaded
  15435. * @param onError defines an optional callback raised if there is an issue to load the texture
  15436. * @param format defines the format of the data
  15437. * @param forcedExtension defines the extension to use to pick the right loader
  15438. * @returns the cube texture as an InternalTexture
  15439. */
  15440. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15441. var _this = this;
  15442. if (onLoad === void 0) { onLoad = null; }
  15443. if (onError === void 0) { onError = null; }
  15444. if (forcedExtension === void 0) { forcedExtension = null; }
  15445. var callback = function (loadData) {
  15446. if (!loadData) {
  15447. if (onLoad) {
  15448. onLoad(null);
  15449. }
  15450. return;
  15451. }
  15452. var texture = loadData.texture;
  15453. if (loadData.info.sphericalPolynomial) {
  15454. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15455. }
  15456. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15457. texture._lodGenerationScale = scale;
  15458. texture._lodGenerationOffset = offset;
  15459. if (_this._caps.textureLOD) {
  15460. // Do not add extra process if texture lod is supported.
  15461. if (onLoad) {
  15462. onLoad(texture);
  15463. }
  15464. return;
  15465. }
  15466. var mipSlices = 3;
  15467. var gl = _this._gl;
  15468. var width = loadData.width;
  15469. if (!width) {
  15470. return;
  15471. }
  15472. var textures = [];
  15473. for (var i = 0; i < mipSlices; i++) {
  15474. //compute LOD from even spacing in smoothness (matching shader calculation)
  15475. var smoothness = i / (mipSlices - 1);
  15476. var roughness = 1 - smoothness;
  15477. var minLODIndex = offset; // roughness = 0
  15478. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15479. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15480. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15481. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15482. glTextureFromLod.isCube = true;
  15483. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15488. if (loadData.isDDS) {
  15489. var info = loadData.info;
  15490. var data = loadData.data;
  15491. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15492. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15493. }
  15494. else {
  15495. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15496. }
  15497. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15498. // Wrap in a base texture for easy binding.
  15499. var lodTexture = new BABYLON.BaseTexture(scene);
  15500. lodTexture.isCube = true;
  15501. lodTexture._texture = glTextureFromLod;
  15502. glTextureFromLod.isReady = true;
  15503. textures.push(lodTexture);
  15504. }
  15505. texture._lodTextureHigh = textures[2];
  15506. texture._lodTextureMid = textures[1];
  15507. texture._lodTextureLow = textures[0];
  15508. if (onLoad) {
  15509. onLoad(texture);
  15510. }
  15511. };
  15512. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15513. };
  15514. /**
  15515. * Creates a cube texture
  15516. * @param rootUrl defines the url where the files to load is located
  15517. * @param scene defines the current scene
  15518. * @param files defines the list of files to load (1 per face)
  15519. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15520. * @param onLoad defines an optional callback raised when the texture is loaded
  15521. * @param onError defines an optional callback raised if there is an issue to load the texture
  15522. * @param format defines the format of the data
  15523. * @param forcedExtension defines the extension to use to pick the right loader
  15524. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15525. * @returns the cube texture as an InternalTexture
  15526. */
  15527. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15528. var _this = this;
  15529. if (onLoad === void 0) { onLoad = null; }
  15530. if (onError === void 0) { onError = null; }
  15531. if (forcedExtension === void 0) { forcedExtension = null; }
  15532. if (createPolynomials === void 0) { createPolynomials = false; }
  15533. var gl = this._gl;
  15534. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15535. texture.isCube = true;
  15536. texture.url = rootUrl;
  15537. texture.generateMipMaps = !noMipmap;
  15538. if (!this._doNotHandleContextLost) {
  15539. texture._extension = forcedExtension;
  15540. texture._files = files;
  15541. }
  15542. var isKTX = false;
  15543. var isDDS = false;
  15544. var lastDot = rootUrl.lastIndexOf('.');
  15545. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15546. if (this._textureFormatInUse) {
  15547. extension = this._textureFormatInUse;
  15548. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15549. isKTX = true;
  15550. }
  15551. else {
  15552. isDDS = (extension === ".dds");
  15553. }
  15554. var onerror = function (request, exception) {
  15555. if (onError && request) {
  15556. onError(request.status + " " + request.statusText, exception);
  15557. }
  15558. };
  15559. if (isKTX) {
  15560. this._loadFile(rootUrl, function (data) {
  15561. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15562. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15563. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15564. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15565. ktx.uploadLevels(_this._gl, !noMipmap);
  15566. _this.setCubeMapTextureParams(gl, loadMipmap);
  15567. texture.width = ktx.pixelWidth;
  15568. texture.height = ktx.pixelHeight;
  15569. texture.isReady = true;
  15570. }, undefined, undefined, true, onerror);
  15571. }
  15572. else if (isDDS) {
  15573. if (files && files.length === 6) {
  15574. this._cascadeLoadFiles(scene, function (imgs) {
  15575. var info;
  15576. var loadMipmap = false;
  15577. var width = 0;
  15578. for (var index = 0; index < imgs.length; index++) {
  15579. var data = imgs[index];
  15580. info = BABYLON.DDSTools.GetDDSInfo(data);
  15581. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15582. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15583. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15584. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15585. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15586. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15587. }
  15588. texture.width = info.width;
  15589. texture.height = info.height;
  15590. texture.type = info.textureType;
  15591. width = info.width;
  15592. }
  15593. _this.setCubeMapTextureParams(gl, loadMipmap);
  15594. texture.isReady = true;
  15595. if (onLoad) {
  15596. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15597. }
  15598. }, files, onError);
  15599. }
  15600. else {
  15601. this._loadFile(rootUrl, function (data) {
  15602. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15603. if (createPolynomials) {
  15604. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15605. }
  15606. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15607. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15608. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15609. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15610. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15611. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15612. }
  15613. _this.setCubeMapTextureParams(gl, loadMipmap);
  15614. texture.width = info.width;
  15615. texture.height = info.height;
  15616. texture.isReady = true;
  15617. texture.type = info.textureType;
  15618. if (onLoad) {
  15619. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15620. }
  15621. }, undefined, undefined, true, onerror);
  15622. }
  15623. }
  15624. else {
  15625. if (!files) {
  15626. throw new Error("Cannot load cubemap because files were not defined");
  15627. }
  15628. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15629. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15630. var height = width;
  15631. _this._prepareWorkingCanvas();
  15632. if (!_this._workingCanvas || !_this._workingContext) {
  15633. return;
  15634. }
  15635. _this._workingCanvas.width = width;
  15636. _this._workingCanvas.height = height;
  15637. var faces = [
  15638. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15639. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15640. ];
  15641. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15642. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15643. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15644. for (var index = 0; index < faces.length; index++) {
  15645. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15646. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15647. }
  15648. if (!noMipmap) {
  15649. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15650. }
  15651. _this.setCubeMapTextureParams(gl, !noMipmap);
  15652. texture.width = width;
  15653. texture.height = height;
  15654. texture.isReady = true;
  15655. if (format) {
  15656. texture.format = format;
  15657. }
  15658. texture.onLoadedObservable.notifyObservers(texture);
  15659. texture.onLoadedObservable.clear();
  15660. if (onLoad) {
  15661. onLoad();
  15662. }
  15663. }, files, onError);
  15664. }
  15665. this._internalTexturesCache.push(texture);
  15666. return texture;
  15667. };
  15668. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15669. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15670. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15672. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15673. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15674. // this.resetTextureCache();
  15675. };
  15676. /**
  15677. * Update a raw cube texture
  15678. * @param texture defines the texture to udpdate
  15679. * @param data defines the data to store
  15680. * @param format defines the data format
  15681. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15682. * @param invertY defines if data must be stored with Y axis inverted
  15683. * @param compression defines the compression used (null by default)
  15684. * @param level defines which level of the texture to update
  15685. */
  15686. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15687. if (compression === void 0) { compression = null; }
  15688. if (level === void 0) { level = 0; }
  15689. texture._bufferViewArray = data;
  15690. texture.format = format;
  15691. texture.type = type;
  15692. texture.invertY = invertY;
  15693. texture._compression = compression;
  15694. var gl = this._gl;
  15695. var textureType = this._getWebGLTextureType(type);
  15696. var internalFormat = this._getInternalFormat(format);
  15697. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15698. var needConversion = false;
  15699. if (internalFormat === gl.RGB) {
  15700. internalFormat = gl.RGBA;
  15701. needConversion = true;
  15702. }
  15703. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15704. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15705. if (texture.width % 4 !== 0) {
  15706. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15707. }
  15708. // Data are known to be in +X +Y +Z -X -Y -Z
  15709. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15710. var faceData = data[faceIndex];
  15711. if (compression) {
  15712. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15713. }
  15714. else {
  15715. if (needConversion) {
  15716. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15717. }
  15718. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15719. }
  15720. }
  15721. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15722. if (isPot && texture.generateMipMaps && level === 0) {
  15723. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15724. }
  15725. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15726. // this.resetTextureCache();
  15727. texture.isReady = true;
  15728. };
  15729. /**
  15730. * Creates a new raw cube texture
  15731. * @param data defines the array of data to use to create each face
  15732. * @param size defines the size of the textures
  15733. * @param format defines the format of the data
  15734. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15735. * @param generateMipMaps defines if the engine should generate the mip levels
  15736. * @param invertY defines if data must be stored with Y axis inverted
  15737. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15738. * @param compression defines the compression used (null by default)
  15739. * @returns the cube texture as an InternalTexture
  15740. */
  15741. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15742. if (compression === void 0) { compression = null; }
  15743. var gl = this._gl;
  15744. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15745. texture.isCube = true;
  15746. texture.generateMipMaps = generateMipMaps;
  15747. texture.format = format;
  15748. texture.type = type;
  15749. if (!this._doNotHandleContextLost) {
  15750. texture._bufferViewArray = data;
  15751. }
  15752. var textureType = this._getWebGLTextureType(type);
  15753. var internalFormat = this._getInternalFormat(format);
  15754. if (internalFormat === gl.RGB) {
  15755. internalFormat = gl.RGBA;
  15756. }
  15757. var width = size;
  15758. var height = width;
  15759. texture.width = width;
  15760. texture.height = height;
  15761. // Double check on POT to generate Mips.
  15762. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15763. if (!isPot) {
  15764. generateMipMaps = false;
  15765. }
  15766. // Upload data if needed. The texture won't be ready until then.
  15767. if (data) {
  15768. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15769. }
  15770. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15771. // Filters
  15772. if (data && generateMipMaps) {
  15773. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15774. }
  15775. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15778. }
  15779. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15782. }
  15783. else {
  15784. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15787. }
  15788. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15789. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15790. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15791. return texture;
  15792. };
  15793. /**
  15794. * Creates a new raw cube texture from a specified url
  15795. * @param url defines the url where the data is located
  15796. * @param scene defines the current scene
  15797. * @param size defines the size of the textures
  15798. * @param format defines the format of the data
  15799. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15800. * @param noMipmap defines if the engine should avoid generating the mip levels
  15801. * @param callback defines a callback used to extract texture data from loaded data
  15802. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15803. * @param onLoad defines a callback called when texture is loaded
  15804. * @param onError defines a callback called if there is an error
  15805. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15806. * @param invertY defines if data must be stored with Y axis inverted
  15807. * @returns the cube texture as an InternalTexture
  15808. */
  15809. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15810. var _this = this;
  15811. if (onLoad === void 0) { onLoad = null; }
  15812. if (onError === void 0) { onError = null; }
  15813. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15814. if (invertY === void 0) { invertY = false; }
  15815. var gl = this._gl;
  15816. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15817. scene._addPendingData(texture);
  15818. texture.url = url;
  15819. this._internalTexturesCache.push(texture);
  15820. var onerror = function (request, exception) {
  15821. scene._removePendingData(texture);
  15822. if (onError && request) {
  15823. onError(request.status + " " + request.statusText, exception);
  15824. }
  15825. };
  15826. var internalCallback = function (data) {
  15827. var width = texture.width;
  15828. var faceDataArrays = callback(data);
  15829. if (!faceDataArrays) {
  15830. return;
  15831. }
  15832. if (mipmapGenerator) {
  15833. var textureType = _this._getWebGLTextureType(type);
  15834. var internalFormat = _this._getInternalFormat(format);
  15835. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15836. var needConversion = false;
  15837. if (internalFormat === gl.RGB) {
  15838. internalFormat = gl.RGBA;
  15839. needConversion = true;
  15840. }
  15841. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15842. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15843. var mipData = mipmapGenerator(faceDataArrays);
  15844. for (var level = 0; level < mipData.length; level++) {
  15845. var mipSize = width >> level;
  15846. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15847. var mipFaceData = mipData[level][faceIndex];
  15848. if (needConversion) {
  15849. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15850. }
  15851. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15852. }
  15853. }
  15854. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15855. }
  15856. else {
  15857. texture.generateMipMaps = !noMipmap;
  15858. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15859. }
  15860. texture.isReady = true;
  15861. // this.resetTextureCache();
  15862. scene._removePendingData(texture);
  15863. if (onLoad) {
  15864. onLoad();
  15865. }
  15866. };
  15867. this._loadFile(url, function (data) {
  15868. internalCallback(data);
  15869. }, undefined, scene.database, true, onerror);
  15870. return texture;
  15871. };
  15872. ;
  15873. /**
  15874. * Update a raw 3D texture
  15875. * @param texture defines the texture to update
  15876. * @param data defines the data to store
  15877. * @param format defines the data format
  15878. * @param invertY defines if data must be stored with Y axis inverted
  15879. * @param compression defines the used compression (can be null)
  15880. */
  15881. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15882. if (compression === void 0) { compression = null; }
  15883. var internalFormat = this._getInternalFormat(format);
  15884. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15885. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15886. if (!this._doNotHandleContextLost) {
  15887. texture._bufferView = data;
  15888. texture.format = format;
  15889. texture.invertY = invertY;
  15890. texture._compression = compression;
  15891. }
  15892. if (texture.width % 4 !== 0) {
  15893. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15894. }
  15895. if (compression && data) {
  15896. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15897. }
  15898. else {
  15899. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15900. }
  15901. if (texture.generateMipMaps) {
  15902. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15903. }
  15904. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15905. // this.resetTextureCache();
  15906. texture.isReady = true;
  15907. };
  15908. /**
  15909. * Creates a new raw 3D texture
  15910. * @param data defines the data used to create the texture
  15911. * @param width defines the width of the texture
  15912. * @param height defines the height of the texture
  15913. * @param depth defines the depth of the texture
  15914. * @param format defines the format of the texture
  15915. * @param generateMipMaps defines if the engine must generate mip levels
  15916. * @param invertY defines if data must be stored with Y axis inverted
  15917. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15918. * @param compression defines the compressed used (can be null)
  15919. * @returns a new raw 3D texture (stored in an InternalTexture)
  15920. */
  15921. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15922. if (compression === void 0) { compression = null; }
  15923. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15924. texture.baseWidth = width;
  15925. texture.baseHeight = height;
  15926. texture.baseDepth = depth;
  15927. texture.width = width;
  15928. texture.height = height;
  15929. texture.depth = depth;
  15930. texture.format = format;
  15931. texture.generateMipMaps = generateMipMaps;
  15932. texture.samplingMode = samplingMode;
  15933. texture.is3D = true;
  15934. if (!this._doNotHandleContextLost) {
  15935. texture._bufferView = data;
  15936. }
  15937. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15938. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15939. // Filters
  15940. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15941. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15942. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15943. if (generateMipMaps) {
  15944. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15945. }
  15946. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15947. this._internalTexturesCache.push(texture);
  15948. return texture;
  15949. };
  15950. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15951. var gl = this._gl;
  15952. if (!gl) {
  15953. return;
  15954. }
  15955. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15956. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15957. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15958. if (!noMipmap && !isCompressed) {
  15959. gl.generateMipmap(gl.TEXTURE_2D);
  15960. }
  15961. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15962. // this.resetTextureCache();
  15963. if (scene) {
  15964. scene._removePendingData(texture);
  15965. }
  15966. texture.onLoadedObservable.notifyObservers(texture);
  15967. texture.onLoadedObservable.clear();
  15968. };
  15969. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15970. var _this = this;
  15971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15972. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15973. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15974. var gl = this._gl;
  15975. if (!gl) {
  15976. return;
  15977. }
  15978. if (!texture._webGLTexture) {
  15979. // this.resetTextureCache();
  15980. if (scene) {
  15981. scene._removePendingData(texture);
  15982. }
  15983. return;
  15984. }
  15985. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15986. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15987. texture.baseWidth = width;
  15988. texture.baseHeight = height;
  15989. texture.width = potWidth;
  15990. texture.height = potHeight;
  15991. texture.isReady = true;
  15992. if (processFunction(potWidth, potHeight, function () {
  15993. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15994. })) {
  15995. // Returning as texture needs extra async steps
  15996. return;
  15997. }
  15998. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15999. };
  16000. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16001. // Create new RGBA data container.
  16002. var rgbaData;
  16003. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16004. rgbaData = new Float32Array(width * height * 4);
  16005. }
  16006. else {
  16007. rgbaData = new Uint32Array(width * height * 4);
  16008. }
  16009. // Convert each pixel.
  16010. for (var x = 0; x < width; x++) {
  16011. for (var y = 0; y < height; y++) {
  16012. var index = (y * width + x) * 3;
  16013. var newIndex = (y * width + x) * 4;
  16014. // Map Old Value to new value.
  16015. rgbaData[newIndex + 0] = rgbData[index + 0];
  16016. rgbaData[newIndex + 1] = rgbData[index + 1];
  16017. rgbaData[newIndex + 2] = rgbData[index + 2];
  16018. // Add fully opaque alpha channel.
  16019. rgbaData[newIndex + 3] = 1;
  16020. }
  16021. }
  16022. return rgbaData;
  16023. };
  16024. /** @hidden */
  16025. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16026. var gl = this._gl;
  16027. if (texture._framebuffer) {
  16028. gl.deleteFramebuffer(texture._framebuffer);
  16029. texture._framebuffer = null;
  16030. }
  16031. if (texture._depthStencilBuffer) {
  16032. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16033. texture._depthStencilBuffer = null;
  16034. }
  16035. if (texture._MSAAFramebuffer) {
  16036. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16037. texture._MSAAFramebuffer = null;
  16038. }
  16039. if (texture._MSAARenderBuffer) {
  16040. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16041. texture._MSAARenderBuffer = null;
  16042. }
  16043. };
  16044. /** @hidden */
  16045. Engine.prototype._releaseTexture = function (texture) {
  16046. var gl = this._gl;
  16047. this._releaseFramebufferObjects(texture);
  16048. gl.deleteTexture(texture._webGLTexture);
  16049. // Unbind channels
  16050. this.unbindAllTextures();
  16051. var index = this._internalTexturesCache.indexOf(texture);
  16052. if (index !== -1) {
  16053. this._internalTexturesCache.splice(index, 1);
  16054. }
  16055. // Integrated fixed lod samplers.
  16056. if (texture._lodTextureHigh) {
  16057. texture._lodTextureHigh.dispose();
  16058. }
  16059. if (texture._lodTextureMid) {
  16060. texture._lodTextureMid.dispose();
  16061. }
  16062. if (texture._lodTextureLow) {
  16063. texture._lodTextureLow.dispose();
  16064. }
  16065. // Set output texture of post process to null if the texture has been released/disposed
  16066. this.scenes.forEach(function (scene) {
  16067. scene.postProcesses.forEach(function (postProcess) {
  16068. if (postProcess._outputTexture == texture) {
  16069. postProcess._outputTexture = null;
  16070. }
  16071. });
  16072. scene.cameras.forEach(function (camera) {
  16073. camera._postProcesses.forEach(function (postProcess) {
  16074. if (postProcess) {
  16075. if (postProcess._outputTexture == texture) {
  16076. postProcess._outputTexture = null;
  16077. }
  16078. }
  16079. });
  16080. });
  16081. });
  16082. };
  16083. Engine.prototype.setProgram = function (program) {
  16084. if (this._currentProgram !== program) {
  16085. this._gl.useProgram(program);
  16086. this._currentProgram = program;
  16087. }
  16088. };
  16089. /**
  16090. * Binds an effect to the webGL context
  16091. * @param effect defines the effect to bind
  16092. */
  16093. Engine.prototype.bindSamplers = function (effect) {
  16094. this.setProgram(effect.getProgram());
  16095. var samplers = effect.getSamplers();
  16096. for (var index = 0; index < samplers.length; index++) {
  16097. var uniform = effect.getUniform(samplers[index]);
  16098. if (uniform) {
  16099. this._boundUniforms[index] = uniform;
  16100. }
  16101. }
  16102. this._currentEffect = null;
  16103. };
  16104. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16105. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16106. return;
  16107. }
  16108. // Remove
  16109. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16110. // Bind last to it
  16111. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16112. // Bind to dummy
  16113. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16114. };
  16115. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16116. if (!internalTexture) {
  16117. return -1;
  16118. }
  16119. internalTexture._initialSlot = channel;
  16120. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16121. if (channel !== internalTexture._designatedSlot) {
  16122. this._textureCollisions.addCount(1, false);
  16123. }
  16124. }
  16125. else {
  16126. if (channel !== internalTexture._designatedSlot) {
  16127. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16128. return internalTexture._designatedSlot;
  16129. }
  16130. else {
  16131. // No slot for this texture, let's pick a new one (if we find a free slot)
  16132. if (this._nextFreeTextureSlots.length) {
  16133. return this._nextFreeTextureSlots[0];
  16134. }
  16135. // We need to recycle the oldest bound texture, sorry.
  16136. this._textureCollisions.addCount(1, false);
  16137. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16138. }
  16139. }
  16140. }
  16141. return channel;
  16142. };
  16143. Engine.prototype._linkTrackers = function (previous, next) {
  16144. previous.next = next;
  16145. next.previous = previous;
  16146. };
  16147. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16148. var currentSlot = internalTexture._designatedSlot;
  16149. if (currentSlot === -1) {
  16150. return -1;
  16151. }
  16152. internalTexture._designatedSlot = -1;
  16153. if (this.disableTextureBindingOptimization) {
  16154. return -1;
  16155. }
  16156. // Remove from bound list
  16157. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16158. // Free the slot
  16159. this._boundTexturesCache[currentSlot] = null;
  16160. this._nextFreeTextureSlots.push(currentSlot);
  16161. return currentSlot;
  16162. };
  16163. Engine.prototype._activateCurrentTexture = function () {
  16164. if (this._currentTextureChannel !== this._activeChannel) {
  16165. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16166. this._currentTextureChannel = this._activeChannel;
  16167. }
  16168. };
  16169. /** @hidden */
  16170. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16171. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16172. if (force === void 0) { force = false; }
  16173. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16174. this._activeChannel = texture._designatedSlot;
  16175. }
  16176. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16177. var isTextureForRendering = texture && texture._initialSlot > -1;
  16178. if (currentTextureBound !== texture || force) {
  16179. if (currentTextureBound) {
  16180. this._removeDesignatedSlot(currentTextureBound);
  16181. }
  16182. this._activateCurrentTexture();
  16183. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16184. this._boundTexturesCache[this._activeChannel] = texture;
  16185. if (texture) {
  16186. if (!this.disableTextureBindingOptimization) {
  16187. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16188. if (slotIndex > -1) {
  16189. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16190. }
  16191. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16192. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16193. }
  16194. texture._designatedSlot = this._activeChannel;
  16195. }
  16196. }
  16197. else if (forTextureDataUpdate) {
  16198. this._activateCurrentTexture();
  16199. }
  16200. if (isTextureForRendering && !forTextureDataUpdate) {
  16201. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16202. }
  16203. };
  16204. /** @hidden */
  16205. Engine.prototype._bindTexture = function (channel, texture) {
  16206. if (channel < 0) {
  16207. return;
  16208. }
  16209. if (texture) {
  16210. channel = this._getCorrectTextureChannel(channel, texture);
  16211. }
  16212. this._activeChannel = channel;
  16213. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16214. };
  16215. /**
  16216. * Sets a texture to the webGL context from a postprocess
  16217. * @param channel defines the channel to use
  16218. * @param postProcess defines the source postprocess
  16219. */
  16220. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16221. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16222. };
  16223. /**
  16224. * Binds the output of the passed in post process to the texture channel specified
  16225. * @param channel The channel the texture should be bound to
  16226. * @param postProcess The post process which's output should be bound
  16227. */
  16228. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16229. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16230. };
  16231. /**
  16232. * Unbind all textures from the webGL context
  16233. */
  16234. Engine.prototype.unbindAllTextures = function () {
  16235. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16236. this._activeChannel = channel;
  16237. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16238. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16239. if (this.webGLVersion > 1) {
  16240. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16241. }
  16242. }
  16243. };
  16244. /**
  16245. * Sets a texture to the according uniform.
  16246. * @param channel The texture channel
  16247. * @param uniform The uniform to set
  16248. * @param texture The texture to apply
  16249. */
  16250. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16251. if (channel < 0) {
  16252. return;
  16253. }
  16254. if (uniform) {
  16255. this._boundUniforms[channel] = uniform;
  16256. }
  16257. this._setTexture(channel, texture);
  16258. };
  16259. /**
  16260. * Sets a depth stencil texture from a render target to the according uniform.
  16261. * @param channel The texture channel
  16262. * @param uniform The uniform to set
  16263. * @param texture The render target texture containing the depth stencil texture to apply
  16264. */
  16265. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16266. if (channel < 0) {
  16267. return;
  16268. }
  16269. if (uniform) {
  16270. this._boundUniforms[channel] = uniform;
  16271. }
  16272. if (!texture || !texture.depthStencilTexture) {
  16273. this._setTexture(channel, null);
  16274. }
  16275. else {
  16276. this._setTexture(channel, texture, false, true);
  16277. }
  16278. };
  16279. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16280. var uniform = this._boundUniforms[sourceSlot];
  16281. if (uniform._currentState === destination) {
  16282. return;
  16283. }
  16284. this._gl.uniform1i(uniform, destination);
  16285. uniform._currentState = destination;
  16286. };
  16287. Engine.prototype._getTextureWrapMode = function (mode) {
  16288. switch (mode) {
  16289. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16290. return this._gl.REPEAT;
  16291. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16292. return this._gl.CLAMP_TO_EDGE;
  16293. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16294. return this._gl.MIRRORED_REPEAT;
  16295. }
  16296. return this._gl.REPEAT;
  16297. };
  16298. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16299. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16300. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16301. // Not ready?
  16302. if (!texture) {
  16303. if (this._boundTexturesCache[channel] != null) {
  16304. this._activeChannel = channel;
  16305. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16306. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16307. if (this.webGLVersion > 1) {
  16308. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16309. }
  16310. }
  16311. return false;
  16312. }
  16313. // Video
  16314. if (texture.video) {
  16315. this._activeChannel = channel;
  16316. texture.update();
  16317. }
  16318. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16319. texture.delayLoad();
  16320. return false;
  16321. }
  16322. var internalTexture;
  16323. if (depthStencilTexture) {
  16324. internalTexture = texture.depthStencilTexture;
  16325. }
  16326. else if (texture.isReady()) {
  16327. internalTexture = texture.getInternalTexture();
  16328. }
  16329. else if (texture.isCube) {
  16330. internalTexture = this.emptyCubeTexture;
  16331. }
  16332. else if (texture.is3D) {
  16333. internalTexture = this.emptyTexture3D;
  16334. }
  16335. else {
  16336. internalTexture = this.emptyTexture;
  16337. }
  16338. if (!isPartOfTextureArray) {
  16339. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16340. }
  16341. var needToBind = true;
  16342. if (this._boundTexturesCache[channel] === internalTexture) {
  16343. this._moveBoundTextureOnTop(internalTexture);
  16344. if (!isPartOfTextureArray) {
  16345. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16346. }
  16347. needToBind = false;
  16348. }
  16349. this._activeChannel = channel;
  16350. if (internalTexture && internalTexture.is3D) {
  16351. if (needToBind) {
  16352. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16353. }
  16354. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16355. internalTexture._cachedWrapU = texture.wrapU;
  16356. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16357. }
  16358. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16359. internalTexture._cachedWrapV = texture.wrapV;
  16360. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16361. }
  16362. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16363. internalTexture._cachedWrapR = texture.wrapR;
  16364. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16365. }
  16366. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16367. }
  16368. else if (internalTexture && internalTexture.isCube) {
  16369. if (needToBind) {
  16370. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16371. }
  16372. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16373. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16374. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16375. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16376. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16377. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16378. }
  16379. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16380. }
  16381. else {
  16382. if (needToBind) {
  16383. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16384. }
  16385. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16386. internalTexture._cachedWrapU = texture.wrapU;
  16387. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16388. }
  16389. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16390. internalTexture._cachedWrapV = texture.wrapV;
  16391. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16392. }
  16393. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16394. }
  16395. return true;
  16396. };
  16397. /**
  16398. * Sets an array of texture to the webGL context
  16399. * @param channel defines the channel where the texture array must be set
  16400. * @param uniform defines the associated uniform location
  16401. * @param textures defines the array of textures to bind
  16402. */
  16403. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16404. if (channel < 0 || !uniform) {
  16405. return;
  16406. }
  16407. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16408. this._textureUnits = new Int32Array(textures.length);
  16409. }
  16410. for (var i = 0; i < textures.length; i++) {
  16411. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16412. }
  16413. this._gl.uniform1iv(uniform, this._textureUnits);
  16414. for (var index = 0; index < textures.length; index++) {
  16415. this._setTexture(this._textureUnits[index], textures[index], true);
  16416. }
  16417. };
  16418. /** @hidden */
  16419. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16420. var internalTexture = texture.getInternalTexture();
  16421. if (!internalTexture) {
  16422. return;
  16423. }
  16424. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16425. var value = texture.anisotropicFilteringLevel;
  16426. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16427. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16428. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16429. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16430. }
  16431. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16432. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16433. internalTexture._cachedAnisotropicFilteringLevel = value;
  16434. }
  16435. };
  16436. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16437. this._bindTextureDirectly(target, texture, true, true);
  16438. this._gl.texParameterf(target, parameter, value);
  16439. };
  16440. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16441. if (texture) {
  16442. this._bindTextureDirectly(target, texture, true, true);
  16443. }
  16444. this._gl.texParameteri(target, parameter, value);
  16445. };
  16446. /**
  16447. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16448. * @param x defines the x coordinate of the rectangle where pixels must be read
  16449. * @param y defines the y coordinate of the rectangle where pixels must be read
  16450. * @param width defines the width of the rectangle where pixels must be read
  16451. * @param height defines the height of the rectangle where pixels must be read
  16452. * @returns a Uint8Array containing RGBA colors
  16453. */
  16454. Engine.prototype.readPixels = function (x, y, width, height) {
  16455. var data = new Uint8Array(height * width * 4);
  16456. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16457. return data;
  16458. };
  16459. /**
  16460. * Add an externaly attached data from its key.
  16461. * This method call will fail and return false, if such key already exists.
  16462. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16463. * @param key the unique key that identifies the data
  16464. * @param data the data object to associate to the key for this Engine instance
  16465. * @return true if no such key were already present and the data was added successfully, false otherwise
  16466. */
  16467. Engine.prototype.addExternalData = function (key, data) {
  16468. if (!this._externalData) {
  16469. this._externalData = new BABYLON.StringDictionary();
  16470. }
  16471. return this._externalData.add(key, data);
  16472. };
  16473. /**
  16474. * Get an externaly attached data from its key
  16475. * @param key the unique key that identifies the data
  16476. * @return the associated data, if present (can be null), or undefined if not present
  16477. */
  16478. Engine.prototype.getExternalData = function (key) {
  16479. if (!this._externalData) {
  16480. this._externalData = new BABYLON.StringDictionary();
  16481. }
  16482. return this._externalData.get(key);
  16483. };
  16484. /**
  16485. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16486. * @param key the unique key that identifies the data
  16487. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16488. * @return the associated data, can be null if the factory returned null.
  16489. */
  16490. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16491. if (!this._externalData) {
  16492. this._externalData = new BABYLON.StringDictionary();
  16493. }
  16494. return this._externalData.getOrAddWithFactory(key, factory);
  16495. };
  16496. /**
  16497. * Remove an externaly attached data from the Engine instance
  16498. * @param key the unique key that identifies the data
  16499. * @return true if the data was successfully removed, false if it doesn't exist
  16500. */
  16501. Engine.prototype.removeExternalData = function (key) {
  16502. if (!this._externalData) {
  16503. this._externalData = new BABYLON.StringDictionary();
  16504. }
  16505. return this._externalData.remove(key);
  16506. };
  16507. /**
  16508. * Unbind all vertex attributes from the webGL context
  16509. */
  16510. Engine.prototype.unbindAllAttributes = function () {
  16511. if (this._mustWipeVertexAttributes) {
  16512. this._mustWipeVertexAttributes = false;
  16513. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16514. this._gl.disableVertexAttribArray(i);
  16515. this._vertexAttribArraysEnabled[i] = false;
  16516. this._currentBufferPointers[i].active = false;
  16517. }
  16518. return;
  16519. }
  16520. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16521. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16522. continue;
  16523. }
  16524. this._gl.disableVertexAttribArray(i);
  16525. this._vertexAttribArraysEnabled[i] = false;
  16526. this._currentBufferPointers[i].active = false;
  16527. }
  16528. };
  16529. /**
  16530. * 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
  16531. */
  16532. Engine.prototype.releaseEffects = function () {
  16533. for (var name in this._compiledEffects) {
  16534. this._deleteProgram(this._compiledEffects[name]._program);
  16535. }
  16536. this._compiledEffects = {};
  16537. };
  16538. /**
  16539. * Dispose and release all associated resources
  16540. */
  16541. Engine.prototype.dispose = function () {
  16542. this.hideLoadingUI();
  16543. this.stopRenderLoop();
  16544. // Release postProcesses
  16545. while (this.postProcesses.length) {
  16546. this.postProcesses[0].dispose();
  16547. }
  16548. // Empty texture
  16549. if (this._emptyTexture) {
  16550. this._releaseTexture(this._emptyTexture);
  16551. this._emptyTexture = null;
  16552. }
  16553. if (this._emptyCubeTexture) {
  16554. this._releaseTexture(this._emptyCubeTexture);
  16555. this._emptyCubeTexture = null;
  16556. }
  16557. // Rescale PP
  16558. if (this._rescalePostProcess) {
  16559. this._rescalePostProcess.dispose();
  16560. }
  16561. // Release scenes
  16562. while (this.scenes.length) {
  16563. this.scenes[0].dispose();
  16564. }
  16565. // Release audio engine
  16566. if (Engine.audioEngine) {
  16567. Engine.audioEngine.dispose();
  16568. }
  16569. // Release effects
  16570. this.releaseEffects();
  16571. // Unbind
  16572. this.unbindAllAttributes();
  16573. this._boundUniforms = [];
  16574. if (this._dummyFramebuffer) {
  16575. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16576. }
  16577. //WebVR
  16578. this.disableVR();
  16579. // Events
  16580. if (BABYLON.Tools.IsWindowObjectExist()) {
  16581. window.removeEventListener("blur", this._onBlur);
  16582. window.removeEventListener("focus", this._onFocus);
  16583. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16584. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16585. if (this._renderingCanvas) {
  16586. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16587. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16588. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16589. if (!this._doNotHandleContextLost) {
  16590. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16591. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16592. }
  16593. }
  16594. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16595. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16596. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16597. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16598. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16599. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16600. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16601. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16602. if (this._onVrDisplayConnect) {
  16603. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16604. if (this._onVrDisplayDisconnect) {
  16605. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16606. }
  16607. if (this._onVrDisplayPresentChange) {
  16608. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16609. }
  16610. this._onVrDisplayConnect = null;
  16611. this._onVrDisplayDisconnect = null;
  16612. }
  16613. }
  16614. // Remove from Instances
  16615. var index = Engine.Instances.indexOf(this);
  16616. if (index >= 0) {
  16617. Engine.Instances.splice(index, 1);
  16618. }
  16619. this._workingCanvas = null;
  16620. this._workingContext = null;
  16621. this._currentBufferPointers = [];
  16622. this._renderingCanvas = null;
  16623. this._currentProgram = null;
  16624. this._bindedRenderFunction = null;
  16625. this.onResizeObservable.clear();
  16626. this.onCanvasBlurObservable.clear();
  16627. this.onCanvasFocusObservable.clear();
  16628. this.onCanvasPointerOutObservable.clear();
  16629. this.onBeginFrameObservable.clear();
  16630. this.onEndFrameObservable.clear();
  16631. BABYLON.Effect.ResetCache();
  16632. // Abort active requests
  16633. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16634. var request = _a[_i];
  16635. request.abort();
  16636. }
  16637. };
  16638. // Loading screen
  16639. /**
  16640. * Display the loading screen
  16641. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16642. */
  16643. Engine.prototype.displayLoadingUI = function () {
  16644. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16645. return;
  16646. }
  16647. var loadingScreen = this.loadingScreen;
  16648. if (loadingScreen) {
  16649. loadingScreen.displayLoadingUI();
  16650. }
  16651. };
  16652. /**
  16653. * Hide the loading screen
  16654. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16655. */
  16656. Engine.prototype.hideLoadingUI = function () {
  16657. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16658. return;
  16659. }
  16660. var loadingScreen = this.loadingScreen;
  16661. if (loadingScreen) {
  16662. loadingScreen.hideLoadingUI();
  16663. }
  16664. };
  16665. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16666. /**
  16667. * Gets the current loading screen object
  16668. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16669. */
  16670. get: function () {
  16671. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16672. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16673. return this._loadingScreen;
  16674. },
  16675. /**
  16676. * Sets the current loading screen object
  16677. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16678. */
  16679. set: function (loadingScreen) {
  16680. this._loadingScreen = loadingScreen;
  16681. },
  16682. enumerable: true,
  16683. configurable: true
  16684. });
  16685. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16686. /**
  16687. * Sets the current loading screen text
  16688. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16689. */
  16690. set: function (text) {
  16691. this.loadingScreen.loadingUIText = text;
  16692. },
  16693. enumerable: true,
  16694. configurable: true
  16695. });
  16696. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16697. /**
  16698. * Sets the current loading screen background color
  16699. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16700. */
  16701. set: function (color) {
  16702. this.loadingScreen.loadingUIBackgroundColor = color;
  16703. },
  16704. enumerable: true,
  16705. configurable: true
  16706. });
  16707. /**
  16708. * Attach a new callback raised when context lost event is fired
  16709. * @param callback defines the callback to call
  16710. */
  16711. Engine.prototype.attachContextLostEvent = function (callback) {
  16712. if (this._renderingCanvas) {
  16713. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16714. }
  16715. };
  16716. /**
  16717. * Attach a new callback raised when context restored event is fired
  16718. * @param callback defines the callback to call
  16719. */
  16720. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16721. if (this._renderingCanvas) {
  16722. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16723. }
  16724. };
  16725. /**
  16726. * Gets the source code of the vertex shader associated with a specific webGL program
  16727. * @param program defines the program to use
  16728. * @returns a string containing the source code of the vertex shader associated with the program
  16729. */
  16730. Engine.prototype.getVertexShaderSource = function (program) {
  16731. var shaders = this._gl.getAttachedShaders(program);
  16732. if (!shaders) {
  16733. return null;
  16734. }
  16735. return this._gl.getShaderSource(shaders[0]);
  16736. };
  16737. /**
  16738. * Gets the source code of the fragment shader associated with a specific webGL program
  16739. * @param program defines the program to use
  16740. * @returns a string containing the source code of the fragment shader associated with the program
  16741. */
  16742. Engine.prototype.getFragmentShaderSource = function (program) {
  16743. var shaders = this._gl.getAttachedShaders(program);
  16744. if (!shaders) {
  16745. return null;
  16746. }
  16747. return this._gl.getShaderSource(shaders[1]);
  16748. };
  16749. /**
  16750. * Get the current error code of the webGL context
  16751. * @returns the error code
  16752. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16753. */
  16754. Engine.prototype.getError = function () {
  16755. return this._gl.getError();
  16756. };
  16757. // FPS
  16758. /**
  16759. * Gets the current framerate
  16760. * @returns a number representing the framerate
  16761. */
  16762. Engine.prototype.getFps = function () {
  16763. return this._fps;
  16764. };
  16765. /**
  16766. * Gets the time spent between current and previous frame
  16767. * @returns a number representing the delta time in ms
  16768. */
  16769. Engine.prototype.getDeltaTime = function () {
  16770. return this._deltaTime;
  16771. };
  16772. Engine.prototype._measureFps = function () {
  16773. this._performanceMonitor.sampleFrame();
  16774. this._fps = this._performanceMonitor.averageFPS;
  16775. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16776. };
  16777. /** @hidden */
  16778. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16779. if (faceIndex === void 0) { faceIndex = -1; }
  16780. var gl = this._gl;
  16781. if (!this._dummyFramebuffer) {
  16782. var dummy = gl.createFramebuffer();
  16783. if (!dummy) {
  16784. throw new Error("Unable to create dummy framebuffer");
  16785. }
  16786. this._dummyFramebuffer = dummy;
  16787. }
  16788. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16789. if (faceIndex > -1) {
  16790. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16791. }
  16792. else {
  16793. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16794. }
  16795. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16796. var buffer;
  16797. switch (readType) {
  16798. case gl.UNSIGNED_BYTE:
  16799. buffer = new Uint8Array(4 * width * height);
  16800. readType = gl.UNSIGNED_BYTE;
  16801. break;
  16802. default:
  16803. buffer = new Float32Array(4 * width * height);
  16804. readType = gl.FLOAT;
  16805. break;
  16806. }
  16807. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16808. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16809. return buffer;
  16810. };
  16811. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16812. if (this._webGLVersion > 1) {
  16813. return this._caps.colorBufferFloat;
  16814. }
  16815. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16816. };
  16817. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16818. if (this._webGLVersion > 1) {
  16819. return this._caps.colorBufferFloat;
  16820. }
  16821. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16822. };
  16823. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16824. Engine.prototype._canRenderToFramebuffer = function (type) {
  16825. var gl = this._gl;
  16826. //clear existing errors
  16827. while (gl.getError() !== gl.NO_ERROR) { }
  16828. var successful = true;
  16829. var texture = gl.createTexture();
  16830. gl.bindTexture(gl.TEXTURE_2D, texture);
  16831. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16832. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16833. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16834. var fb = gl.createFramebuffer();
  16835. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16836. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16837. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16838. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16839. successful = successful && (gl.getError() === gl.NO_ERROR);
  16840. //try render by clearing frame buffer's color buffer
  16841. if (successful) {
  16842. gl.clear(gl.COLOR_BUFFER_BIT);
  16843. successful = successful && (gl.getError() === gl.NO_ERROR);
  16844. }
  16845. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16846. if (successful) {
  16847. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16848. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16849. var readFormat = gl.RGBA;
  16850. var readType = gl.UNSIGNED_BYTE;
  16851. var buffer = new Uint8Array(4);
  16852. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16853. successful = successful && (gl.getError() === gl.NO_ERROR);
  16854. }
  16855. //clean up
  16856. gl.deleteTexture(texture);
  16857. gl.deleteFramebuffer(fb);
  16858. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16859. //clear accumulated errors
  16860. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16861. return successful;
  16862. };
  16863. /** @hidden */
  16864. Engine.prototype._getWebGLTextureType = function (type) {
  16865. if (type === Engine.TEXTURETYPE_FLOAT) {
  16866. return this._gl.FLOAT;
  16867. }
  16868. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16869. // Add Half Float Constant.
  16870. return this._gl.HALF_FLOAT_OES;
  16871. }
  16872. return this._gl.UNSIGNED_BYTE;
  16873. };
  16874. ;
  16875. Engine.prototype._getInternalFormat = function (format) {
  16876. var internalFormat = this._gl.RGBA;
  16877. switch (format) {
  16878. case Engine.TEXTUREFORMAT_ALPHA:
  16879. internalFormat = this._gl.ALPHA;
  16880. break;
  16881. case Engine.TEXTUREFORMAT_LUMINANCE:
  16882. internalFormat = this._gl.LUMINANCE;
  16883. break;
  16884. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16885. internalFormat = this._gl.LUMINANCE_ALPHA;
  16886. break;
  16887. case Engine.TEXTUREFORMAT_RGB:
  16888. case Engine.TEXTUREFORMAT_RGB32F:
  16889. internalFormat = this._gl.RGB;
  16890. break;
  16891. case Engine.TEXTUREFORMAT_RGBA:
  16892. case Engine.TEXTUREFORMAT_RGBA32F:
  16893. internalFormat = this._gl.RGBA;
  16894. break;
  16895. case Engine.TEXTUREFORMAT_R32F:
  16896. internalFormat = this._gl.RED;
  16897. break;
  16898. case Engine.TEXTUREFORMAT_RG32F:
  16899. internalFormat = this._gl.RG;
  16900. break;
  16901. }
  16902. return internalFormat;
  16903. };
  16904. /** @hidden */
  16905. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16906. if (this._webGLVersion === 1) {
  16907. if (format) {
  16908. switch (format) {
  16909. case Engine.TEXTUREFORMAT_LUMINANCE:
  16910. return this._gl.LUMINANCE;
  16911. }
  16912. }
  16913. return this._gl.RGBA;
  16914. }
  16915. if (type === Engine.TEXTURETYPE_FLOAT) {
  16916. if (format) {
  16917. switch (format) {
  16918. case Engine.TEXTUREFORMAT_R32F:
  16919. return this._gl.R32F;
  16920. case Engine.TEXTUREFORMAT_RG32F:
  16921. return this._gl.RG32F;
  16922. case Engine.TEXTUREFORMAT_RGB32F:
  16923. return this._gl.RGB32F;
  16924. }
  16925. }
  16926. return this._gl.RGBA32F;
  16927. }
  16928. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16929. return this._gl.RGBA16F;
  16930. }
  16931. if (format) {
  16932. switch (format) {
  16933. case Engine.TEXTUREFORMAT_LUMINANCE:
  16934. return this._gl.LUMINANCE;
  16935. case Engine.TEXTUREFORMAT_RGB:
  16936. return this._gl.RGB;
  16937. }
  16938. }
  16939. return this._gl.RGBA;
  16940. };
  16941. ;
  16942. /** @hidden */
  16943. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16944. if (type === Engine.TEXTURETYPE_FLOAT) {
  16945. return this._gl.RGBA32F;
  16946. }
  16947. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16948. return this._gl.RGBA16F;
  16949. }
  16950. return this._gl.RGBA8;
  16951. };
  16952. ;
  16953. /**
  16954. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16955. * @return the new query
  16956. */
  16957. Engine.prototype.createQuery = function () {
  16958. return this._gl.createQuery();
  16959. };
  16960. /**
  16961. * Delete and release a webGL query
  16962. * @param query defines the query to delete
  16963. * @return the current engine
  16964. */
  16965. Engine.prototype.deleteQuery = function (query) {
  16966. this._gl.deleteQuery(query);
  16967. return this;
  16968. };
  16969. /**
  16970. * Check if a given query has resolved and got its value
  16971. * @param query defines the query to check
  16972. * @returns true if the query got its value
  16973. */
  16974. Engine.prototype.isQueryResultAvailable = function (query) {
  16975. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16976. };
  16977. /**
  16978. * Gets the value of a given query
  16979. * @param query defines the query to check
  16980. * @returns the value of the query
  16981. */
  16982. Engine.prototype.getQueryResult = function (query) {
  16983. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16984. };
  16985. /**
  16986. * Initiates an occlusion query
  16987. * @param algorithmType defines the algorithm to use
  16988. * @param query defines the query to use
  16989. * @returns the current engine
  16990. * @see http://doc.babylonjs.com/features/occlusionquery
  16991. */
  16992. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16993. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16994. this._gl.beginQuery(glAlgorithm, query);
  16995. return this;
  16996. };
  16997. /**
  16998. * Ends an occlusion query
  16999. * @see http://doc.babylonjs.com/features/occlusionquery
  17000. * @param algorithmType defines the algorithm to use
  17001. * @returns the current engine
  17002. */
  17003. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17004. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17005. this._gl.endQuery(glAlgorithm);
  17006. return this;
  17007. };
  17008. /* Time queries */
  17009. Engine.prototype._createTimeQuery = function () {
  17010. var timerQuery = this._caps.timerQuery;
  17011. if (timerQuery.createQueryEXT) {
  17012. return timerQuery.createQueryEXT();
  17013. }
  17014. return this.createQuery();
  17015. };
  17016. Engine.prototype._deleteTimeQuery = function (query) {
  17017. var timerQuery = this._caps.timerQuery;
  17018. if (timerQuery.deleteQueryEXT) {
  17019. timerQuery.deleteQueryEXT(query);
  17020. return;
  17021. }
  17022. this.deleteQuery(query);
  17023. };
  17024. Engine.prototype._getTimeQueryResult = function (query) {
  17025. var timerQuery = this._caps.timerQuery;
  17026. if (timerQuery.getQueryObjectEXT) {
  17027. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17028. }
  17029. return this.getQueryResult(query);
  17030. };
  17031. Engine.prototype._getTimeQueryAvailability = function (query) {
  17032. var timerQuery = this._caps.timerQuery;
  17033. if (timerQuery.getQueryObjectEXT) {
  17034. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17035. }
  17036. return this.isQueryResultAvailable(query);
  17037. };
  17038. /**
  17039. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17040. * Please note that only one query can be issued at a time
  17041. * @returns a time token used to track the time span
  17042. */
  17043. Engine.prototype.startTimeQuery = function () {
  17044. var timerQuery = this._caps.timerQuery;
  17045. if (!timerQuery) {
  17046. return null;
  17047. }
  17048. var token = new BABYLON._TimeToken();
  17049. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17050. if (this._caps.canUseTimestampForTimerQuery) {
  17051. token._startTimeQuery = this._createTimeQuery();
  17052. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17053. }
  17054. else {
  17055. if (this._currentNonTimestampToken) {
  17056. return this._currentNonTimestampToken;
  17057. }
  17058. token._timeElapsedQuery = this._createTimeQuery();
  17059. if (timerQuery.beginQueryEXT) {
  17060. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17061. }
  17062. else {
  17063. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17064. }
  17065. this._currentNonTimestampToken = token;
  17066. }
  17067. return token;
  17068. };
  17069. /**
  17070. * Ends a time query
  17071. * @param token defines the token used to measure the time span
  17072. * @returns the time spent (in ns)
  17073. */
  17074. Engine.prototype.endTimeQuery = function (token) {
  17075. var timerQuery = this._caps.timerQuery;
  17076. if (!timerQuery || !token) {
  17077. return -1;
  17078. }
  17079. if (this._caps.canUseTimestampForTimerQuery) {
  17080. if (!token._startTimeQuery) {
  17081. return -1;
  17082. }
  17083. if (!token._endTimeQuery) {
  17084. token._endTimeQuery = this._createTimeQuery();
  17085. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17086. }
  17087. }
  17088. else if (!token._timeElapsedQueryEnded) {
  17089. if (!token._timeElapsedQuery) {
  17090. return -1;
  17091. }
  17092. if (timerQuery.endQueryEXT) {
  17093. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17094. }
  17095. else {
  17096. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17097. }
  17098. token._timeElapsedQueryEnded = true;
  17099. }
  17100. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17101. var available = false;
  17102. if (token._endTimeQuery) {
  17103. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17104. }
  17105. else if (token._timeElapsedQuery) {
  17106. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17107. }
  17108. if (available && !disjoint) {
  17109. var result = 0;
  17110. if (this._caps.canUseTimestampForTimerQuery) {
  17111. if (!token._startTimeQuery || !token._endTimeQuery) {
  17112. return -1;
  17113. }
  17114. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17115. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17116. result = timeEnd - timeStart;
  17117. this._deleteTimeQuery(token._startTimeQuery);
  17118. this._deleteTimeQuery(token._endTimeQuery);
  17119. token._startTimeQuery = null;
  17120. token._endTimeQuery = null;
  17121. }
  17122. else {
  17123. if (!token._timeElapsedQuery) {
  17124. return -1;
  17125. }
  17126. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17127. this._deleteTimeQuery(token._timeElapsedQuery);
  17128. token._timeElapsedQuery = null;
  17129. token._timeElapsedQueryEnded = false;
  17130. this._currentNonTimestampToken = null;
  17131. }
  17132. return result;
  17133. }
  17134. return -1;
  17135. };
  17136. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17137. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17138. };
  17139. // Transform feedback
  17140. /**
  17141. * Creates a webGL transform feedback object
  17142. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17143. * @returns the webGL transform feedback object
  17144. */
  17145. Engine.prototype.createTransformFeedback = function () {
  17146. return this._gl.createTransformFeedback();
  17147. };
  17148. /**
  17149. * Delete a webGL transform feedback object
  17150. * @param value defines the webGL transform feedback object to delete
  17151. */
  17152. Engine.prototype.deleteTransformFeedback = function (value) {
  17153. this._gl.deleteTransformFeedback(value);
  17154. };
  17155. /**
  17156. * Bind a webGL transform feedback object to the webgl context
  17157. * @param value defines the webGL transform feedback object to bind
  17158. */
  17159. Engine.prototype.bindTransformFeedback = function (value) {
  17160. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17161. };
  17162. /**
  17163. * Begins a transform feedback operation
  17164. * @param usePoints defines if points or triangles must be used
  17165. */
  17166. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17167. if (usePoints === void 0) { usePoints = true; }
  17168. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17169. };
  17170. /**
  17171. * Ends a transform feedback operation
  17172. */
  17173. Engine.prototype.endTransformFeedback = function () {
  17174. this._gl.endTransformFeedback();
  17175. };
  17176. /**
  17177. * Specify the varyings to use with transform feedback
  17178. * @param program defines the associated webGL program
  17179. * @param value defines the list of strings representing the varying names
  17180. */
  17181. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17182. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17183. };
  17184. /**
  17185. * Bind a webGL buffer for a transform feedback operation
  17186. * @param value defines the webGL buffer to bind
  17187. */
  17188. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17189. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17190. };
  17191. /** @hidden */
  17192. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17193. var _this = this;
  17194. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17195. this._activeRequests.push(request);
  17196. request.onCompleteObservable.add(function (request) {
  17197. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17198. });
  17199. return request;
  17200. };
  17201. /** @hidden */
  17202. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17203. var _this = this;
  17204. return new Promise(function (resolve, reject) {
  17205. _this._loadFile(url, function (data) {
  17206. resolve(data);
  17207. }, undefined, database, useArrayBuffer, function (request, exception) {
  17208. reject(exception);
  17209. });
  17210. });
  17211. };
  17212. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17213. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17214. var onload = function (data) {
  17215. loadedFiles[index] = data;
  17216. loadedFiles._internalCount++;
  17217. if (loadedFiles._internalCount === 6) {
  17218. onfinish(loadedFiles);
  17219. }
  17220. };
  17221. var onerror = function (request, exception) {
  17222. if (onErrorCallBack && request) {
  17223. onErrorCallBack(request.status + " " + request.statusText, exception);
  17224. }
  17225. };
  17226. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17227. };
  17228. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17229. if (onError === void 0) { onError = null; }
  17230. var loadedFiles = [];
  17231. loadedFiles._internalCount = 0;
  17232. for (var index = 0; index < 6; index++) {
  17233. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17234. }
  17235. };
  17236. // Statics
  17237. /**
  17238. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17239. * @returns true if the engine can be created
  17240. * @ignorenaming
  17241. */
  17242. Engine.isSupported = function () {
  17243. try {
  17244. var tempcanvas = document.createElement("canvas");
  17245. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17246. return gl != null && !!window.WebGLRenderingContext;
  17247. }
  17248. catch (e) {
  17249. return false;
  17250. }
  17251. };
  17252. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17253. Engine.ExceptionList = [
  17254. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17255. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17256. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17257. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17258. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17259. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17260. ];
  17261. /** Gets the list of created engines */
  17262. Engine.Instances = new Array();
  17263. // Const statics
  17264. Engine._ALPHA_DISABLE = 0;
  17265. Engine._ALPHA_ADD = 1;
  17266. Engine._ALPHA_COMBINE = 2;
  17267. Engine._ALPHA_SUBTRACT = 3;
  17268. Engine._ALPHA_MULTIPLY = 4;
  17269. Engine._ALPHA_MAXIMIZED = 5;
  17270. Engine._ALPHA_ONEONE = 6;
  17271. Engine._ALPHA_PREMULTIPLIED = 7;
  17272. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17273. Engine._ALPHA_INTERPOLATE = 9;
  17274. Engine._ALPHA_SCREENMODE = 10;
  17275. Engine._DELAYLOADSTATE_NONE = 0;
  17276. Engine._DELAYLOADSTATE_LOADED = 1;
  17277. Engine._DELAYLOADSTATE_LOADING = 2;
  17278. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17279. Engine._TEXTUREFORMAT_ALPHA = 0;
  17280. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17281. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17282. Engine._TEXTUREFORMAT_RGB = 4;
  17283. Engine._TEXTUREFORMAT_RGBA = 5;
  17284. Engine._TEXTUREFORMAT_R32F = 6;
  17285. Engine._TEXTUREFORMAT_RG32F = 7;
  17286. Engine._TEXTUREFORMAT_RGB32F = 8;
  17287. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17288. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17289. Engine._TEXTURETYPE_FLOAT = 1;
  17290. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17291. // Depht or Stencil test Constants.
  17292. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17293. Engine._ALWAYS = 0x0207; // 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.
  17294. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17295. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17296. Engine._LEQUAL = 0x0203; // 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.
  17297. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17298. Engine._GEQUAL = 0x0206; // 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.
  17299. Engine._NOTEQUAL = 0x0205; // 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.
  17300. // Stencil Actions Constants.
  17301. Engine._KEEP = 0x1E00;
  17302. Engine._REPLACE = 0x1E01;
  17303. Engine._INCR = 0x1E02;
  17304. Engine._DECR = 0x1E03;
  17305. Engine._INVERT = 0x150A;
  17306. Engine._INCR_WRAP = 0x8507;
  17307. Engine._DECR_WRAP = 0x8508;
  17308. // Texture rescaling mode
  17309. Engine._SCALEMODE_FLOOR = 1;
  17310. Engine._SCALEMODE_NEAREST = 2;
  17311. Engine._SCALEMODE_CEILING = 3;
  17312. // Updatable statics so stick with vars here
  17313. /**
  17314. * Gets or sets the epsilon value used by collision engine
  17315. */
  17316. Engine.CollisionsEpsilon = 0.001;
  17317. /**
  17318. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17319. */
  17320. Engine.CodeRepository = "src/";
  17321. /**
  17322. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17323. */
  17324. Engine.ShadersRepository = "src/Shaders/";
  17325. return Engine;
  17326. }());
  17327. BABYLON.Engine = Engine;
  17328. })(BABYLON || (BABYLON = {}));
  17329. //# sourceMappingURL=babylon.engine.js.map
  17330. var BABYLON;
  17331. (function (BABYLON) {
  17332. /**
  17333. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17334. */
  17335. var Node = /** @class */ (function () {
  17336. /**
  17337. * Creates a new Node
  17338. * @param {string} name - the name and id to be given to this node
  17339. * @param {BABYLON.Scene} the scene this node will be added to
  17340. */
  17341. function Node(name, scene) {
  17342. if (scene === void 0) { scene = null; }
  17343. /**
  17344. * Gets or sets a string used to store user defined state for the node
  17345. */
  17346. this.state = "";
  17347. /**
  17348. * Gets or sets an object used to store user defined information for the node
  17349. */
  17350. this.metadata = null;
  17351. /**
  17352. * Gets or sets a boolean used to define if the node must be serialized
  17353. */
  17354. this.doNotSerialize = false;
  17355. /** @hidden */
  17356. this._isDisposed = false;
  17357. /**
  17358. * Gets a list of Animations associated with the node
  17359. */
  17360. this.animations = new Array();
  17361. this._ranges = {};
  17362. this._isEnabled = true;
  17363. this._isReady = true;
  17364. /** @hidden */
  17365. this._currentRenderId = -1;
  17366. this._parentRenderId = -1;
  17367. this._childRenderId = -1;
  17368. this._animationPropertiesOverride = null;
  17369. /**
  17370. * An event triggered when the mesh is disposed
  17371. */
  17372. this.onDisposeObservable = new BABYLON.Observable();
  17373. // Behaviors
  17374. this._behaviors = new Array();
  17375. this.name = name;
  17376. this.id = name;
  17377. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17378. this.uniqueId = this._scene.getUniqueId();
  17379. this._initCache();
  17380. }
  17381. /**
  17382. * Gets a boolean indicating if the node has been disposed
  17383. * @returns true if the node was disposed
  17384. */
  17385. Node.prototype.isDisposed = function () {
  17386. return this._isDisposed;
  17387. };
  17388. Object.defineProperty(Node.prototype, "parent", {
  17389. get: function () {
  17390. return this._parentNode;
  17391. },
  17392. /**
  17393. * Gets or sets the parent of the node
  17394. */
  17395. set: function (parent) {
  17396. if (this._parentNode === parent) {
  17397. return;
  17398. }
  17399. // Remove self from list of children of parent
  17400. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17401. var index = this._parentNode._children.indexOf(this);
  17402. if (index !== -1) {
  17403. this._parentNode._children.splice(index, 1);
  17404. }
  17405. }
  17406. // Store new parent
  17407. this._parentNode = parent;
  17408. // Add as child to new parent
  17409. if (this._parentNode) {
  17410. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17411. this._parentNode._children = new Array();
  17412. }
  17413. this._parentNode._children.push(this);
  17414. }
  17415. },
  17416. enumerable: true,
  17417. configurable: true
  17418. });
  17419. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17420. /**
  17421. * Gets or sets the animation properties override
  17422. */
  17423. get: function () {
  17424. if (!this._animationPropertiesOverride) {
  17425. return this._scene.animationPropertiesOverride;
  17426. }
  17427. return this._animationPropertiesOverride;
  17428. },
  17429. set: function (value) {
  17430. this._animationPropertiesOverride = value;
  17431. },
  17432. enumerable: true,
  17433. configurable: true
  17434. });
  17435. /**
  17436. * Gets a string idenfifying the name of the class
  17437. * @returns "Node" string
  17438. */
  17439. Node.prototype.getClassName = function () {
  17440. return "Node";
  17441. };
  17442. Object.defineProperty(Node.prototype, "onDispose", {
  17443. /**
  17444. * Sets a callback that will be raised when the node will be disposed
  17445. */
  17446. set: function (callback) {
  17447. if (this._onDisposeObserver) {
  17448. this.onDisposeObservable.remove(this._onDisposeObserver);
  17449. }
  17450. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17451. },
  17452. enumerable: true,
  17453. configurable: true
  17454. });
  17455. /**
  17456. * Gets the scene of the node
  17457. * @returns a {BABYLON.Scene}
  17458. */
  17459. Node.prototype.getScene = function () {
  17460. return this._scene;
  17461. };
  17462. /**
  17463. * Gets the engine of the node
  17464. * @returns a {BABYLON.Engine}
  17465. */
  17466. Node.prototype.getEngine = function () {
  17467. return this._scene.getEngine();
  17468. };
  17469. /**
  17470. * Attach a behavior to the node
  17471. * @see http://doc.babylonjs.com/features/behaviour
  17472. * @param behavior defines the behavior to attach
  17473. * @returns the current Node
  17474. */
  17475. Node.prototype.addBehavior = function (behavior) {
  17476. var _this = this;
  17477. var index = this._behaviors.indexOf(behavior);
  17478. if (index !== -1) {
  17479. return this;
  17480. }
  17481. behavior.init();
  17482. if (this._scene.isLoading) {
  17483. // We defer the attach when the scene will be loaded
  17484. var observer = this._scene.onDataLoadedObservable.add(function () {
  17485. behavior.attach(_this);
  17486. setTimeout(function () {
  17487. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17488. _this._scene.onDataLoadedObservable.remove(observer);
  17489. }, 0);
  17490. });
  17491. }
  17492. else {
  17493. behavior.attach(this);
  17494. }
  17495. this._behaviors.push(behavior);
  17496. return this;
  17497. };
  17498. /**
  17499. * Remove an attached behavior
  17500. * @see http://doc.babylonjs.com/features/behaviour
  17501. * @param behavior defines the behavior to attach
  17502. * @returns the current Node
  17503. */
  17504. Node.prototype.removeBehavior = function (behavior) {
  17505. var index = this._behaviors.indexOf(behavior);
  17506. if (index === -1) {
  17507. return this;
  17508. }
  17509. this._behaviors[index].detach();
  17510. this._behaviors.splice(index, 1);
  17511. return this;
  17512. };
  17513. Object.defineProperty(Node.prototype, "behaviors", {
  17514. /**
  17515. * Gets the list of attached behaviors
  17516. * @see http://doc.babylonjs.com/features/behaviour
  17517. */
  17518. get: function () {
  17519. return this._behaviors;
  17520. },
  17521. enumerable: true,
  17522. configurable: true
  17523. });
  17524. /**
  17525. * Gets an attached behavior by name
  17526. * @param name defines the name of the behavior to look for
  17527. * @see http://doc.babylonjs.com/features/behaviour
  17528. * @returns null if behavior was not found else the requested behavior
  17529. */
  17530. Node.prototype.getBehaviorByName = function (name) {
  17531. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17532. var behavior = _a[_i];
  17533. if (behavior.name === name) {
  17534. return behavior;
  17535. }
  17536. }
  17537. return null;
  17538. };
  17539. /**
  17540. * Returns the world matrix of the node
  17541. * @returns a matrix containing the node's world matrix
  17542. */
  17543. Node.prototype.getWorldMatrix = function () {
  17544. return BABYLON.Matrix.Identity();
  17545. };
  17546. /** @hidden */
  17547. Node.prototype._getWorldMatrixDeterminant = function () {
  17548. return 1;
  17549. };
  17550. // override it in derived class if you add new variables to the cache
  17551. // and call the parent class method
  17552. /** @hidden */
  17553. Node.prototype._initCache = function () {
  17554. this._cache = {};
  17555. this._cache.parent = undefined;
  17556. };
  17557. /** @hidden */
  17558. Node.prototype.updateCache = function (force) {
  17559. if (!force && this.isSynchronized())
  17560. return;
  17561. this._cache.parent = this.parent;
  17562. this._updateCache();
  17563. };
  17564. // override it in derived class if you add new variables to the cache
  17565. // and call the parent class method if !ignoreParentClass
  17566. /** @hidden */
  17567. Node.prototype._updateCache = function (ignoreParentClass) {
  17568. };
  17569. // override it in derived class if you add new variables to the cache
  17570. /** @hidden */
  17571. Node.prototype._isSynchronized = function () {
  17572. return true;
  17573. };
  17574. /** @hidden */
  17575. Node.prototype._markSyncedWithParent = function () {
  17576. if (this.parent) {
  17577. this._parentRenderId = this.parent._childRenderId;
  17578. }
  17579. };
  17580. /** @hidden */
  17581. Node.prototype.isSynchronizedWithParent = function () {
  17582. if (!this.parent) {
  17583. return true;
  17584. }
  17585. if (this._parentRenderId !== this.parent._childRenderId) {
  17586. return false;
  17587. }
  17588. return this.parent.isSynchronized();
  17589. };
  17590. /** @hidden */
  17591. Node.prototype.isSynchronized = function (updateCache) {
  17592. var check = this.hasNewParent();
  17593. check = check || !this.isSynchronizedWithParent();
  17594. check = check || !this._isSynchronized();
  17595. if (updateCache)
  17596. this.updateCache(true);
  17597. return !check;
  17598. };
  17599. /** @hidden */
  17600. Node.prototype.hasNewParent = function (update) {
  17601. if (this._cache.parent === this.parent)
  17602. return false;
  17603. if (update)
  17604. this._cache.parent = this.parent;
  17605. return true;
  17606. };
  17607. /**
  17608. * Is this node ready to be used/rendered
  17609. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17610. * @return true if the node is ready
  17611. */
  17612. Node.prototype.isReady = function (completeCheck) {
  17613. if (completeCheck === void 0) { completeCheck = false; }
  17614. return this._isReady;
  17615. };
  17616. /**
  17617. * Is this node enabled?
  17618. * 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
  17619. * @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
  17620. * @return whether this node (and its parent) is enabled
  17621. */
  17622. Node.prototype.isEnabled = function (checkAncestors) {
  17623. if (checkAncestors === void 0) { checkAncestors = true; }
  17624. if (checkAncestors === false) {
  17625. return this._isEnabled;
  17626. }
  17627. if (this._isEnabled === false) {
  17628. return false;
  17629. }
  17630. if (this.parent !== undefined && this.parent !== null) {
  17631. return this.parent.isEnabled(checkAncestors);
  17632. }
  17633. return true;
  17634. };
  17635. /**
  17636. * Set the enabled state of this node
  17637. * @param value defines the new enabled state
  17638. */
  17639. Node.prototype.setEnabled = function (value) {
  17640. this._isEnabled = value;
  17641. };
  17642. /**
  17643. * Is this node a descendant of the given node?
  17644. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17645. * @param ancestor defines the parent node to inspect
  17646. * @returns a boolean indicating if this node is a descendant of the given node
  17647. */
  17648. Node.prototype.isDescendantOf = function (ancestor) {
  17649. if (this.parent) {
  17650. if (this.parent === ancestor) {
  17651. return true;
  17652. }
  17653. return this.parent.isDescendantOf(ancestor);
  17654. }
  17655. return false;
  17656. };
  17657. /** @hidden */
  17658. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17659. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17660. if (!this._children) {
  17661. return;
  17662. }
  17663. for (var index = 0; index < this._children.length; index++) {
  17664. var item = this._children[index];
  17665. if (!predicate || predicate(item)) {
  17666. results.push(item);
  17667. }
  17668. if (!directDescendantsOnly) {
  17669. item._getDescendants(results, false, predicate);
  17670. }
  17671. }
  17672. };
  17673. /**
  17674. * Will return all nodes that have this node as ascendant
  17675. * @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
  17676. * @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
  17677. * @return all children nodes of all types
  17678. */
  17679. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17680. var results = new Array();
  17681. this._getDescendants(results, directDescendantsOnly, predicate);
  17682. return results;
  17683. };
  17684. /**
  17685. * Get all child-meshes of this node
  17686. * @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
  17687. * @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
  17688. * @returns an array of {BABYLON.AbstractMesh}
  17689. */
  17690. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17691. var results = [];
  17692. this._getDescendants(results, directDescendantsOnly, function (node) {
  17693. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17694. });
  17695. return results;
  17696. };
  17697. /**
  17698. * Get all child-transformNodes of this node
  17699. * @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
  17700. * @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
  17701. * @returns an array of {BABYLON.TransformNode}
  17702. */
  17703. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17704. var results = [];
  17705. this._getDescendants(results, directDescendantsOnly, function (node) {
  17706. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17707. });
  17708. return results;
  17709. };
  17710. /**
  17711. * Get all direct children of this node
  17712. * @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
  17713. * @returns an array of {BABYLON.Node}
  17714. */
  17715. Node.prototype.getChildren = function (predicate) {
  17716. return this.getDescendants(true, predicate);
  17717. };
  17718. /** @hidden */
  17719. Node.prototype._setReady = function (state) {
  17720. if (state === this._isReady) {
  17721. return;
  17722. }
  17723. if (!state) {
  17724. this._isReady = false;
  17725. return;
  17726. }
  17727. if (this.onReady) {
  17728. this.onReady(this);
  17729. }
  17730. this._isReady = true;
  17731. };
  17732. /**
  17733. * Get an animation by name
  17734. * @param name defines the name of the animation to look for
  17735. * @returns null if not found else the requested animation
  17736. */
  17737. Node.prototype.getAnimationByName = function (name) {
  17738. for (var i = 0; i < this.animations.length; i++) {
  17739. var animation = this.animations[i];
  17740. if (animation.name === name) {
  17741. return animation;
  17742. }
  17743. }
  17744. return null;
  17745. };
  17746. /**
  17747. * Creates an animation range for this node
  17748. * @param name defines the name of the range
  17749. * @param from defines the starting key
  17750. * @param to defines the end key
  17751. */
  17752. Node.prototype.createAnimationRange = function (name, from, to) {
  17753. // check name not already in use
  17754. if (!this._ranges[name]) {
  17755. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17756. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17757. if (this.animations[i]) {
  17758. this.animations[i].createRange(name, from, to);
  17759. }
  17760. }
  17761. }
  17762. };
  17763. /**
  17764. * Delete a specific animation range
  17765. * @param name defines the name of the range to delete
  17766. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17767. */
  17768. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17769. if (deleteFrames === void 0) { deleteFrames = true; }
  17770. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17771. if (this.animations[i]) {
  17772. this.animations[i].deleteRange(name, deleteFrames);
  17773. }
  17774. }
  17775. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17776. };
  17777. /**
  17778. * Get an animation range by name
  17779. * @param name defines the name of the animation range to look for
  17780. * @returns null if not found else the requested animation range
  17781. */
  17782. Node.prototype.getAnimationRange = function (name) {
  17783. return this._ranges[name];
  17784. };
  17785. /**
  17786. * Will start the animation sequence
  17787. * @param name defines the range frames for animation sequence
  17788. * @param loop defines if the animation should loop (false by default)
  17789. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17790. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17791. * @returns the object created for this animation. If range does not exist, it will return null
  17792. */
  17793. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17794. var range = this.getAnimationRange(name);
  17795. if (!range) {
  17796. return null;
  17797. }
  17798. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17799. };
  17800. /**
  17801. * Serialize animation ranges into a JSON compatible object
  17802. * @returns serialization object
  17803. */
  17804. Node.prototype.serializeAnimationRanges = function () {
  17805. var serializationRanges = [];
  17806. for (var name in this._ranges) {
  17807. var localRange = this._ranges[name];
  17808. if (!localRange) {
  17809. continue;
  17810. }
  17811. var range = {};
  17812. range.name = name;
  17813. range.from = localRange.from;
  17814. range.to = localRange.to;
  17815. serializationRanges.push(range);
  17816. }
  17817. return serializationRanges;
  17818. };
  17819. /**
  17820. * Computes the world matrix of the node
  17821. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17822. * @returns the world matrix
  17823. */
  17824. Node.prototype.computeWorldMatrix = function (force) {
  17825. return BABYLON.Matrix.Identity();
  17826. };
  17827. /**
  17828. * Releases resources associated with this node.
  17829. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17830. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17831. */
  17832. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17833. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17834. if (!doNotRecurse) {
  17835. var nodes = this.getDescendants(true);
  17836. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17837. var node = nodes_1[_i];
  17838. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17839. }
  17840. }
  17841. else {
  17842. var transformNodes = this.getChildTransformNodes(true);
  17843. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17844. var transformNode = transformNodes_1[_a];
  17845. transformNode.parent = null;
  17846. transformNode.computeWorldMatrix(true);
  17847. }
  17848. }
  17849. this.parent = null;
  17850. // Callback
  17851. this.onDisposeObservable.notifyObservers(this);
  17852. this.onDisposeObservable.clear();
  17853. // Behaviors
  17854. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17855. var behavior = _c[_b];
  17856. behavior.detach();
  17857. }
  17858. this._behaviors = [];
  17859. this._isDisposed = true;
  17860. };
  17861. /**
  17862. * Parse animation range data from a serialization object and store them into a given node
  17863. * @param node defines where to store the animation ranges
  17864. * @param parsedNode defines the serialization object to read data from
  17865. * @param scene defines the hosting scene
  17866. */
  17867. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17868. if (parsedNode.ranges) {
  17869. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17870. var data = parsedNode.ranges[index];
  17871. node.createAnimationRange(data.name, data.from, data.to);
  17872. }
  17873. }
  17874. };
  17875. __decorate([
  17876. BABYLON.serialize()
  17877. ], Node.prototype, "name", void 0);
  17878. __decorate([
  17879. BABYLON.serialize()
  17880. ], Node.prototype, "id", void 0);
  17881. __decorate([
  17882. BABYLON.serialize()
  17883. ], Node.prototype, "uniqueId", void 0);
  17884. __decorate([
  17885. BABYLON.serialize()
  17886. ], Node.prototype, "state", void 0);
  17887. __decorate([
  17888. BABYLON.serialize()
  17889. ], Node.prototype, "metadata", void 0);
  17890. return Node;
  17891. }());
  17892. BABYLON.Node = Node;
  17893. })(BABYLON || (BABYLON = {}));
  17894. //# sourceMappingURL=babylon.node.js.map
  17895. var BABYLON;
  17896. (function (BABYLON) {
  17897. var BoundingSphere = /** @class */ (function () {
  17898. /**
  17899. * Creates a new bounding sphere
  17900. * @param min defines the minimum vector (in local space)
  17901. * @param max defines the maximum vector (in local space)
  17902. */
  17903. function BoundingSphere(min, max) {
  17904. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17905. this.reConstruct(min, max);
  17906. }
  17907. /**
  17908. * Recreates the entire bounding sphere from scratch
  17909. * @param min defines the new minimum vector (in local space)
  17910. * @param max defines the new maximum vector (in local space)
  17911. */
  17912. BoundingSphere.prototype.reConstruct = function (min, max) {
  17913. this.minimum = min.clone();
  17914. this.maximum = max.clone();
  17915. var distance = BABYLON.Vector3.Distance(min, max);
  17916. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17917. this.radius = distance * 0.5;
  17918. this.centerWorld = BABYLON.Vector3.Zero();
  17919. this._update(BABYLON.Matrix.Identity());
  17920. };
  17921. // Methods
  17922. BoundingSphere.prototype._update = function (world) {
  17923. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17924. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17925. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17926. };
  17927. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17928. for (var i = 0; i < 6; i++) {
  17929. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17930. return false;
  17931. }
  17932. return true;
  17933. };
  17934. BoundingSphere.prototype.intersectsPoint = function (point) {
  17935. var x = this.centerWorld.x - point.x;
  17936. var y = this.centerWorld.y - point.y;
  17937. var z = this.centerWorld.z - point.z;
  17938. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17939. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17940. return false;
  17941. return true;
  17942. };
  17943. // Statics
  17944. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17945. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17946. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17947. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17948. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17949. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17950. return false;
  17951. return true;
  17952. };
  17953. return BoundingSphere;
  17954. }());
  17955. BABYLON.BoundingSphere = BoundingSphere;
  17956. })(BABYLON || (BABYLON = {}));
  17957. //# sourceMappingURL=babylon.boundingSphere.js.map
  17958. var BABYLON;
  17959. (function (BABYLON) {
  17960. var BoundingBox = /** @class */ (function () {
  17961. /**
  17962. * Creates a new bounding box
  17963. * @param min defines the minimum vector (in local space)
  17964. * @param max defines the maximum vector (in local space)
  17965. */
  17966. function BoundingBox(min, max) {
  17967. this.vectorsWorld = new Array();
  17968. this.reConstruct(min, max);
  17969. }
  17970. // Methods
  17971. /**
  17972. * Recreates the entire bounding box from scratch
  17973. * @param min defines the new minimum vector (in local space)
  17974. * @param max defines the new maximum vector (in local space)
  17975. */
  17976. BoundingBox.prototype.reConstruct = function (min, max) {
  17977. this.minimum = min.clone();
  17978. this.maximum = max.clone();
  17979. // Bounding vectors
  17980. this.vectors = new Array();
  17981. this.vectors.push(this.minimum.clone());
  17982. this.vectors.push(this.maximum.clone());
  17983. this.vectors.push(this.minimum.clone());
  17984. this.vectors[2].x = this.maximum.x;
  17985. this.vectors.push(this.minimum.clone());
  17986. this.vectors[3].y = this.maximum.y;
  17987. this.vectors.push(this.minimum.clone());
  17988. this.vectors[4].z = this.maximum.z;
  17989. this.vectors.push(this.maximum.clone());
  17990. this.vectors[5].z = this.minimum.z;
  17991. this.vectors.push(this.maximum.clone());
  17992. this.vectors[6].x = this.minimum.x;
  17993. this.vectors.push(this.maximum.clone());
  17994. this.vectors[7].y = this.minimum.y;
  17995. // OBB
  17996. this.center = this.maximum.add(this.minimum).scale(0.5);
  17997. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17998. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17999. // World
  18000. for (var index = 0; index < this.vectors.length; index++) {
  18001. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18002. }
  18003. this.minimumWorld = BABYLON.Vector3.Zero();
  18004. this.maximumWorld = BABYLON.Vector3.Zero();
  18005. this.centerWorld = BABYLON.Vector3.Zero();
  18006. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18007. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18008. };
  18009. BoundingBox.prototype.getWorldMatrix = function () {
  18010. return this._worldMatrix;
  18011. };
  18012. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18013. this._worldMatrix.copyFrom(matrix);
  18014. return this;
  18015. };
  18016. BoundingBox.prototype._update = function (world) {
  18017. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18018. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18019. for (var index = 0; index < this.vectors.length; index++) {
  18020. var v = this.vectorsWorld[index];
  18021. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18022. if (v.x < this.minimumWorld.x)
  18023. this.minimumWorld.x = v.x;
  18024. if (v.y < this.minimumWorld.y)
  18025. this.minimumWorld.y = v.y;
  18026. if (v.z < this.minimumWorld.z)
  18027. this.minimumWorld.z = v.z;
  18028. if (v.x > this.maximumWorld.x)
  18029. this.maximumWorld.x = v.x;
  18030. if (v.y > this.maximumWorld.y)
  18031. this.maximumWorld.y = v.y;
  18032. if (v.z > this.maximumWorld.z)
  18033. this.maximumWorld.z = v.z;
  18034. }
  18035. // Extend
  18036. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18037. this.extendSizeWorld.scaleInPlace(0.5);
  18038. // OBB
  18039. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18040. this.centerWorld.scaleInPlace(0.5);
  18041. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18042. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18043. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18044. this._worldMatrix = world;
  18045. };
  18046. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18047. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18048. };
  18049. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18050. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18051. };
  18052. BoundingBox.prototype.intersectsPoint = function (point) {
  18053. var delta = -BABYLON.Epsilon;
  18054. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18055. return false;
  18056. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18057. return false;
  18058. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18059. return false;
  18060. return true;
  18061. };
  18062. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18063. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18064. };
  18065. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18066. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18067. return false;
  18068. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18069. return false;
  18070. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18071. return false;
  18072. return true;
  18073. };
  18074. // Statics
  18075. BoundingBox.Intersects = function (box0, box1) {
  18076. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18077. return false;
  18078. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18079. return false;
  18080. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18081. return false;
  18082. return true;
  18083. };
  18084. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18085. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18086. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18087. return (num <= (sphereRadius * sphereRadius));
  18088. };
  18089. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18090. for (var p = 0; p < 6; p++) {
  18091. for (var i = 0; i < 8; i++) {
  18092. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18093. return false;
  18094. }
  18095. }
  18096. }
  18097. return true;
  18098. };
  18099. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18100. for (var p = 0; p < 6; p++) {
  18101. var inCount = 8;
  18102. for (var i = 0; i < 8; i++) {
  18103. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18104. --inCount;
  18105. }
  18106. else {
  18107. break;
  18108. }
  18109. }
  18110. if (inCount === 0)
  18111. return false;
  18112. }
  18113. return true;
  18114. };
  18115. return BoundingBox;
  18116. }());
  18117. BABYLON.BoundingBox = BoundingBox;
  18118. })(BABYLON || (BABYLON = {}));
  18119. //# sourceMappingURL=babylon.boundingBox.js.map
  18120. var BABYLON;
  18121. (function (BABYLON) {
  18122. var computeBoxExtents = function (axis, box) {
  18123. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18124. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18125. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18126. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18127. var r = r0 + r1 + r2;
  18128. return {
  18129. min: p - r,
  18130. max: p + r
  18131. };
  18132. };
  18133. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18134. var axisOverlap = function (axis, box0, box1) {
  18135. var result0 = computeBoxExtents(axis, box0);
  18136. var result1 = computeBoxExtents(axis, box1);
  18137. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18138. };
  18139. var BoundingInfo = /** @class */ (function () {
  18140. function BoundingInfo(minimum, maximum) {
  18141. this.minimum = minimum;
  18142. this.maximum = maximum;
  18143. this._isLocked = false;
  18144. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18145. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18146. }
  18147. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18148. get: function () {
  18149. return this._isLocked;
  18150. },
  18151. set: function (value) {
  18152. this._isLocked = value;
  18153. },
  18154. enumerable: true,
  18155. configurable: true
  18156. });
  18157. // Methods
  18158. BoundingInfo.prototype.update = function (world) {
  18159. if (this._isLocked) {
  18160. return;
  18161. }
  18162. this.boundingBox._update(world);
  18163. this.boundingSphere._update(world);
  18164. };
  18165. /**
  18166. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18167. * @param center New center of the bounding info
  18168. * @param extend New extend of the bounding info
  18169. */
  18170. BoundingInfo.prototype.centerOn = function (center, extend) {
  18171. this.minimum = center.subtract(extend);
  18172. this.maximum = center.add(extend);
  18173. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18174. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18175. return this;
  18176. };
  18177. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18178. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18179. return false;
  18180. return this.boundingBox.isInFrustum(frustumPlanes);
  18181. };
  18182. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18183. /**
  18184. * Gets the world distance between the min and max points of the bounding box
  18185. */
  18186. get: function () {
  18187. var boundingBox = this.boundingBox;
  18188. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18189. return size.length();
  18190. },
  18191. enumerable: true,
  18192. configurable: true
  18193. });
  18194. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18195. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18196. };
  18197. BoundingInfo.prototype._checkCollision = function (collider) {
  18198. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18199. };
  18200. BoundingInfo.prototype.intersectsPoint = function (point) {
  18201. if (!this.boundingSphere.centerWorld) {
  18202. return false;
  18203. }
  18204. if (!this.boundingSphere.intersectsPoint(point)) {
  18205. return false;
  18206. }
  18207. if (!this.boundingBox.intersectsPoint(point)) {
  18208. return false;
  18209. }
  18210. return true;
  18211. };
  18212. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18213. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18214. return false;
  18215. }
  18216. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18217. return false;
  18218. }
  18219. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18220. return false;
  18221. }
  18222. if (!precise) {
  18223. return true;
  18224. }
  18225. var box0 = this.boundingBox;
  18226. var box1 = boundingInfo.boundingBox;
  18227. if (!axisOverlap(box0.directions[0], box0, box1))
  18228. return false;
  18229. if (!axisOverlap(box0.directions[1], box0, box1))
  18230. return false;
  18231. if (!axisOverlap(box0.directions[2], box0, box1))
  18232. return false;
  18233. if (!axisOverlap(box1.directions[0], box0, box1))
  18234. return false;
  18235. if (!axisOverlap(box1.directions[1], box0, box1))
  18236. return false;
  18237. if (!axisOverlap(box1.directions[2], box0, box1))
  18238. return false;
  18239. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18240. return false;
  18241. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18242. return false;
  18243. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18244. return false;
  18245. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18246. return false;
  18247. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18248. return false;
  18249. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18250. return false;
  18251. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18252. return false;
  18253. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18254. return false;
  18255. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18256. return false;
  18257. return true;
  18258. };
  18259. return BoundingInfo;
  18260. }());
  18261. BABYLON.BoundingInfo = BoundingInfo;
  18262. })(BABYLON || (BABYLON = {}));
  18263. //# sourceMappingURL=babylon.boundingInfo.js.map
  18264. var BABYLON;
  18265. (function (BABYLON) {
  18266. var TransformNode = /** @class */ (function (_super) {
  18267. __extends(TransformNode, _super);
  18268. function TransformNode(name, scene, isPure) {
  18269. if (scene === void 0) { scene = null; }
  18270. if (isPure === void 0) { isPure = true; }
  18271. var _this = _super.call(this, name, scene) || this;
  18272. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18273. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18274. _this._up = new BABYLON.Vector3(0, 1, 0);
  18275. _this._right = new BABYLON.Vector3(1, 0, 0);
  18276. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18277. // Properties
  18278. _this._rotation = BABYLON.Vector3.Zero();
  18279. _this._scaling = BABYLON.Vector3.One();
  18280. _this._isDirty = false;
  18281. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18282. _this.scalingDeterminant = 1;
  18283. _this.infiniteDistance = false;
  18284. _this.position = BABYLON.Vector3.Zero();
  18285. _this._localWorld = BABYLON.Matrix.Zero();
  18286. _this._worldMatrix = BABYLON.Matrix.Zero();
  18287. _this._worldMatrixDeterminant = 0;
  18288. _this._absolutePosition = BABYLON.Vector3.Zero();
  18289. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18290. _this._postMultiplyPivotMatrix = false;
  18291. _this._isWorldMatrixFrozen = false;
  18292. /**
  18293. * An event triggered after the world matrix is updated
  18294. */
  18295. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18296. _this._nonUniformScaling = false;
  18297. if (isPure) {
  18298. _this.getScene().addTransformNode(_this);
  18299. }
  18300. return _this;
  18301. }
  18302. /**
  18303. * Gets a string idenfifying the name of the class
  18304. * @returns "TransformNode" string
  18305. */
  18306. TransformNode.prototype.getClassName = function () {
  18307. return "TransformNode";
  18308. };
  18309. Object.defineProperty(TransformNode.prototype, "rotation", {
  18310. /**
  18311. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18312. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18313. * Default : (0.0, 0.0, 0.0)
  18314. */
  18315. get: function () {
  18316. return this._rotation;
  18317. },
  18318. set: function (newRotation) {
  18319. this._rotation = newRotation;
  18320. },
  18321. enumerable: true,
  18322. configurable: true
  18323. });
  18324. Object.defineProperty(TransformNode.prototype, "scaling", {
  18325. /**
  18326. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18327. * Default : (1.0, 1.0, 1.0)
  18328. */
  18329. get: function () {
  18330. return this._scaling;
  18331. },
  18332. /**
  18333. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18334. * Default : (1.0, 1.0, 1.0)
  18335. */
  18336. set: function (newScaling) {
  18337. this._scaling = newScaling;
  18338. },
  18339. enumerable: true,
  18340. configurable: true
  18341. });
  18342. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18343. /**
  18344. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18345. * It's null by default.
  18346. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18347. */
  18348. get: function () {
  18349. return this._rotationQuaternion;
  18350. },
  18351. set: function (quaternion) {
  18352. this._rotationQuaternion = quaternion;
  18353. //reset the rotation vector.
  18354. if (quaternion && this.rotation.length()) {
  18355. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18356. }
  18357. },
  18358. enumerable: true,
  18359. configurable: true
  18360. });
  18361. Object.defineProperty(TransformNode.prototype, "forward", {
  18362. /**
  18363. * The forward direction of that transform in world space.
  18364. */
  18365. get: function () {
  18366. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18367. },
  18368. enumerable: true,
  18369. configurable: true
  18370. });
  18371. Object.defineProperty(TransformNode.prototype, "up", {
  18372. /**
  18373. * The up direction of that transform in world space.
  18374. */
  18375. get: function () {
  18376. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18377. },
  18378. enumerable: true,
  18379. configurable: true
  18380. });
  18381. Object.defineProperty(TransformNode.prototype, "right", {
  18382. /**
  18383. * The right direction of that transform in world space.
  18384. */
  18385. get: function () {
  18386. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18387. },
  18388. enumerable: true,
  18389. configurable: true
  18390. });
  18391. /**
  18392. * Returns the latest update of the World matrix
  18393. * Returns a Matrix.
  18394. */
  18395. TransformNode.prototype.getWorldMatrix = function () {
  18396. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18397. this.computeWorldMatrix();
  18398. }
  18399. return this._worldMatrix;
  18400. };
  18401. /** @hidden */
  18402. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18403. return this._worldMatrixDeterminant;
  18404. };
  18405. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18406. /**
  18407. * Returns directly the latest state of the mesh World matrix.
  18408. * A Matrix is returned.
  18409. */
  18410. get: function () {
  18411. return this._worldMatrix;
  18412. },
  18413. enumerable: true,
  18414. configurable: true
  18415. });
  18416. /**
  18417. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18418. * Returns the TransformNode.
  18419. */
  18420. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18421. this._poseMatrix.copyFrom(matrix);
  18422. return this;
  18423. };
  18424. /**
  18425. * Returns the mesh Pose matrix.
  18426. * Returned object : Matrix
  18427. */
  18428. TransformNode.prototype.getPoseMatrix = function () {
  18429. return this._poseMatrix;
  18430. };
  18431. TransformNode.prototype._isSynchronized = function () {
  18432. if (this._isDirty) {
  18433. return false;
  18434. }
  18435. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18436. return false;
  18437. if (this._cache.pivotMatrixUpdated) {
  18438. return false;
  18439. }
  18440. if (this.infiniteDistance) {
  18441. return false;
  18442. }
  18443. if (!this._cache.position.equals(this.position))
  18444. return false;
  18445. if (this.rotationQuaternion) {
  18446. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18447. return false;
  18448. }
  18449. if (!this._cache.rotation.equals(this.rotation))
  18450. return false;
  18451. if (!this._cache.scaling.equals(this.scaling))
  18452. return false;
  18453. return true;
  18454. };
  18455. TransformNode.prototype._initCache = function () {
  18456. _super.prototype._initCache.call(this);
  18457. this._cache.localMatrixUpdated = false;
  18458. this._cache.position = BABYLON.Vector3.Zero();
  18459. this._cache.scaling = BABYLON.Vector3.Zero();
  18460. this._cache.rotation = BABYLON.Vector3.Zero();
  18461. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18462. this._cache.billboardMode = -1;
  18463. };
  18464. TransformNode.prototype.markAsDirty = function (property) {
  18465. if (property === "rotation") {
  18466. this.rotationQuaternion = null;
  18467. }
  18468. this._currentRenderId = Number.MAX_VALUE;
  18469. this._isDirty = true;
  18470. return this;
  18471. };
  18472. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18473. /**
  18474. * Returns the current mesh absolute position.
  18475. * Retuns a Vector3.
  18476. */
  18477. get: function () {
  18478. return this._absolutePosition;
  18479. },
  18480. enumerable: true,
  18481. configurable: true
  18482. });
  18483. /**
  18484. * Sets a new matrix to apply before all other transformation
  18485. * @param matrix defines the transform matrix
  18486. * @returns the current TransformNode
  18487. */
  18488. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18489. return this.setPivotMatrix(matrix, false);
  18490. };
  18491. /**
  18492. * Sets a new pivot matrix to the current node
  18493. * @param matrix defines the new pivot matrix to use
  18494. * @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
  18495. * @returns the current TransformNode
  18496. */
  18497. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18498. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18499. this._pivotMatrix = matrix.clone();
  18500. this._cache.pivotMatrixUpdated = true;
  18501. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18502. if (this._postMultiplyPivotMatrix) {
  18503. if (!this._pivotMatrixInverse) {
  18504. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18505. }
  18506. else {
  18507. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18508. }
  18509. }
  18510. return this;
  18511. };
  18512. /**
  18513. * Returns the mesh pivot matrix.
  18514. * Default : Identity.
  18515. * A Matrix is returned.
  18516. */
  18517. TransformNode.prototype.getPivotMatrix = function () {
  18518. return this._pivotMatrix;
  18519. };
  18520. /**
  18521. * Prevents the World matrix to be computed any longer.
  18522. * Returns the TransformNode.
  18523. */
  18524. TransformNode.prototype.freezeWorldMatrix = function () {
  18525. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18526. this.computeWorldMatrix(true);
  18527. this._isWorldMatrixFrozen = true;
  18528. return this;
  18529. };
  18530. /**
  18531. * Allows back the World matrix computation.
  18532. * Returns the TransformNode.
  18533. */
  18534. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18535. this._isWorldMatrixFrozen = false;
  18536. this.computeWorldMatrix(true);
  18537. return this;
  18538. };
  18539. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18540. /**
  18541. * True if the World matrix has been frozen.
  18542. * Returns a boolean.
  18543. */
  18544. get: function () {
  18545. return this._isWorldMatrixFrozen;
  18546. },
  18547. enumerable: true,
  18548. configurable: true
  18549. });
  18550. /**
  18551. * Retuns the mesh absolute position in the World.
  18552. * Returns a Vector3.
  18553. */
  18554. TransformNode.prototype.getAbsolutePosition = function () {
  18555. this.computeWorldMatrix();
  18556. return this._absolutePosition;
  18557. };
  18558. /**
  18559. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18560. * Returns the TransformNode.
  18561. */
  18562. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18563. if (!absolutePosition) {
  18564. return this;
  18565. }
  18566. var absolutePositionX;
  18567. var absolutePositionY;
  18568. var absolutePositionZ;
  18569. if (absolutePosition.x === undefined) {
  18570. if (arguments.length < 3) {
  18571. return this;
  18572. }
  18573. absolutePositionX = arguments[0];
  18574. absolutePositionY = arguments[1];
  18575. absolutePositionZ = arguments[2];
  18576. }
  18577. else {
  18578. absolutePositionX = absolutePosition.x;
  18579. absolutePositionY = absolutePosition.y;
  18580. absolutePositionZ = absolutePosition.z;
  18581. }
  18582. if (this.parent) {
  18583. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18584. invertParentWorldMatrix.invert();
  18585. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18586. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18587. }
  18588. else {
  18589. this.position.x = absolutePositionX;
  18590. this.position.y = absolutePositionY;
  18591. this.position.z = absolutePositionZ;
  18592. }
  18593. return this;
  18594. };
  18595. /**
  18596. * Sets the mesh position in its local space.
  18597. * Returns the TransformNode.
  18598. */
  18599. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18600. this.computeWorldMatrix();
  18601. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18602. return this;
  18603. };
  18604. /**
  18605. * Returns the mesh position in the local space from the current World matrix values.
  18606. * Returns a new Vector3.
  18607. */
  18608. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18609. this.computeWorldMatrix();
  18610. var invLocalWorldMatrix = this._localWorld.clone();
  18611. invLocalWorldMatrix.invert();
  18612. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18613. };
  18614. /**
  18615. * Translates the mesh along the passed Vector3 in its local space.
  18616. * Returns the TransformNode.
  18617. */
  18618. TransformNode.prototype.locallyTranslate = function (vector3) {
  18619. this.computeWorldMatrix(true);
  18620. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18621. return this;
  18622. };
  18623. /**
  18624. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18625. * @param targetPoint the position (must be in same space as current mesh) to look at
  18626. * @param yawCor optional yaw (y-axis) correction in radians
  18627. * @param pitchCor optional pitch (x-axis) correction in radians
  18628. * @param rollCor optional roll (z-axis) correction in radians
  18629. * @param space the choosen space of the target
  18630. * @returns the TransformNode.
  18631. */
  18632. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18633. if (yawCor === void 0) { yawCor = 0; }
  18634. if (pitchCor === void 0) { pitchCor = 0; }
  18635. if (rollCor === void 0) { rollCor = 0; }
  18636. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18637. var dv = TransformNode._lookAtVectorCache;
  18638. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18639. targetPoint.subtractToRef(pos, dv);
  18640. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18641. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18642. var pitch = Math.atan2(dv.y, len);
  18643. if (this.rotationQuaternion) {
  18644. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18645. }
  18646. else {
  18647. this.rotation.x = pitch + pitchCor;
  18648. this.rotation.y = yaw + yawCor;
  18649. this.rotation.z = rollCor;
  18650. }
  18651. return this;
  18652. };
  18653. /**
  18654. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18655. * This Vector3 is expressed in the World space.
  18656. */
  18657. TransformNode.prototype.getDirection = function (localAxis) {
  18658. var result = BABYLON.Vector3.Zero();
  18659. this.getDirectionToRef(localAxis, result);
  18660. return result;
  18661. };
  18662. /**
  18663. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18664. * localAxis is expressed in the mesh local space.
  18665. * result is computed in the Wordl space from the mesh World matrix.
  18666. * Returns the TransformNode.
  18667. */
  18668. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18669. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18670. return this;
  18671. };
  18672. /**
  18673. * Sets a new pivot point to the current node
  18674. * @param point defines the new pivot point to use
  18675. * @param space defines if the point is in world or local space (local by default)
  18676. * @returns the current TransformNode
  18677. */
  18678. TransformNode.prototype.setPivotPoint = function (point, space) {
  18679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18680. if (this.getScene().getRenderId() == 0) {
  18681. this.computeWorldMatrix(true);
  18682. }
  18683. var wm = this.getWorldMatrix();
  18684. if (space == BABYLON.Space.WORLD) {
  18685. var tmat = BABYLON.Tmp.Matrix[0];
  18686. wm.invertToRef(tmat);
  18687. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18688. }
  18689. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18690. };
  18691. /**
  18692. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18693. */
  18694. TransformNode.prototype.getPivotPoint = function () {
  18695. var point = BABYLON.Vector3.Zero();
  18696. this.getPivotPointToRef(point);
  18697. return point;
  18698. };
  18699. /**
  18700. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18701. * Returns the TransformNode.
  18702. */
  18703. TransformNode.prototype.getPivotPointToRef = function (result) {
  18704. result.x = -this._pivotMatrix.m[12];
  18705. result.y = -this._pivotMatrix.m[13];
  18706. result.z = -this._pivotMatrix.m[14];
  18707. return this;
  18708. };
  18709. /**
  18710. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18711. */
  18712. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18713. var point = BABYLON.Vector3.Zero();
  18714. this.getAbsolutePivotPointToRef(point);
  18715. return point;
  18716. };
  18717. /**
  18718. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18719. * Returns the TransformNode.
  18720. */
  18721. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18722. result.x = this._pivotMatrix.m[12];
  18723. result.y = this._pivotMatrix.m[13];
  18724. result.z = this._pivotMatrix.m[14];
  18725. this.getPivotPointToRef(result);
  18726. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18727. return this;
  18728. };
  18729. /**
  18730. * Defines the passed node as the parent of the current node.
  18731. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18732. * Returns the TransformNode.
  18733. */
  18734. TransformNode.prototype.setParent = function (node) {
  18735. if (node === null) {
  18736. var rotation = BABYLON.Tmp.Quaternion[0];
  18737. var position = BABYLON.Tmp.Vector3[0];
  18738. var scale = BABYLON.Tmp.Vector3[1];
  18739. if (this.parent && this.parent.computeWorldMatrix) {
  18740. this.parent.computeWorldMatrix(true);
  18741. }
  18742. this.computeWorldMatrix(true);
  18743. this.getWorldMatrix().decompose(scale, rotation, position);
  18744. if (this.rotationQuaternion) {
  18745. this.rotationQuaternion.copyFrom(rotation);
  18746. }
  18747. else {
  18748. rotation.toEulerAnglesToRef(this.rotation);
  18749. }
  18750. this.scaling.x = scale.x;
  18751. this.scaling.y = scale.y;
  18752. this.scaling.z = scale.z;
  18753. this.position.x = position.x;
  18754. this.position.y = position.y;
  18755. this.position.z = position.z;
  18756. }
  18757. else {
  18758. var rotation = BABYLON.Tmp.Quaternion[0];
  18759. var position = BABYLON.Tmp.Vector3[0];
  18760. var scale = BABYLON.Tmp.Vector3[1];
  18761. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18762. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18763. this.computeWorldMatrix(true);
  18764. node.computeWorldMatrix(true);
  18765. node.getWorldMatrix().invertToRef(invParentMatrix);
  18766. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18767. diffMatrix.decompose(scale, rotation, position);
  18768. if (this.rotationQuaternion) {
  18769. this.rotationQuaternion.copyFrom(rotation);
  18770. }
  18771. else {
  18772. rotation.toEulerAnglesToRef(this.rotation);
  18773. }
  18774. this.position.x = position.x;
  18775. this.position.y = position.y;
  18776. this.position.z = position.z;
  18777. this.scaling.x = scale.x;
  18778. this.scaling.y = scale.y;
  18779. this.scaling.z = scale.z;
  18780. }
  18781. this.parent = node;
  18782. return this;
  18783. };
  18784. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18785. get: function () {
  18786. return this._nonUniformScaling;
  18787. },
  18788. enumerable: true,
  18789. configurable: true
  18790. });
  18791. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18792. if (this._nonUniformScaling === value) {
  18793. return false;
  18794. }
  18795. this._nonUniformScaling = true;
  18796. return true;
  18797. };
  18798. /**
  18799. * Attach the current TransformNode to another TransformNode associated with a bone
  18800. * @param bone Bone affecting the TransformNode
  18801. * @param affectedTransformNode TransformNode associated with the bone
  18802. */
  18803. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18804. this._transformToBoneReferal = affectedTransformNode;
  18805. this.parent = bone;
  18806. if (bone.getWorldMatrix().determinant() < 0) {
  18807. this.scalingDeterminant *= -1;
  18808. }
  18809. return this;
  18810. };
  18811. TransformNode.prototype.detachFromBone = function () {
  18812. if (!this.parent) {
  18813. return this;
  18814. }
  18815. if (this.parent.getWorldMatrix().determinant() < 0) {
  18816. this.scalingDeterminant *= -1;
  18817. }
  18818. this._transformToBoneReferal = null;
  18819. this.parent = null;
  18820. return this;
  18821. };
  18822. /**
  18823. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18824. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18825. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18826. * The passed axis is also normalized.
  18827. * Returns the TransformNode.
  18828. */
  18829. TransformNode.prototype.rotate = function (axis, amount, space) {
  18830. axis.normalize();
  18831. if (!this.rotationQuaternion) {
  18832. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18833. this.rotation = BABYLON.Vector3.Zero();
  18834. }
  18835. var rotationQuaternion;
  18836. if (!space || space === BABYLON.Space.LOCAL) {
  18837. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18838. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18839. }
  18840. else {
  18841. if (this.parent) {
  18842. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18843. invertParentWorldMatrix.invert();
  18844. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18845. }
  18846. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18847. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18848. }
  18849. return this;
  18850. };
  18851. /**
  18852. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18853. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18854. * The passed axis is also normalized.
  18855. * Returns the TransformNode.
  18856. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18857. */
  18858. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18859. axis.normalize();
  18860. if (!this.rotationQuaternion) {
  18861. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18862. this.rotation.copyFromFloats(0, 0, 0);
  18863. }
  18864. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18865. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18866. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18867. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18868. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18869. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18870. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18871. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18872. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18873. return this;
  18874. };
  18875. /**
  18876. * Translates the mesh along the axis vector for the passed distance in the given space.
  18877. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18878. * Returns the TransformNode.
  18879. */
  18880. TransformNode.prototype.translate = function (axis, distance, space) {
  18881. var displacementVector = axis.scale(distance);
  18882. if (!space || space === BABYLON.Space.LOCAL) {
  18883. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18884. this.setPositionWithLocalVector(tempV3);
  18885. }
  18886. else {
  18887. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18888. }
  18889. return this;
  18890. };
  18891. /**
  18892. * Adds a rotation step to the mesh current rotation.
  18893. * x, y, z are Euler angles expressed in radians.
  18894. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18895. * This means this rotation is made in the mesh local space only.
  18896. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18897. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18898. * ```javascript
  18899. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18900. * ```
  18901. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18902. * 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.
  18903. * Returns the TransformNode.
  18904. */
  18905. TransformNode.prototype.addRotation = function (x, y, z) {
  18906. var rotationQuaternion;
  18907. if (this.rotationQuaternion) {
  18908. rotationQuaternion = this.rotationQuaternion;
  18909. }
  18910. else {
  18911. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18912. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18913. }
  18914. var accumulation = BABYLON.Tmp.Quaternion[0];
  18915. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18916. rotationQuaternion.multiplyInPlace(accumulation);
  18917. if (!this.rotationQuaternion) {
  18918. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18919. }
  18920. return this;
  18921. };
  18922. /**
  18923. * Computes the mesh World matrix and returns it.
  18924. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18925. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18926. * If the parameter `force`is set to `true`, the actual computation is done.
  18927. * Returns the mesh World Matrix.
  18928. */
  18929. TransformNode.prototype.computeWorldMatrix = function (force) {
  18930. if (this._isWorldMatrixFrozen) {
  18931. return this._worldMatrix;
  18932. }
  18933. if (!force && this.isSynchronized(true)) {
  18934. this._currentRenderId = this.getScene().getRenderId();
  18935. return this._worldMatrix;
  18936. }
  18937. this._cache.position.copyFrom(this.position);
  18938. this._cache.scaling.copyFrom(this.scaling);
  18939. this._cache.pivotMatrixUpdated = false;
  18940. this._cache.billboardMode = this.billboardMode;
  18941. this._currentRenderId = this.getScene().getRenderId();
  18942. this._childRenderId = this.getScene().getRenderId();
  18943. this._isDirty = false;
  18944. // Scaling
  18945. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18946. // Rotation
  18947. //rotate, if quaternion is set and rotation was used
  18948. if (this.rotationQuaternion) {
  18949. var len = this.rotation.length();
  18950. if (len) {
  18951. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18952. this.rotation.copyFromFloats(0, 0, 0);
  18953. }
  18954. }
  18955. if (this.rotationQuaternion) {
  18956. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18957. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18958. }
  18959. else {
  18960. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18961. this._cache.rotation.copyFrom(this.rotation);
  18962. }
  18963. // Translation
  18964. var camera = this.getScene().activeCamera;
  18965. if (this.infiniteDistance && !this.parent && camera) {
  18966. var cameraWorldMatrix = camera.getWorldMatrix();
  18967. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18968. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18969. }
  18970. else {
  18971. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18972. }
  18973. // Composing transformations
  18974. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18975. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18976. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18977. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18978. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18979. // Need to decompose each rotation here
  18980. var currentPosition = BABYLON.Tmp.Vector3[3];
  18981. if (this.parent && this.parent.getWorldMatrix) {
  18982. if (this._transformToBoneReferal) {
  18983. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18984. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18985. }
  18986. else {
  18987. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18988. }
  18989. }
  18990. else {
  18991. currentPosition.copyFrom(this.position);
  18992. }
  18993. currentPosition.subtractInPlace(camera.globalPosition);
  18994. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18995. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18996. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18997. }
  18998. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18999. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19000. }
  19001. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19002. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19003. }
  19004. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19005. }
  19006. else {
  19007. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19008. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19009. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19010. }
  19011. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19012. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19013. }
  19014. // Local world
  19015. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19016. // Parent
  19017. if (this.parent && this.parent.getWorldMatrix) {
  19018. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19019. if (this._transformToBoneReferal) {
  19020. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19021. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19022. }
  19023. else {
  19024. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19025. }
  19026. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19027. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19028. this._worldMatrix.copyFrom(this._localWorld);
  19029. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19030. }
  19031. else {
  19032. if (this._transformToBoneReferal) {
  19033. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19034. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19035. }
  19036. else {
  19037. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19038. }
  19039. }
  19040. this._markSyncedWithParent();
  19041. }
  19042. else {
  19043. this._worldMatrix.copyFrom(this._localWorld);
  19044. }
  19045. // Post multiply inverse of pivotMatrix
  19046. if (this._postMultiplyPivotMatrix) {
  19047. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19048. }
  19049. // Normal matrix
  19050. if (this.scaling.isNonUniform) {
  19051. this._updateNonUniformScalingState(true);
  19052. }
  19053. else if (this.parent && this.parent._nonUniformScaling) {
  19054. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19055. }
  19056. else {
  19057. this._updateNonUniformScalingState(false);
  19058. }
  19059. this._afterComputeWorldMatrix();
  19060. // Absolute position
  19061. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19062. // Callbacks
  19063. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19064. if (!this._poseMatrix) {
  19065. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19066. }
  19067. // Cache the determinant
  19068. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19069. return this._worldMatrix;
  19070. };
  19071. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19072. };
  19073. /**
  19074. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19075. * @param func: callback function to add
  19076. *
  19077. * Returns the TransformNode.
  19078. */
  19079. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19080. this.onAfterWorldMatrixUpdateObservable.add(func);
  19081. return this;
  19082. };
  19083. /**
  19084. * Removes a registered callback function.
  19085. * Returns the TransformNode.
  19086. */
  19087. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19088. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19089. return this;
  19090. };
  19091. /**
  19092. * Clone the current transform node
  19093. * Returns the new transform node
  19094. * @param name Name of the new clone
  19095. * @param newParent New parent for the clone
  19096. * @param doNotCloneChildren Do not clone children hierarchy
  19097. */
  19098. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19099. var _this = this;
  19100. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19101. result.name = name;
  19102. result.id = name;
  19103. if (newParent) {
  19104. result.parent = newParent;
  19105. }
  19106. if (!doNotCloneChildren) {
  19107. // Children
  19108. var directDescendants = this.getDescendants(true);
  19109. for (var index = 0; index < directDescendants.length; index++) {
  19110. var child = directDescendants[index];
  19111. if (child.clone) {
  19112. child.clone(name + "." + child.name, result);
  19113. }
  19114. }
  19115. }
  19116. return result;
  19117. };
  19118. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19119. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19120. serializationObject.type = this.getClassName();
  19121. // Parent
  19122. if (this.parent) {
  19123. serializationObject.parentId = this.parent.id;
  19124. }
  19125. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19126. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19127. }
  19128. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19129. serializationObject.isEnabled = this.isEnabled();
  19130. // Parent
  19131. if (this.parent) {
  19132. serializationObject.parentId = this.parent.id;
  19133. }
  19134. return serializationObject;
  19135. };
  19136. // Statics
  19137. /**
  19138. * Returns a new TransformNode object parsed from the source provided.
  19139. * The parameter `parsedMesh` is the source.
  19140. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19141. */
  19142. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19143. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19144. if (BABYLON.Tags) {
  19145. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19146. }
  19147. if (parsedTransformNode.localMatrix) {
  19148. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19149. }
  19150. else if (parsedTransformNode.pivotMatrix) {
  19151. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19152. }
  19153. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19154. // Parent
  19155. if (parsedTransformNode.parentId) {
  19156. transformNode._waitingParentId = parsedTransformNode.parentId;
  19157. }
  19158. return transformNode;
  19159. };
  19160. /**
  19161. * Releases resources associated with this transform node.
  19162. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19163. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19164. */
  19165. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19166. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19167. // Animations
  19168. this.getScene().stopAnimation(this);
  19169. // Remove from scene
  19170. this.getScene().removeTransformNode(this);
  19171. this.onAfterWorldMatrixUpdateObservable.clear();
  19172. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19173. };
  19174. // Statics
  19175. TransformNode.BILLBOARDMODE_NONE = 0;
  19176. TransformNode.BILLBOARDMODE_X = 1;
  19177. TransformNode.BILLBOARDMODE_Y = 2;
  19178. TransformNode.BILLBOARDMODE_Z = 4;
  19179. TransformNode.BILLBOARDMODE_ALL = 7;
  19180. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19181. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19182. __decorate([
  19183. BABYLON.serializeAsVector3()
  19184. ], TransformNode.prototype, "_rotation", void 0);
  19185. __decorate([
  19186. BABYLON.serializeAsQuaternion()
  19187. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19188. __decorate([
  19189. BABYLON.serializeAsVector3()
  19190. ], TransformNode.prototype, "_scaling", void 0);
  19191. __decorate([
  19192. BABYLON.serialize()
  19193. ], TransformNode.prototype, "billboardMode", void 0);
  19194. __decorate([
  19195. BABYLON.serialize()
  19196. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19197. __decorate([
  19198. BABYLON.serialize()
  19199. ], TransformNode.prototype, "infiniteDistance", void 0);
  19200. __decorate([
  19201. BABYLON.serializeAsVector3()
  19202. ], TransformNode.prototype, "position", void 0);
  19203. return TransformNode;
  19204. }(BABYLON.Node));
  19205. BABYLON.TransformNode = TransformNode;
  19206. })(BABYLON || (BABYLON = {}));
  19207. //# sourceMappingURL=babylon.transformNode.js.map
  19208. var BABYLON;
  19209. (function (BABYLON) {
  19210. /**
  19211. * Class used to store all common mesh properties
  19212. */
  19213. var AbstractMesh = /** @class */ (function (_super) {
  19214. __extends(AbstractMesh, _super);
  19215. // Constructor
  19216. /**
  19217. * Creates a new AbstractMesh
  19218. * @param name defines the name of the mesh
  19219. * @param scene defines the hosting scene
  19220. */
  19221. function AbstractMesh(name, scene) {
  19222. if (scene === void 0) { scene = null; }
  19223. var _this = _super.call(this, name, scene, false) || this;
  19224. _this._facetNb = 0; // facet number
  19225. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19226. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19227. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19228. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19229. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19230. _this._subDiv = {
  19231. max: 1,
  19232. X: 1,
  19233. Y: 1,
  19234. Z: 1
  19235. };
  19236. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19237. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19238. // Events
  19239. /**
  19240. * An event triggered when this mesh collides with another one
  19241. */
  19242. _this.onCollideObservable = new BABYLON.Observable();
  19243. /**
  19244. * An event triggered when the collision's position changes
  19245. */
  19246. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19247. /**
  19248. * An event triggered when material is changed
  19249. */
  19250. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19251. // Properties
  19252. /**
  19253. * Gets or sets the orientation for POV movement & rotation
  19254. */
  19255. _this.definedFacingForward = true;
  19256. /**
  19257. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19258. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19259. * * 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.
  19260. * @see http://doc.babylonjs.com/features/occlusionquery
  19261. */
  19262. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19263. /**
  19264. * 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:
  19265. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19266. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19267. * * 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.
  19268. * @see http://doc.babylonjs.com/features/occlusionquery
  19269. */
  19270. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19271. /**
  19272. * 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.
  19273. * The default value is -1 which means don't break the query and wait till the result
  19274. * @see http://doc.babylonjs.com/features/occlusionquery
  19275. */
  19276. _this.occlusionRetryCount = -1;
  19277. _this._occlusionInternalRetryCounter = 0;
  19278. _this._isOccluded = false;
  19279. _this._isOcclusionQueryInProgress = false;
  19280. _this._visibility = 1.0;
  19281. /** Gets or sets the alpha index used to sort transparent meshes
  19282. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19283. */
  19284. _this.alphaIndex = Number.MAX_VALUE;
  19285. /**
  19286. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19287. */
  19288. _this.isVisible = true;
  19289. /**
  19290. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19291. */
  19292. _this.isPickable = true;
  19293. /**
  19294. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19295. */
  19296. _this.showBoundingBox = false;
  19297. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19298. _this.showSubMeshesBoundingBox = false;
  19299. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19300. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19301. */
  19302. _this.isBlocker = false;
  19303. /**
  19304. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19305. */
  19306. _this.enablePointerMoveEvents = false;
  19307. /**
  19308. * Specifies the rendering group id for this mesh (0 by default)
  19309. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19310. */
  19311. _this.renderingGroupId = 0;
  19312. _this._receiveShadows = false;
  19313. /**
  19314. * Gets or sets a boolean indicating if the outline must be rendered as well
  19315. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19316. */
  19317. _this.renderOutline = false;
  19318. /** Defines color to use when rendering outline */
  19319. _this.outlineColor = BABYLON.Color3.Red();
  19320. /** Define width to use when rendering outline */
  19321. _this.outlineWidth = 0.02;
  19322. /**
  19323. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19324. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19325. */
  19326. _this.renderOverlay = false;
  19327. /** Defines color to use when rendering overlay */
  19328. _this.overlayColor = BABYLON.Color3.Red();
  19329. /** Defines alpha to use when rendering overlay */
  19330. _this.overlayAlpha = 0.5;
  19331. _this._hasVertexAlpha = false;
  19332. _this._useVertexColors = true;
  19333. _this._computeBonesUsingShaders = true;
  19334. _this._numBoneInfluencers = 4;
  19335. _this._applyFog = true;
  19336. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19337. _this.useOctreeForRenderingSelection = true;
  19338. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19339. _this.useOctreeForPicking = true;
  19340. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19341. _this.useOctreeForCollisions = true;
  19342. _this._layerMask = 0x0FFFFFFF;
  19343. /**
  19344. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19345. */
  19346. _this.alwaysSelectAsActiveMesh = false;
  19347. /**
  19348. * Gets or sets the current action manager
  19349. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19350. */
  19351. _this.actionManager = null;
  19352. /**
  19353. * Gets or sets impostor used for physic simulation
  19354. * @see http://doc.babylonjs.com/features/physics_engine
  19355. */
  19356. _this.physicsImpostor = null;
  19357. // Collisions
  19358. _this._checkCollisions = false;
  19359. _this._collisionMask = -1;
  19360. _this._collisionGroup = -1;
  19361. /**
  19362. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19363. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19364. */
  19365. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19366. /**
  19367. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19368. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19369. */
  19370. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19371. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19372. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19373. // Edges
  19374. /**
  19375. * Defines edge width used when edgesRenderer is enabled
  19376. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19377. */
  19378. _this.edgesWidth = 1;
  19379. /**
  19380. * Defines edge color used when edgesRenderer is enabled
  19381. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19382. */
  19383. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19384. // Cache
  19385. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19386. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19387. /** @hidden */
  19388. _this._renderId = 0;
  19389. /** @hidden */
  19390. _this._intersectionsInProgress = new Array();
  19391. /** @hidden */
  19392. _this._unIndexed = false;
  19393. /** @hidden */
  19394. _this._lightSources = new Array();
  19395. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19396. if (collidedMesh === void 0) { collidedMesh = null; }
  19397. //TODO move this to the collision coordinator!
  19398. if (_this.getScene().workerCollisions)
  19399. newPosition.multiplyInPlace(_this._collider._radius);
  19400. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19401. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19402. _this.position.addInPlace(_this._diffPositionForCollisions);
  19403. }
  19404. if (collidedMesh) {
  19405. _this.onCollideObservable.notifyObservers(collidedMesh);
  19406. }
  19407. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19408. };
  19409. _this.getScene().addMesh(_this);
  19410. _this._resyncLightSources();
  19411. return _this;
  19412. }
  19413. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19414. /**
  19415. * No billboard
  19416. */
  19417. get: function () {
  19418. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19419. },
  19420. enumerable: true,
  19421. configurable: true
  19422. });
  19423. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19424. /** Billboard on X axis */
  19425. get: function () {
  19426. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19432. /** Billboard on Y axis */
  19433. get: function () {
  19434. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19440. /** Billboard on Z axis */
  19441. get: function () {
  19442. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19443. },
  19444. enumerable: true,
  19445. configurable: true
  19446. });
  19447. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19448. /** Billboard on all axes */
  19449. get: function () {
  19450. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19451. },
  19452. enumerable: true,
  19453. configurable: true
  19454. });
  19455. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19456. /**
  19457. * Gets the number of facets in the mesh
  19458. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19459. */
  19460. get: function () {
  19461. return this._facetNb;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19467. /**
  19468. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19469. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19470. */
  19471. get: function () {
  19472. return this._partitioningSubdivisions;
  19473. },
  19474. set: function (nb) {
  19475. this._partitioningSubdivisions = nb;
  19476. },
  19477. enumerable: true,
  19478. configurable: true
  19479. });
  19480. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19481. /**
  19482. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19483. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19484. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19485. */
  19486. get: function () {
  19487. return this._partitioningBBoxRatio;
  19488. },
  19489. set: function (ratio) {
  19490. this._partitioningBBoxRatio = ratio;
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19496. /**
  19497. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19498. * Works only for updatable meshes.
  19499. * Doesn't work with multi-materials
  19500. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19501. */
  19502. get: function () {
  19503. return this._facetDepthSort;
  19504. },
  19505. set: function (sort) {
  19506. this._facetDepthSort = sort;
  19507. },
  19508. enumerable: true,
  19509. configurable: true
  19510. });
  19511. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19512. /**
  19513. * The location (Vector3) where the facet depth sort must be computed from.
  19514. * By default, the active camera position.
  19515. * Used only when facet depth sort is enabled
  19516. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19517. */
  19518. get: function () {
  19519. return this._facetDepthSortFrom;
  19520. },
  19521. set: function (location) {
  19522. this._facetDepthSortFrom = location;
  19523. },
  19524. enumerable: true,
  19525. configurable: true
  19526. });
  19527. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19528. /**
  19529. * gets a boolean indicating if facetData is enabled
  19530. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19531. */
  19532. get: function () {
  19533. return this._facetDataEnabled;
  19534. },
  19535. enumerable: true,
  19536. configurable: true
  19537. });
  19538. /** @hidden */
  19539. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19540. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19541. return false;
  19542. }
  19543. this._markSubMeshesAsMiscDirty();
  19544. return true;
  19545. };
  19546. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19547. /** Set a function to call when this mesh collides with another one */
  19548. set: function (callback) {
  19549. if (this._onCollideObserver) {
  19550. this.onCollideObservable.remove(this._onCollideObserver);
  19551. }
  19552. this._onCollideObserver = this.onCollideObservable.add(callback);
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19558. /** Set a function to call when the collision's position changes */
  19559. set: function (callback) {
  19560. if (this._onCollisionPositionChangeObserver) {
  19561. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19562. }
  19563. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19564. },
  19565. enumerable: true,
  19566. configurable: true
  19567. });
  19568. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19569. /**
  19570. * 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
  19571. * @see http://doc.babylonjs.com/features/occlusionquery
  19572. */
  19573. get: function () {
  19574. return this._isOccluded;
  19575. },
  19576. set: function (value) {
  19577. this._isOccluded = value;
  19578. },
  19579. enumerable: true,
  19580. configurable: true
  19581. });
  19582. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19583. /**
  19584. * Flag to check the progress status of the query
  19585. * @see http://doc.babylonjs.com/features/occlusionquery
  19586. */
  19587. get: function () {
  19588. return this._isOcclusionQueryInProgress;
  19589. },
  19590. enumerable: true,
  19591. configurable: true
  19592. });
  19593. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19594. /**
  19595. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19596. */
  19597. get: function () {
  19598. return this._visibility;
  19599. },
  19600. /**
  19601. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19602. */
  19603. set: function (value) {
  19604. if (this._visibility === value) {
  19605. return;
  19606. }
  19607. this._visibility = value;
  19608. this._markSubMeshesAsMiscDirty();
  19609. },
  19610. enumerable: true,
  19611. configurable: true
  19612. });
  19613. Object.defineProperty(AbstractMesh.prototype, "material", {
  19614. /** Gets or sets current material */
  19615. get: function () {
  19616. return this._material;
  19617. },
  19618. set: function (value) {
  19619. if (this._material === value) {
  19620. return;
  19621. }
  19622. this._material = value;
  19623. if (this.onMaterialChangedObservable.hasObservers) {
  19624. this.onMaterialChangedObservable.notifyObservers(this);
  19625. }
  19626. if (!this.subMeshes) {
  19627. return;
  19628. }
  19629. this._unBindEffect();
  19630. },
  19631. enumerable: true,
  19632. configurable: true
  19633. });
  19634. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19635. /**
  19636. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19637. * @see http://doc.babylonjs.com/babylon101/shadows
  19638. */
  19639. get: function () {
  19640. return this._receiveShadows;
  19641. },
  19642. set: function (value) {
  19643. if (this._receiveShadows === value) {
  19644. return;
  19645. }
  19646. this._receiveShadows = value;
  19647. this._markSubMeshesAsLightDirty();
  19648. },
  19649. enumerable: true,
  19650. configurable: true
  19651. });
  19652. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19653. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19654. get: function () {
  19655. return this._hasVertexAlpha;
  19656. },
  19657. set: function (value) {
  19658. if (this._hasVertexAlpha === value) {
  19659. return;
  19660. }
  19661. this._hasVertexAlpha = value;
  19662. this._markSubMeshesAsAttributesDirty();
  19663. this._markSubMeshesAsMiscDirty();
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19669. /** 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) */
  19670. get: function () {
  19671. return this._useVertexColors;
  19672. },
  19673. set: function (value) {
  19674. if (this._useVertexColors === value) {
  19675. return;
  19676. }
  19677. this._useVertexColors = value;
  19678. this._markSubMeshesAsAttributesDirty();
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19684. /**
  19685. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19686. */
  19687. get: function () {
  19688. return this._computeBonesUsingShaders;
  19689. },
  19690. set: function (value) {
  19691. if (this._computeBonesUsingShaders === value) {
  19692. return;
  19693. }
  19694. this._computeBonesUsingShaders = value;
  19695. this._markSubMeshesAsAttributesDirty();
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19701. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19702. get: function () {
  19703. return this._numBoneInfluencers;
  19704. },
  19705. set: function (value) {
  19706. if (this._numBoneInfluencers === value) {
  19707. return;
  19708. }
  19709. this._numBoneInfluencers = value;
  19710. this._markSubMeshesAsAttributesDirty();
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19716. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19717. get: function () {
  19718. return this._applyFog;
  19719. },
  19720. set: function (value) {
  19721. if (this._applyFog === value) {
  19722. return;
  19723. }
  19724. this._applyFog = value;
  19725. this._markSubMeshesAsMiscDirty();
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19731. /**
  19732. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19733. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19734. */
  19735. get: function () {
  19736. return this._layerMask;
  19737. },
  19738. set: function (value) {
  19739. if (value === this._layerMask) {
  19740. return;
  19741. }
  19742. this._layerMask = value;
  19743. this._resyncLightSources();
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19749. /**
  19750. * Gets or sets a collision mask used to mask collisions (default is -1).
  19751. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19752. */
  19753. get: function () {
  19754. return this._collisionMask;
  19755. },
  19756. set: function (mask) {
  19757. this._collisionMask = !isNaN(mask) ? mask : -1;
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19763. /**
  19764. * Gets or sets the current collision group mask (-1 by default).
  19765. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19766. */
  19767. get: function () {
  19768. return this._collisionGroup;
  19769. },
  19770. set: function (mask) {
  19771. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19772. },
  19773. enumerable: true,
  19774. configurable: true
  19775. });
  19776. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19777. /** @hidden */
  19778. get: function () {
  19779. return null;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19785. get: function () {
  19786. return this._skeleton;
  19787. },
  19788. /**
  19789. * Gets or sets a skeleton to apply skining transformations
  19790. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19791. */
  19792. set: function (value) {
  19793. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19794. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19795. }
  19796. if (value && value.needInitialSkinMatrix) {
  19797. value._registerMeshWithPoseMatrix(this);
  19798. }
  19799. this._skeleton = value;
  19800. if (!this._skeleton) {
  19801. this._bonesTransformMatrices = null;
  19802. }
  19803. this._markSubMeshesAsAttributesDirty();
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. /**
  19809. * Returns the string "AbstractMesh"
  19810. * @returns "AbstractMesh"
  19811. */
  19812. AbstractMesh.prototype.getClassName = function () {
  19813. return "AbstractMesh";
  19814. };
  19815. /**
  19816. * Gets a string representation of the current mesh
  19817. * @param fullDetails defines a boolean indicating if full details must be included
  19818. * @returns a string representation of the current mesh
  19819. */
  19820. AbstractMesh.prototype.toString = function (fullDetails) {
  19821. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19822. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19823. if (this._skeleton) {
  19824. ret += ", skeleton: " + this._skeleton.name;
  19825. }
  19826. if (fullDetails) {
  19827. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19828. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19829. }
  19830. return ret;
  19831. };
  19832. /** @hidden */
  19833. AbstractMesh.prototype._rebuild = function () {
  19834. if (this._occlusionQuery) {
  19835. this._occlusionQuery = null;
  19836. }
  19837. if (this._edgesRenderer) {
  19838. this._edgesRenderer._rebuild();
  19839. }
  19840. if (!this.subMeshes) {
  19841. return;
  19842. }
  19843. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19844. var subMesh = _a[_i];
  19845. subMesh._rebuild();
  19846. }
  19847. };
  19848. /** @hidden */
  19849. AbstractMesh.prototype._resyncLightSources = function () {
  19850. this._lightSources.length = 0;
  19851. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19852. var light = _a[_i];
  19853. if (!light.isEnabled()) {
  19854. continue;
  19855. }
  19856. if (light.canAffectMesh(this)) {
  19857. this._lightSources.push(light);
  19858. }
  19859. }
  19860. this._markSubMeshesAsLightDirty();
  19861. };
  19862. /** @hidden */
  19863. AbstractMesh.prototype._resyncLighSource = function (light) {
  19864. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19865. var index = this._lightSources.indexOf(light);
  19866. if (index === -1) {
  19867. if (!isIn) {
  19868. return;
  19869. }
  19870. this._lightSources.push(light);
  19871. }
  19872. else {
  19873. if (isIn) {
  19874. return;
  19875. }
  19876. this._lightSources.splice(index, 1);
  19877. }
  19878. this._markSubMeshesAsLightDirty();
  19879. };
  19880. /** @hidden */
  19881. AbstractMesh.prototype._unBindEffect = function () {
  19882. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19883. var subMesh = _a[_i];
  19884. subMesh.setEffect(null);
  19885. }
  19886. };
  19887. /** @hidden */
  19888. AbstractMesh.prototype._removeLightSource = function (light) {
  19889. var index = this._lightSources.indexOf(light);
  19890. if (index === -1) {
  19891. return;
  19892. }
  19893. this._lightSources.splice(index, 1);
  19894. this._markSubMeshesAsLightDirty();
  19895. };
  19896. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19897. if (!this.subMeshes) {
  19898. return;
  19899. }
  19900. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19901. var subMesh = _a[_i];
  19902. if (subMesh._materialDefines) {
  19903. func(subMesh._materialDefines);
  19904. }
  19905. }
  19906. };
  19907. /** @hidden */
  19908. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19909. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19910. };
  19911. /** @hidden */
  19912. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19913. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19914. };
  19915. /** @hidden */
  19916. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19917. if (!this.subMeshes) {
  19918. return;
  19919. }
  19920. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19921. var subMesh = _a[_i];
  19922. var material = subMesh.getMaterial();
  19923. if (material) {
  19924. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19925. }
  19926. }
  19927. };
  19928. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19929. /**
  19930. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19931. */
  19932. get: function () {
  19933. return this._scaling;
  19934. },
  19935. set: function (newScaling) {
  19936. this._scaling = newScaling;
  19937. if (this.physicsImpostor) {
  19938. this.physicsImpostor.forceUpdate();
  19939. }
  19940. },
  19941. enumerable: true,
  19942. configurable: true
  19943. });
  19944. // Methods
  19945. /**
  19946. * Disables the mesh edge rendering mode
  19947. * @returns the currentAbstractMesh
  19948. */
  19949. AbstractMesh.prototype.disableEdgesRendering = function () {
  19950. if (this._edgesRenderer) {
  19951. this._edgesRenderer.dispose();
  19952. this._edgesRenderer = null;
  19953. }
  19954. return this;
  19955. };
  19956. /**
  19957. * Enables the edge rendering mode on the mesh.
  19958. * This mode makes the mesh edges visible
  19959. * @param epsilon defines the maximal distance between two angles to detect a face
  19960. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19961. * @returns the currentAbstractMesh
  19962. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19963. */
  19964. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19965. if (epsilon === void 0) { epsilon = 0.95; }
  19966. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19967. this.disableEdgesRendering();
  19968. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19969. return this;
  19970. };
  19971. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19972. /**
  19973. * Returns true if the mesh is blocked. Implemented by child classes
  19974. */
  19975. get: function () {
  19976. return false;
  19977. },
  19978. enumerable: true,
  19979. configurable: true
  19980. });
  19981. /**
  19982. * Returns the mesh itself by default. Implemented by child classes
  19983. * @param camera defines the camera to use to pick the right LOD level
  19984. * @returns the currentAbstractMesh
  19985. */
  19986. AbstractMesh.prototype.getLOD = function (camera) {
  19987. return this;
  19988. };
  19989. /**
  19990. * Returns 0 by default. Implemented by child classes
  19991. * @returns an integer
  19992. */
  19993. AbstractMesh.prototype.getTotalVertices = function () {
  19994. return 0;
  19995. };
  19996. /**
  19997. * Returns null by default. Implemented by child classes
  19998. * @returns null
  19999. */
  20000. AbstractMesh.prototype.getIndices = function () {
  20001. return null;
  20002. };
  20003. /**
  20004. * Returns the array of the requested vertex data kind. Implemented by child classes
  20005. * @param kind defines the vertex data kind to use
  20006. * @returns null
  20007. */
  20008. AbstractMesh.prototype.getVerticesData = function (kind) {
  20009. return null;
  20010. };
  20011. /**
  20012. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20013. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20014. * Note that a new underlying VertexBuffer object is created each call.
  20015. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20016. * @param kind defines vertex data kind:
  20017. * * BABYLON.VertexBuffer.PositionKind
  20018. * * BABYLON.VertexBuffer.UVKind
  20019. * * BABYLON.VertexBuffer.UV2Kind
  20020. * * BABYLON.VertexBuffer.UV3Kind
  20021. * * BABYLON.VertexBuffer.UV4Kind
  20022. * * BABYLON.VertexBuffer.UV5Kind
  20023. * * BABYLON.VertexBuffer.UV6Kind
  20024. * * BABYLON.VertexBuffer.ColorKind
  20025. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20026. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20027. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20028. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20029. * @param data defines the data source
  20030. * @param updatable defines if the data must be flagged as updatable (or static)
  20031. * @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
  20032. * @returns the current mesh
  20033. */
  20034. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20035. return this;
  20036. };
  20037. /**
  20038. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20039. * If the mesh has no geometry, it is simply returned as it is.
  20040. * @param kind defines vertex data kind:
  20041. * * BABYLON.VertexBuffer.PositionKind
  20042. * * BABYLON.VertexBuffer.UVKind
  20043. * * BABYLON.VertexBuffer.UV2Kind
  20044. * * BABYLON.VertexBuffer.UV3Kind
  20045. * * BABYLON.VertexBuffer.UV4Kind
  20046. * * BABYLON.VertexBuffer.UV5Kind
  20047. * * BABYLON.VertexBuffer.UV6Kind
  20048. * * BABYLON.VertexBuffer.ColorKind
  20049. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20050. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20051. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20052. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20053. * @param data defines the data source
  20054. * @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
  20055. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20056. * @returns the current mesh
  20057. */
  20058. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20059. return this;
  20060. };
  20061. /**
  20062. * Sets the mesh indices,
  20063. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20064. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20065. * @param totalVertices Defines the total number of vertices
  20066. * @returns the current mesh
  20067. */
  20068. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20069. return this;
  20070. };
  20071. /**
  20072. * Gets a boolean indicating if specific vertex data is present
  20073. * @param kind defines the vertex data kind to use
  20074. * @returns true is data kind is present
  20075. */
  20076. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20077. return false;
  20078. };
  20079. /**
  20080. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20081. * @returns a BoundingInfo
  20082. */
  20083. AbstractMesh.prototype.getBoundingInfo = function () {
  20084. if (this._masterMesh) {
  20085. return this._masterMesh.getBoundingInfo();
  20086. }
  20087. if (!this._boundingInfo) {
  20088. // this._boundingInfo is being created here
  20089. this._updateBoundingInfo();
  20090. }
  20091. // cannot be null.
  20092. return this._boundingInfo;
  20093. };
  20094. /**
  20095. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20096. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20097. * @returns the current mesh
  20098. */
  20099. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20100. if (includeDescendants === void 0) { includeDescendants = true; }
  20101. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20102. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20103. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20104. if (maxDimension === 0) {
  20105. return this;
  20106. }
  20107. var scale = 1 / maxDimension;
  20108. this.scaling.scaleInPlace(scale);
  20109. return this;
  20110. };
  20111. /**
  20112. * Overwrite the current bounding info
  20113. * @param boundingInfo defines the new bounding info
  20114. * @returns the current mesh
  20115. */
  20116. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20117. this._boundingInfo = boundingInfo;
  20118. return this;
  20119. };
  20120. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20121. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20122. get: function () {
  20123. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20124. },
  20125. enumerable: true,
  20126. configurable: true
  20127. });
  20128. /** @hidden */
  20129. AbstractMesh.prototype._preActivate = function () {
  20130. };
  20131. /** @hidden */
  20132. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20133. };
  20134. /** @hidden */
  20135. AbstractMesh.prototype._activate = function (renderId) {
  20136. this._renderId = renderId;
  20137. };
  20138. /**
  20139. * Gets the current world matrix
  20140. * @returns a Matrix
  20141. */
  20142. AbstractMesh.prototype.getWorldMatrix = function () {
  20143. if (this._masterMesh) {
  20144. return this._masterMesh.getWorldMatrix();
  20145. }
  20146. return _super.prototype.getWorldMatrix.call(this);
  20147. };
  20148. /** @hidden */
  20149. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20150. if (this._masterMesh) {
  20151. return this._masterMesh._getWorldMatrixDeterminant();
  20152. }
  20153. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20154. };
  20155. // ================================== Point of View Movement =================================
  20156. /**
  20157. * Perform relative position change from the point of view of behind the front of the mesh.
  20158. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20159. * Supports definition of mesh facing forward or backward
  20160. * @param amountRight defines the distance on the right axis
  20161. * @param amountUp defines the distance on the up axis
  20162. * @param amountForward defines the distance on the forward axis
  20163. * @returns the current mesh
  20164. */
  20165. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20166. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20167. return this;
  20168. };
  20169. /**
  20170. * Calculate relative position change from the point of view of behind the front of the mesh.
  20171. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20172. * Supports definition of mesh facing forward or backward
  20173. * @param amountRight defines the distance on the right axis
  20174. * @param amountUp defines the distance on the up axis
  20175. * @param amountForward defines the distance on the forward axis
  20176. * @returns the new displacement vector
  20177. */
  20178. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20179. var rotMatrix = new BABYLON.Matrix();
  20180. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20181. rotQuaternion.toRotationMatrix(rotMatrix);
  20182. var translationDelta = BABYLON.Vector3.Zero();
  20183. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20184. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20185. return translationDelta;
  20186. };
  20187. // ================================== Point of View Rotation =================================
  20188. /**
  20189. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20190. * Supports definition of mesh facing forward or backward
  20191. * @param flipBack defines the flip
  20192. * @param twirlClockwise defines the twirl
  20193. * @param tiltRight defines the tilt
  20194. * @returns the current mesh
  20195. */
  20196. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20197. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20198. return this;
  20199. };
  20200. /**
  20201. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20202. * Supports definition of mesh facing forward or backward.
  20203. * @param flipBack defines the flip
  20204. * @param twirlClockwise defines the twirl
  20205. * @param tiltRight defines the tilt
  20206. * @returns the new rotation vector
  20207. */
  20208. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20209. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20210. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20211. };
  20212. /**
  20213. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20214. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20215. * @returns the new bounding vectors
  20216. */
  20217. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20218. if (includeDescendants === void 0) { includeDescendants = true; }
  20219. this.computeWorldMatrix(true);
  20220. var min;
  20221. var max;
  20222. var boundingInfo = this.getBoundingInfo();
  20223. if (!this.subMeshes) {
  20224. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20225. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20226. }
  20227. else {
  20228. min = boundingInfo.boundingBox.minimumWorld;
  20229. max = boundingInfo.boundingBox.maximumWorld;
  20230. }
  20231. if (includeDescendants) {
  20232. var descendants = this.getDescendants(false);
  20233. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20234. var descendant = descendants_1[_i];
  20235. var childMesh = descendant;
  20236. childMesh.computeWorldMatrix(true);
  20237. //make sure we have the needed params to get mix and max
  20238. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20239. continue;
  20240. }
  20241. var childBoundingInfo = childMesh.getBoundingInfo();
  20242. var boundingBox = childBoundingInfo.boundingBox;
  20243. var minBox = boundingBox.minimumWorld;
  20244. var maxBox = boundingBox.maximumWorld;
  20245. BABYLON.Tools.CheckExtends(minBox, min, max);
  20246. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20247. }
  20248. }
  20249. return {
  20250. min: min,
  20251. max: max
  20252. };
  20253. };
  20254. /** @hidden */
  20255. AbstractMesh.prototype._updateBoundingInfo = function () {
  20256. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20257. this._boundingInfo.update(this.worldMatrixFromCache);
  20258. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20259. return this;
  20260. };
  20261. /** @hidden */
  20262. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20263. if (!this.subMeshes) {
  20264. return this;
  20265. }
  20266. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20267. var subMesh = this.subMeshes[subIndex];
  20268. if (!subMesh.IsGlobal) {
  20269. subMesh.updateBoundingInfo(matrix);
  20270. }
  20271. }
  20272. return this;
  20273. };
  20274. /** @hidden */
  20275. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20276. // Bounding info
  20277. this._updateBoundingInfo();
  20278. };
  20279. /**
  20280. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20281. * A mesh is in the frustum if its bounding box intersects the frustum
  20282. * @param frustumPlanes defines the frustum to test
  20283. * @returns true if the mesh is in the frustum planes
  20284. */
  20285. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20286. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20287. };
  20288. /**
  20289. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20290. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20291. * @param frustumPlanes defines the frustum to test
  20292. * @returns true if the mesh is completely in the frustum planes
  20293. */
  20294. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20295. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20296. ;
  20297. };
  20298. /**
  20299. * True if the mesh intersects another mesh or a SolidParticle object
  20300. * @param mesh defines a target mesh or SolidParticle to test
  20301. * @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)
  20302. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20303. * @returns true if there is an intersection
  20304. */
  20305. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20306. if (precise === void 0) { precise = false; }
  20307. if (!this._boundingInfo || !mesh._boundingInfo) {
  20308. return false;
  20309. }
  20310. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20311. return true;
  20312. }
  20313. if (includeDescendants) {
  20314. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20315. var child = _a[_i];
  20316. if (child.intersectsMesh(mesh, precise, true)) {
  20317. return true;
  20318. }
  20319. }
  20320. }
  20321. return false;
  20322. };
  20323. /**
  20324. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20325. * @param point defines the point to test
  20326. * @returns true if there is an intersection
  20327. */
  20328. AbstractMesh.prototype.intersectsPoint = function (point) {
  20329. if (!this._boundingInfo) {
  20330. return false;
  20331. }
  20332. return this._boundingInfo.intersectsPoint(point);
  20333. };
  20334. /**
  20335. * Gets the current physics impostor
  20336. * @see http://doc.babylonjs.com/features/physics_engine
  20337. * @returns a physics impostor or null
  20338. */
  20339. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20340. return this.physicsImpostor;
  20341. };
  20342. /**
  20343. * Gets the position of the current mesh in camera space
  20344. * @param camera defines the camera to use
  20345. * @returns a position
  20346. */
  20347. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20348. if (camera === void 0) { camera = null; }
  20349. if (!camera) {
  20350. camera = this.getScene().activeCamera;
  20351. }
  20352. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20353. };
  20354. /**
  20355. * Returns the distance from the mesh to the active camera
  20356. * @param camera defines the camera to use
  20357. * @returns the distance
  20358. */
  20359. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20360. if (camera === void 0) { camera = null; }
  20361. if (!camera) {
  20362. camera = this.getScene().activeCamera;
  20363. }
  20364. return this.absolutePosition.subtract(camera.position).length();
  20365. };
  20366. /**
  20367. * Apply a physic impulse to the mesh
  20368. * @param force defines the force to apply
  20369. * @param contactPoint defines where to apply the force
  20370. * @returns the current mesh
  20371. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20372. */
  20373. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20374. if (!this.physicsImpostor) {
  20375. return this;
  20376. }
  20377. this.physicsImpostor.applyImpulse(force, contactPoint);
  20378. return this;
  20379. };
  20380. /**
  20381. * Creates a physic joint between two meshes
  20382. * @param otherMesh defines the other mesh to use
  20383. * @param pivot1 defines the pivot to use on this mesh
  20384. * @param pivot2 defines the pivot to use on the other mesh
  20385. * @param options defines additional options (can be plugin dependent)
  20386. * @returns the current mesh
  20387. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20388. */
  20389. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20390. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20391. return this;
  20392. }
  20393. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20394. mainPivot: pivot1,
  20395. connectedPivot: pivot2,
  20396. nativeParams: options
  20397. });
  20398. return this;
  20399. };
  20400. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20401. // Collisions
  20402. /**
  20403. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20404. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20405. */
  20406. get: function () {
  20407. return this._checkCollisions;
  20408. },
  20409. set: function (collisionEnabled) {
  20410. this._checkCollisions = collisionEnabled;
  20411. if (this.getScene().workerCollisions) {
  20412. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20413. }
  20414. },
  20415. enumerable: true,
  20416. configurable: true
  20417. });
  20418. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20419. /**
  20420. * Gets Collider object used to compute collisions (not physics)
  20421. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20422. */
  20423. get: function () {
  20424. return this._collider;
  20425. },
  20426. enumerable: true,
  20427. configurable: true
  20428. });
  20429. /**
  20430. * Move the mesh using collision engine
  20431. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20432. * @param displacement defines the requested displacement vector
  20433. * @returns the current mesh
  20434. */
  20435. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20436. var globalPosition = this.getAbsolutePosition();
  20437. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20438. if (!this._collider) {
  20439. this._collider = new BABYLON.Collider();
  20440. }
  20441. this._collider._radius = this.ellipsoid;
  20442. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20443. return this;
  20444. };
  20445. // Submeshes octree
  20446. /**
  20447. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20448. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20449. * @param maxCapacity defines the maximum size of each block (64 by default)
  20450. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20451. * @returns the new octree
  20452. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20453. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20454. */
  20455. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20456. if (maxCapacity === void 0) { maxCapacity = 64; }
  20457. if (maxDepth === void 0) { maxDepth = 2; }
  20458. if (!this._submeshesOctree) {
  20459. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20460. }
  20461. this.computeWorldMatrix(true);
  20462. var boundingInfo = this.getBoundingInfo();
  20463. // Update octree
  20464. var bbox = boundingInfo.boundingBox;
  20465. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20466. return this._submeshesOctree;
  20467. };
  20468. // Collisions
  20469. /** @hidden */
  20470. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20471. this._generatePointsArray();
  20472. if (!this._positions) {
  20473. return this;
  20474. }
  20475. // Transformation
  20476. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20477. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20478. subMesh._lastColliderWorldVertices = [];
  20479. subMesh._trianglePlanes = [];
  20480. var start = subMesh.verticesStart;
  20481. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20482. for (var i = start; i < end; i++) {
  20483. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20484. }
  20485. }
  20486. // Collide
  20487. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20488. if (collider.collisionFound) {
  20489. collider.collidedMesh = this;
  20490. }
  20491. return this;
  20492. };
  20493. /** @hidden */
  20494. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20495. var subMeshes;
  20496. var len;
  20497. // Octrees
  20498. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20499. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20500. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20501. len = intersections.length;
  20502. subMeshes = intersections.data;
  20503. }
  20504. else {
  20505. subMeshes = this.subMeshes;
  20506. len = subMeshes.length;
  20507. }
  20508. for (var index = 0; index < len; index++) {
  20509. var subMesh = subMeshes[index];
  20510. // Bounding test
  20511. if (len > 1 && !subMesh._checkCollision(collider))
  20512. continue;
  20513. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20514. }
  20515. return this;
  20516. };
  20517. /** @hidden */
  20518. AbstractMesh.prototype._checkCollision = function (collider) {
  20519. // Bounding box test
  20520. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20521. return this;
  20522. // Transformation matrix
  20523. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20524. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20525. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20526. return this;
  20527. };
  20528. // Picking
  20529. /** @hidden */
  20530. AbstractMesh.prototype._generatePointsArray = function () {
  20531. return false;
  20532. };
  20533. /**
  20534. * Checks if the passed Ray intersects with the mesh
  20535. * @param ray defines the ray to use
  20536. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20537. * @returns the picking info
  20538. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20539. */
  20540. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20541. var pickingInfo = new BABYLON.PickingInfo();
  20542. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20543. return pickingInfo;
  20544. }
  20545. if (!this._generatePointsArray()) {
  20546. return pickingInfo;
  20547. }
  20548. var intersectInfo = null;
  20549. // Octrees
  20550. var subMeshes;
  20551. var len;
  20552. if (this._submeshesOctree && this.useOctreeForPicking) {
  20553. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20554. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20555. len = intersections.length;
  20556. subMeshes = intersections.data;
  20557. }
  20558. else {
  20559. subMeshes = this.subMeshes;
  20560. len = subMeshes.length;
  20561. }
  20562. for (var index = 0; index < len; index++) {
  20563. var subMesh = subMeshes[index];
  20564. // Bounding test
  20565. if (len > 1 && !subMesh.canIntersects(ray))
  20566. continue;
  20567. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20568. if (currentIntersectInfo) {
  20569. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20570. intersectInfo = currentIntersectInfo;
  20571. intersectInfo.subMeshId = index;
  20572. if (fastCheck) {
  20573. break;
  20574. }
  20575. }
  20576. }
  20577. }
  20578. if (intersectInfo) {
  20579. // Get picked point
  20580. var world = this.getWorldMatrix();
  20581. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20582. var direction = ray.direction.clone();
  20583. direction = direction.scale(intersectInfo.distance);
  20584. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20585. var pickedPoint = worldOrigin.add(worldDirection);
  20586. // Return result
  20587. pickingInfo.hit = true;
  20588. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20589. pickingInfo.pickedPoint = pickedPoint;
  20590. pickingInfo.pickedMesh = this;
  20591. pickingInfo.bu = intersectInfo.bu || 0;
  20592. pickingInfo.bv = intersectInfo.bv || 0;
  20593. pickingInfo.faceId = intersectInfo.faceId;
  20594. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20595. return pickingInfo;
  20596. }
  20597. return pickingInfo;
  20598. };
  20599. /**
  20600. * Clones the current mesh
  20601. * @param name defines the mesh name
  20602. * @param newParent defines the new mesh parent
  20603. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20604. * @returns the new mesh
  20605. */
  20606. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20607. return null;
  20608. };
  20609. /**
  20610. * Disposes all the submeshes of the current meshnp
  20611. * @returns the current mesh
  20612. */
  20613. AbstractMesh.prototype.releaseSubMeshes = function () {
  20614. if (this.subMeshes) {
  20615. while (this.subMeshes.length) {
  20616. this.subMeshes[0].dispose();
  20617. }
  20618. }
  20619. else {
  20620. this.subMeshes = new Array();
  20621. }
  20622. return this;
  20623. };
  20624. /**
  20625. * Releases resources associated with this abstract mesh.
  20626. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20627. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20628. */
  20629. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20630. var _this = this;
  20631. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20632. var index;
  20633. // Smart Array Retainers.
  20634. this.getScene().freeActiveMeshes();
  20635. this.getScene().freeRenderingGroups();
  20636. // Action manager
  20637. if (this.actionManager !== undefined && this.actionManager !== null) {
  20638. this.actionManager.dispose();
  20639. this.actionManager = null;
  20640. }
  20641. // Skeleton
  20642. this._skeleton = null;
  20643. // Physics
  20644. if (this.physicsImpostor) {
  20645. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20646. }
  20647. // Intersections in progress
  20648. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20649. var other = this._intersectionsInProgress[index];
  20650. var pos = other._intersectionsInProgress.indexOf(this);
  20651. other._intersectionsInProgress.splice(pos, 1);
  20652. }
  20653. this._intersectionsInProgress = [];
  20654. // Lights
  20655. var lights = this.getScene().lights;
  20656. lights.forEach(function (light) {
  20657. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20658. if (meshIndex !== -1) {
  20659. light.includedOnlyMeshes.splice(meshIndex, 1);
  20660. }
  20661. meshIndex = light.excludedMeshes.indexOf(_this);
  20662. if (meshIndex !== -1) {
  20663. light.excludedMeshes.splice(meshIndex, 1);
  20664. }
  20665. // Shadow generators
  20666. var generator = light.getShadowGenerator();
  20667. if (generator) {
  20668. var shadowMap = generator.getShadowMap();
  20669. if (shadowMap && shadowMap.renderList) {
  20670. meshIndex = shadowMap.renderList.indexOf(_this);
  20671. if (meshIndex !== -1) {
  20672. shadowMap.renderList.splice(meshIndex, 1);
  20673. }
  20674. }
  20675. }
  20676. });
  20677. // Edges
  20678. if (this._edgesRenderer) {
  20679. this._edgesRenderer.dispose();
  20680. this._edgesRenderer = null;
  20681. }
  20682. // SubMeshes
  20683. if (this.getClassName() !== "InstancedMesh") {
  20684. this.releaseSubMeshes();
  20685. }
  20686. // Octree
  20687. var sceneOctree = this.getScene().selectionOctree;
  20688. if (sceneOctree !== undefined && sceneOctree !== null) {
  20689. var index = sceneOctree.dynamicContent.indexOf(this);
  20690. if (index !== -1) {
  20691. sceneOctree.dynamicContent.splice(index, 1);
  20692. }
  20693. }
  20694. // Query
  20695. var engine = this.getScene().getEngine();
  20696. if (this._occlusionQuery) {
  20697. this._isOcclusionQueryInProgress = false;
  20698. engine.deleteQuery(this._occlusionQuery);
  20699. this._occlusionQuery = null;
  20700. }
  20701. // Engine
  20702. engine.wipeCaches();
  20703. // Remove from scene
  20704. this.getScene().removeMesh(this);
  20705. if (disposeMaterialAndTextures) {
  20706. if (this.material) {
  20707. this.material.dispose(false, true);
  20708. }
  20709. }
  20710. if (!doNotRecurse) {
  20711. // Particles
  20712. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20713. if (this.getScene().particleSystems[index].emitter === this) {
  20714. this.getScene().particleSystems[index].dispose();
  20715. index--;
  20716. }
  20717. }
  20718. }
  20719. // facet data
  20720. if (this._facetDataEnabled) {
  20721. this.disableFacetData();
  20722. }
  20723. this.onAfterWorldMatrixUpdateObservable.clear();
  20724. this.onCollideObservable.clear();
  20725. this.onCollisionPositionChangeObservable.clear();
  20726. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20727. };
  20728. /**
  20729. * Adds the passed mesh as a child to the current mesh
  20730. * @param mesh defines the child mesh
  20731. * @returns the current mesh
  20732. */
  20733. AbstractMesh.prototype.addChild = function (mesh) {
  20734. mesh.setParent(this);
  20735. return this;
  20736. };
  20737. /**
  20738. * Removes the passed mesh from the current mesh children list
  20739. * @param mesh defines the child mesh
  20740. * @returns the current mesh
  20741. */
  20742. AbstractMesh.prototype.removeChild = function (mesh) {
  20743. mesh.setParent(null);
  20744. return this;
  20745. };
  20746. // Facet data
  20747. /** @hidden */
  20748. AbstractMesh.prototype._initFacetData = function () {
  20749. if (!this._facetNormals) {
  20750. this._facetNormals = new Array();
  20751. }
  20752. if (!this._facetPositions) {
  20753. this._facetPositions = new Array();
  20754. }
  20755. if (!this._facetPartitioning) {
  20756. this._facetPartitioning = new Array();
  20757. }
  20758. this._facetNb = (this.getIndices().length / 3) | 0;
  20759. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20760. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20761. for (var f = 0; f < this._facetNb; f++) {
  20762. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20763. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20764. }
  20765. this._facetDataEnabled = true;
  20766. return this;
  20767. };
  20768. /**
  20769. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20770. * This method can be called within the render loop.
  20771. * 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
  20772. * @returns the current mesh
  20773. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20774. */
  20775. AbstractMesh.prototype.updateFacetData = function () {
  20776. if (!this._facetDataEnabled) {
  20777. this._initFacetData();
  20778. }
  20779. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20780. var indices = this.getIndices();
  20781. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20782. var bInfo = this.getBoundingInfo();
  20783. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20784. // init arrays, matrix and sort function on first call
  20785. this._facetDepthSortEnabled = true;
  20786. if (indices instanceof Uint16Array) {
  20787. this._depthSortedIndices = new Uint16Array(indices);
  20788. }
  20789. else if (indices instanceof Uint32Array) {
  20790. this._depthSortedIndices = new Uint32Array(indices);
  20791. }
  20792. else {
  20793. var needs32bits = false;
  20794. for (var i = 0; i < indices.length; i++) {
  20795. if (indices[i] > 65535) {
  20796. needs32bits = true;
  20797. break;
  20798. }
  20799. }
  20800. if (needs32bits) {
  20801. this._depthSortedIndices = new Uint32Array(indices);
  20802. }
  20803. else {
  20804. this._depthSortedIndices = new Uint16Array(indices);
  20805. }
  20806. }
  20807. this._facetDepthSortFunction = function (f1, f2) {
  20808. return (f2.sqDistance - f1.sqDistance);
  20809. };
  20810. if (!this._facetDepthSortFrom) {
  20811. var camera = this.getScene().activeCamera;
  20812. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20813. }
  20814. this._depthSortedFacets = [];
  20815. for (var f = 0; f < this._facetNb; f++) {
  20816. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20817. this._depthSortedFacets.push(depthSortedFacet);
  20818. }
  20819. this._invertedMatrix = BABYLON.Matrix.Identity();
  20820. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20821. }
  20822. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20823. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20824. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20825. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20826. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20827. this._subDiv.max = this._partitioningSubdivisions;
  20828. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20829. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20830. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20831. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20832. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20833. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20834. // set the parameters for ComputeNormals()
  20835. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20836. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20837. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20838. this._facetParameters.bInfo = bInfo;
  20839. this._facetParameters.bbSize = this._bbSize;
  20840. this._facetParameters.subDiv = this._subDiv;
  20841. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20842. this._facetParameters.depthSort = this._facetDepthSort;
  20843. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20844. this.computeWorldMatrix(true);
  20845. this._worldMatrix.invertToRef(this._invertedMatrix);
  20846. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20847. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20848. }
  20849. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20850. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20851. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20852. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20853. var l = (this._depthSortedIndices.length / 3) | 0;
  20854. for (var f = 0; f < l; f++) {
  20855. var sind = this._depthSortedFacets[f].ind;
  20856. this._depthSortedIndices[f * 3] = indices[sind];
  20857. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20858. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20859. }
  20860. this.updateIndices(this._depthSortedIndices);
  20861. }
  20862. return this;
  20863. };
  20864. /**
  20865. * Returns the facetLocalNormals array.
  20866. * The normals are expressed in the mesh local spac
  20867. * @returns an array of Vector3
  20868. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20869. */
  20870. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20871. if (!this._facetNormals) {
  20872. this.updateFacetData();
  20873. }
  20874. return this._facetNormals;
  20875. };
  20876. /**
  20877. * Returns the facetLocalPositions array.
  20878. * The facet positions are expressed in the mesh local space
  20879. * @returns an array of Vector3
  20880. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20881. */
  20882. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20883. if (!this._facetPositions) {
  20884. this.updateFacetData();
  20885. }
  20886. return this._facetPositions;
  20887. };
  20888. /**
  20889. * Returns the facetLocalPartioning array
  20890. * @returns an array of array of numbers
  20891. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20892. */
  20893. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20894. if (!this._facetPartitioning) {
  20895. this.updateFacetData();
  20896. }
  20897. return this._facetPartitioning;
  20898. };
  20899. /**
  20900. * Returns the i-th facet position in the world system.
  20901. * This method allocates a new Vector3 per call
  20902. * @param i defines the facet index
  20903. * @returns a new Vector3
  20904. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20905. */
  20906. AbstractMesh.prototype.getFacetPosition = function (i) {
  20907. var pos = BABYLON.Vector3.Zero();
  20908. this.getFacetPositionToRef(i, pos);
  20909. return pos;
  20910. };
  20911. /**
  20912. * Sets the reference Vector3 with the i-th facet position in the world system
  20913. * @param i defines the facet index
  20914. * @param ref defines the target vector
  20915. * @returns the current mesh
  20916. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20917. */
  20918. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20919. var localPos = (this.getFacetLocalPositions())[i];
  20920. var world = this.getWorldMatrix();
  20921. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20922. return this;
  20923. };
  20924. /**
  20925. * Returns the i-th facet normal in the world system.
  20926. * This method allocates a new Vector3 per call
  20927. * @param i defines the facet index
  20928. * @returns a new Vector3
  20929. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20930. */
  20931. AbstractMesh.prototype.getFacetNormal = function (i) {
  20932. var norm = BABYLON.Vector3.Zero();
  20933. this.getFacetNormalToRef(i, norm);
  20934. return norm;
  20935. };
  20936. /**
  20937. * Sets the reference Vector3 with the i-th facet normal in the world system
  20938. * @param i defines the facet index
  20939. * @param ref defines the target vector
  20940. * @returns the current mesh
  20941. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20942. */
  20943. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20944. var localNorm = (this.getFacetLocalNormals())[i];
  20945. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20946. return this;
  20947. };
  20948. /**
  20949. * 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)
  20950. * @param x defines x coordinate
  20951. * @param y defines y coordinate
  20952. * @param z defines z coordinate
  20953. * @returns the array of facet indexes
  20954. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20955. */
  20956. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20957. var bInfo = this.getBoundingInfo();
  20958. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20959. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20960. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20961. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20962. return null;
  20963. }
  20964. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20965. };
  20966. /**
  20967. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20968. * @param projected sets as the (x,y,z) world projection on the facet
  20969. * @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
  20970. * @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
  20971. * @param x defines x coordinate
  20972. * @param y defines y coordinate
  20973. * @param z defines z coordinate
  20974. * @returns the face index if found (or null instead)
  20975. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20976. */
  20977. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20978. if (checkFace === void 0) { checkFace = false; }
  20979. if (facing === void 0) { facing = true; }
  20980. var world = this.getWorldMatrix();
  20981. var invMat = BABYLON.Tmp.Matrix[5];
  20982. world.invertToRef(invMat);
  20983. var invVect = BABYLON.Tmp.Vector3[8];
  20984. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20985. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20986. if (projected) {
  20987. // tranform the local computed projected vector to world coordinates
  20988. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20989. }
  20990. return closest;
  20991. };
  20992. /**
  20993. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  20994. * @param projected sets as the (x,y,z) local projection on the facet
  20995. * @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
  20996. * @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
  20997. * @param x defines x coordinate
  20998. * @param y defines y coordinate
  20999. * @param z defines z coordinate
  21000. * @returns the face index if found (or null instead)
  21001. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21002. */
  21003. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21004. if (checkFace === void 0) { checkFace = false; }
  21005. if (facing === void 0) { facing = true; }
  21006. var closest = null;
  21007. var tmpx = 0.0;
  21008. var tmpy = 0.0;
  21009. var tmpz = 0.0;
  21010. var d = 0.0; // tmp dot facet normal * facet position
  21011. var t0 = 0.0;
  21012. var projx = 0.0;
  21013. var projy = 0.0;
  21014. var projz = 0.0;
  21015. // Get all the facets in the same partitioning block than (x, y, z)
  21016. var facetPositions = this.getFacetLocalPositions();
  21017. var facetNormals = this.getFacetLocalNormals();
  21018. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21019. if (!facetsInBlock) {
  21020. return null;
  21021. }
  21022. // Get the closest facet to (x, y, z)
  21023. var shortest = Number.MAX_VALUE; // init distance vars
  21024. var tmpDistance = shortest;
  21025. var fib; // current facet in the block
  21026. var norm; // current facet normal
  21027. var p0; // current facet barycenter position
  21028. // loop on all the facets in the current partitioning block
  21029. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21030. fib = facetsInBlock[idx];
  21031. norm = facetNormals[fib];
  21032. p0 = facetPositions[fib];
  21033. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21034. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21035. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21036. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21037. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21038. projx = x + norm.x * t0;
  21039. projy = y + norm.y * t0;
  21040. projz = z + norm.z * t0;
  21041. tmpx = projx - x;
  21042. tmpy = projy - y;
  21043. tmpz = projz - z;
  21044. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21045. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21046. shortest = tmpDistance;
  21047. closest = fib;
  21048. if (projected) {
  21049. projected.x = projx;
  21050. projected.y = projy;
  21051. projected.z = projz;
  21052. }
  21053. }
  21054. }
  21055. }
  21056. return closest;
  21057. };
  21058. /**
  21059. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21060. * @returns the parameters
  21061. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21062. */
  21063. AbstractMesh.prototype.getFacetDataParameters = function () {
  21064. return this._facetParameters;
  21065. };
  21066. /**
  21067. * Disables the feature FacetData and frees the related memory
  21068. * @returns the current mesh
  21069. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21070. */
  21071. AbstractMesh.prototype.disableFacetData = function () {
  21072. if (this._facetDataEnabled) {
  21073. this._facetDataEnabled = false;
  21074. this._facetPositions = new Array();
  21075. this._facetNormals = new Array();
  21076. this._facetPartitioning = new Array();
  21077. this._facetParameters = null;
  21078. this._depthSortedIndices = new Uint32Array(0);
  21079. }
  21080. return this;
  21081. };
  21082. /**
  21083. * Updates the AbstractMesh indices array
  21084. * @param indices defines the data source
  21085. * @returns the current mesh
  21086. */
  21087. AbstractMesh.prototype.updateIndices = function (indices) {
  21088. return this;
  21089. };
  21090. /**
  21091. * Creates new normals data for the mesh
  21092. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21093. * @returns the current mesh
  21094. */
  21095. AbstractMesh.prototype.createNormals = function (updatable) {
  21096. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21097. var indices = this.getIndices();
  21098. var normals;
  21099. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21100. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21101. }
  21102. else {
  21103. normals = [];
  21104. }
  21105. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21106. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21107. return this;
  21108. };
  21109. /**
  21110. * Align the mesh with a normal
  21111. * @param normal defines the normal to use
  21112. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21113. * @returns the current mesh
  21114. */
  21115. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21116. if (!upDirection) {
  21117. upDirection = BABYLON.Axis.Y;
  21118. }
  21119. var axisX = BABYLON.Tmp.Vector3[0];
  21120. var axisZ = BABYLON.Tmp.Vector3[1];
  21121. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21122. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21123. if (this.rotationQuaternion) {
  21124. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21125. }
  21126. else {
  21127. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21128. }
  21129. return this;
  21130. };
  21131. /** @hidden */
  21132. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21133. var engine = this.getEngine();
  21134. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21135. this._isOccluded = false;
  21136. return;
  21137. }
  21138. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21139. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21140. if (isOcclusionQueryAvailable) {
  21141. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21142. this._isOcclusionQueryInProgress = false;
  21143. this._occlusionInternalRetryCounter = 0;
  21144. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21145. }
  21146. else {
  21147. this._occlusionInternalRetryCounter++;
  21148. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21149. this._isOcclusionQueryInProgress = false;
  21150. this._occlusionInternalRetryCounter = 0;
  21151. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21152. // if strict continue the last state of the object.
  21153. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21154. }
  21155. else {
  21156. return;
  21157. }
  21158. }
  21159. }
  21160. var scene = this.getScene();
  21161. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21162. if (!this._occlusionQuery) {
  21163. this._occlusionQuery = engine.createQuery();
  21164. }
  21165. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21166. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21167. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21168. this._isOcclusionQueryInProgress = true;
  21169. };
  21170. /** No occlusion */
  21171. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21172. /** Occlusion set to optimisitic */
  21173. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21174. /** Occlusion set to strict */
  21175. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21176. /** Use an accurante occlusion algorithm */
  21177. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21178. /** Use a conservative occlusion algorithm */
  21179. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21180. return AbstractMesh;
  21181. }(BABYLON.TransformNode));
  21182. BABYLON.AbstractMesh = AbstractMesh;
  21183. })(BABYLON || (BABYLON = {}));
  21184. //# sourceMappingURL=babylon.abstractMesh.js.map
  21185. var BABYLON;
  21186. (function (BABYLON) {
  21187. /**
  21188. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21189. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21190. * 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.
  21191. */
  21192. var Light = /** @class */ (function (_super) {
  21193. __extends(Light, _super);
  21194. /**
  21195. * Creates a Light object in the scene.
  21196. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21197. * @param name The firendly name of the light
  21198. * @param scene The scene the light belongs too
  21199. */
  21200. function Light(name, scene) {
  21201. var _this = _super.call(this, name, scene) || this;
  21202. /**
  21203. * Diffuse gives the basic color to an object.
  21204. */
  21205. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21206. /**
  21207. * Specular produces a highlight color on an object.
  21208. * Note: This is note affecting PBR materials.
  21209. */
  21210. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21211. /**
  21212. * Strength of the light.
  21213. * Note: By default it is define in the framework own unit.
  21214. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21215. */
  21216. _this.intensity = 1.0;
  21217. /**
  21218. * Defines how far from the source the light is impacting in scene units.
  21219. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21220. */
  21221. _this.range = Number.MAX_VALUE;
  21222. /**
  21223. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21224. * of light.
  21225. */
  21226. _this._photometricScale = 1.0;
  21227. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21228. _this._radius = 0.00001;
  21229. /**
  21230. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21231. * exceeding the number allowed of the materials.
  21232. */
  21233. _this.renderPriority = 0;
  21234. /**
  21235. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21236. * the current shadow generator.
  21237. */
  21238. _this.shadowEnabled = true;
  21239. _this._excludeWithLayerMask = 0;
  21240. _this._includeOnlyWithLayerMask = 0;
  21241. _this._lightmapMode = 0;
  21242. /**
  21243. * @hidden Internal use only.
  21244. */
  21245. _this._excludedMeshesIds = new Array();
  21246. /**
  21247. * @hidden Internal use only.
  21248. */
  21249. _this._includedOnlyMeshesIds = new Array();
  21250. _this.getScene().addLight(_this);
  21251. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21252. _this._buildUniformLayout();
  21253. _this.includedOnlyMeshes = new Array();
  21254. _this.excludedMeshes = new Array();
  21255. _this._resyncMeshes();
  21256. return _this;
  21257. }
  21258. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21259. /**
  21260. * If every light affecting the material is in this lightmapMode,
  21261. * material.lightmapTexture adds or multiplies
  21262. * (depends on material.useLightmapAsShadowmap)
  21263. * after every other light calculations.
  21264. */
  21265. get: function () {
  21266. return Light._LIGHTMAP_DEFAULT;
  21267. },
  21268. enumerable: true,
  21269. configurable: true
  21270. });
  21271. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21272. /**
  21273. * material.lightmapTexture as only diffuse lighting from this light
  21274. * adds only specular lighting from this light
  21275. * adds dynamic shadows
  21276. */
  21277. get: function () {
  21278. return Light._LIGHTMAP_SPECULAR;
  21279. },
  21280. enumerable: true,
  21281. configurable: true
  21282. });
  21283. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21284. /**
  21285. * material.lightmapTexture as only lighting
  21286. * no light calculation from this light
  21287. * only adds dynamic shadows from this light
  21288. */
  21289. get: function () {
  21290. return Light._LIGHTMAP_SHADOWSONLY;
  21291. },
  21292. enumerable: true,
  21293. configurable: true
  21294. });
  21295. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21296. /**
  21297. * Each light type uses the default quantity according to its type:
  21298. * point/spot lights use luminous intensity
  21299. * directional lights use illuminance
  21300. */
  21301. get: function () {
  21302. return Light._INTENSITYMODE_AUTOMATIC;
  21303. },
  21304. enumerable: true,
  21305. configurable: true
  21306. });
  21307. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21308. /**
  21309. * lumen (lm)
  21310. */
  21311. get: function () {
  21312. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21313. },
  21314. enumerable: true,
  21315. configurable: true
  21316. });
  21317. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21318. /**
  21319. * candela (lm/sr)
  21320. */
  21321. get: function () {
  21322. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21323. },
  21324. enumerable: true,
  21325. configurable: true
  21326. });
  21327. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21328. /**
  21329. * lux (lm/m^2)
  21330. */
  21331. get: function () {
  21332. return Light._INTENSITYMODE_ILLUMINANCE;
  21333. },
  21334. enumerable: true,
  21335. configurable: true
  21336. });
  21337. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21338. /**
  21339. * nit (cd/m^2)
  21340. */
  21341. get: function () {
  21342. return Light._INTENSITYMODE_LUMINANCE;
  21343. },
  21344. enumerable: true,
  21345. configurable: true
  21346. });
  21347. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21348. /**
  21349. * Light type const id of the point light.
  21350. */
  21351. get: function () {
  21352. return Light._LIGHTTYPEID_POINTLIGHT;
  21353. },
  21354. enumerable: true,
  21355. configurable: true
  21356. });
  21357. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21358. /**
  21359. * Light type const id of the directional light.
  21360. */
  21361. get: function () {
  21362. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21363. },
  21364. enumerable: true,
  21365. configurable: true
  21366. });
  21367. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21368. /**
  21369. * Light type const id of the spot light.
  21370. */
  21371. get: function () {
  21372. return Light._LIGHTTYPEID_SPOTLIGHT;
  21373. },
  21374. enumerable: true,
  21375. configurable: true
  21376. });
  21377. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21378. /**
  21379. * Light type const id of the hemispheric light.
  21380. */
  21381. get: function () {
  21382. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21383. },
  21384. enumerable: true,
  21385. configurable: true
  21386. });
  21387. Object.defineProperty(Light.prototype, "intensityMode", {
  21388. /**
  21389. * Gets the photometric scale used to interpret the intensity.
  21390. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21391. */
  21392. get: function () {
  21393. return this._intensityMode;
  21394. },
  21395. /**
  21396. * Sets the photometric scale used to interpret the intensity.
  21397. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21398. */
  21399. set: function (value) {
  21400. this._intensityMode = value;
  21401. this._computePhotometricScale();
  21402. },
  21403. enumerable: true,
  21404. configurable: true
  21405. });
  21406. ;
  21407. ;
  21408. Object.defineProperty(Light.prototype, "radius", {
  21409. /**
  21410. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21411. */
  21412. get: function () {
  21413. return this._radius;
  21414. },
  21415. /**
  21416. * sets the light radius used by PBR Materials to simulate soft area lights.
  21417. */
  21418. set: function (value) {
  21419. this._radius = value;
  21420. this._computePhotometricScale();
  21421. },
  21422. enumerable: true,
  21423. configurable: true
  21424. });
  21425. ;
  21426. ;
  21427. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21428. /**
  21429. * Gets the only meshes impacted by this light.
  21430. */
  21431. get: function () {
  21432. return this._includedOnlyMeshes;
  21433. },
  21434. /**
  21435. * Sets the only meshes impacted by this light.
  21436. */
  21437. set: function (value) {
  21438. this._includedOnlyMeshes = value;
  21439. this._hookArrayForIncludedOnly(value);
  21440. },
  21441. enumerable: true,
  21442. configurable: true
  21443. });
  21444. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21445. /**
  21446. * Gets the meshes not impacted by this light.
  21447. */
  21448. get: function () {
  21449. return this._excludedMeshes;
  21450. },
  21451. /**
  21452. * Sets the meshes not impacted by this light.
  21453. */
  21454. set: function (value) {
  21455. this._excludedMeshes = value;
  21456. this._hookArrayForExcluded(value);
  21457. },
  21458. enumerable: true,
  21459. configurable: true
  21460. });
  21461. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21462. /**
  21463. * Gets the layer id use to find what meshes are not impacted by the light.
  21464. * Inactive if 0
  21465. */
  21466. get: function () {
  21467. return this._excludeWithLayerMask;
  21468. },
  21469. /**
  21470. * Sets the layer id use to find what meshes are not impacted by the light.
  21471. * Inactive if 0
  21472. */
  21473. set: function (value) {
  21474. this._excludeWithLayerMask = value;
  21475. this._resyncMeshes();
  21476. },
  21477. enumerable: true,
  21478. configurable: true
  21479. });
  21480. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21481. /**
  21482. * Gets the layer id use to find what meshes are impacted by the light.
  21483. * Inactive if 0
  21484. */
  21485. get: function () {
  21486. return this._includeOnlyWithLayerMask;
  21487. },
  21488. /**
  21489. * Sets the layer id use to find what meshes are impacted by the light.
  21490. * Inactive if 0
  21491. */
  21492. set: function (value) {
  21493. this._includeOnlyWithLayerMask = value;
  21494. this._resyncMeshes();
  21495. },
  21496. enumerable: true,
  21497. configurable: true
  21498. });
  21499. Object.defineProperty(Light.prototype, "lightmapMode", {
  21500. /**
  21501. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21502. */
  21503. get: function () {
  21504. return this._lightmapMode;
  21505. },
  21506. /**
  21507. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21508. */
  21509. set: function (value) {
  21510. if (this._lightmapMode === value) {
  21511. return;
  21512. }
  21513. this._lightmapMode = value;
  21514. this._markMeshesAsLightDirty();
  21515. },
  21516. enumerable: true,
  21517. configurable: true
  21518. });
  21519. /**
  21520. * Returns the string "Light".
  21521. * @returns the class name
  21522. */
  21523. Light.prototype.getClassName = function () {
  21524. return "Light";
  21525. };
  21526. /**
  21527. * Converts the light information to a readable string for debug purpose.
  21528. * @param fullDetails Supports for multiple levels of logging within scene loading
  21529. * @returns the human readable light info
  21530. */
  21531. Light.prototype.toString = function (fullDetails) {
  21532. var ret = "Name: " + this.name;
  21533. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21534. if (this.animations) {
  21535. for (var i = 0; i < this.animations.length; i++) {
  21536. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21537. }
  21538. }
  21539. if (fullDetails) {
  21540. }
  21541. return ret;
  21542. };
  21543. /**
  21544. * Set the enabled state of this node.
  21545. * @param value - the new enabled state
  21546. */
  21547. Light.prototype.setEnabled = function (value) {
  21548. _super.prototype.setEnabled.call(this, value);
  21549. this._resyncMeshes();
  21550. };
  21551. /**
  21552. * Returns the Light associated shadow generator if any.
  21553. * @return the associated shadow generator.
  21554. */
  21555. Light.prototype.getShadowGenerator = function () {
  21556. return this._shadowGenerator;
  21557. };
  21558. /**
  21559. * Returns a Vector3, the absolute light position in the World.
  21560. * @returns the world space position of the light
  21561. */
  21562. Light.prototype.getAbsolutePosition = function () {
  21563. return BABYLON.Vector3.Zero();
  21564. };
  21565. /**
  21566. * Specifies if the light will affect the passed mesh.
  21567. * @param mesh The mesh to test against the light
  21568. * @return true the mesh is affected otherwise, false.
  21569. */
  21570. Light.prototype.canAffectMesh = function (mesh) {
  21571. if (!mesh) {
  21572. return true;
  21573. }
  21574. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21575. return false;
  21576. }
  21577. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21578. return false;
  21579. }
  21580. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21581. return false;
  21582. }
  21583. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21584. return false;
  21585. }
  21586. return true;
  21587. };
  21588. /**
  21589. * Computes and Returns the light World matrix.
  21590. * @returns the world matrix
  21591. */
  21592. Light.prototype.getWorldMatrix = function () {
  21593. this._currentRenderId = this.getScene().getRenderId();
  21594. this._childRenderId = this._currentRenderId;
  21595. var worldMatrix = this._getWorldMatrix();
  21596. if (this.parent && this.parent.getWorldMatrix) {
  21597. if (!this._parentedWorldMatrix) {
  21598. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21599. }
  21600. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21601. this._markSyncedWithParent();
  21602. return this._parentedWorldMatrix;
  21603. }
  21604. return worldMatrix;
  21605. };
  21606. /**
  21607. * Sort function to order lights for rendering.
  21608. * @param a First Light object to compare to second.
  21609. * @param b Second Light object to compare first.
  21610. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21611. */
  21612. Light.CompareLightsPriority = function (a, b) {
  21613. //shadow-casting lights have priority over non-shadow-casting lights
  21614. //the renderPrioirty is a secondary sort criterion
  21615. if (a.shadowEnabled !== b.shadowEnabled) {
  21616. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21617. }
  21618. return b.renderPriority - a.renderPriority;
  21619. };
  21620. /**
  21621. * Releases resources associated with this node.
  21622. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21623. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21624. */
  21625. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21626. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21627. if (this._shadowGenerator) {
  21628. this._shadowGenerator.dispose();
  21629. this._shadowGenerator = null;
  21630. }
  21631. // Animations
  21632. this.getScene().stopAnimation(this);
  21633. // Remove from meshes
  21634. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21635. var mesh = _a[_i];
  21636. mesh._removeLightSource(this);
  21637. }
  21638. this._uniformBuffer.dispose();
  21639. // Remove from scene
  21640. this.getScene().removeLight(this);
  21641. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21642. };
  21643. /**
  21644. * Returns the light type ID (integer).
  21645. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21646. */
  21647. Light.prototype.getTypeID = function () {
  21648. return 0;
  21649. };
  21650. /**
  21651. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21652. * @returns the scaled intensity in intensity mode unit
  21653. */
  21654. Light.prototype.getScaledIntensity = function () {
  21655. return this._photometricScale * this.intensity;
  21656. };
  21657. /**
  21658. * Returns a new Light object, named "name", from the current one.
  21659. * @param name The name of the cloned light
  21660. * @returns the new created light
  21661. */
  21662. Light.prototype.clone = function (name) {
  21663. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21664. if (!constructor) {
  21665. return null;
  21666. }
  21667. return BABYLON.SerializationHelper.Clone(constructor, this);
  21668. };
  21669. /**
  21670. * Serializes the current light into a Serialization object.
  21671. * @returns the serialized object.
  21672. */
  21673. Light.prototype.serialize = function () {
  21674. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21675. // Type
  21676. serializationObject.type = this.getTypeID();
  21677. // Parent
  21678. if (this.parent) {
  21679. serializationObject.parentId = this.parent.id;
  21680. }
  21681. // Inclusion / exclusions
  21682. if (this.excludedMeshes.length > 0) {
  21683. serializationObject.excludedMeshesIds = [];
  21684. this.excludedMeshes.forEach(function (mesh) {
  21685. serializationObject.excludedMeshesIds.push(mesh.id);
  21686. });
  21687. }
  21688. if (this.includedOnlyMeshes.length > 0) {
  21689. serializationObject.includedOnlyMeshesIds = [];
  21690. this.includedOnlyMeshes.forEach(function (mesh) {
  21691. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21692. });
  21693. }
  21694. // Animations
  21695. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21696. serializationObject.ranges = this.serializeAnimationRanges();
  21697. return serializationObject;
  21698. };
  21699. /**
  21700. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21701. * This new light is named "name" and added to the passed scene.
  21702. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21703. * @param name The friendly name of the light
  21704. * @param scene The scene the new light will belong to
  21705. * @returns the constructor function
  21706. */
  21707. Light.GetConstructorFromName = function (type, name, scene) {
  21708. switch (type) {
  21709. case 0:
  21710. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21711. case 1:
  21712. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21713. case 2:
  21714. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21715. case 3:
  21716. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21717. }
  21718. return null;
  21719. };
  21720. /**
  21721. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21722. * @param parsedLight The JSON representation of the light
  21723. * @param scene The scene to create the parsed light in
  21724. * @returns the created light after parsing
  21725. */
  21726. Light.Parse = function (parsedLight, scene) {
  21727. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21728. if (!constructor) {
  21729. return null;
  21730. }
  21731. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21732. // Inclusion / exclusions
  21733. if (parsedLight.excludedMeshesIds) {
  21734. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21735. }
  21736. if (parsedLight.includedOnlyMeshesIds) {
  21737. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21738. }
  21739. // Parent
  21740. if (parsedLight.parentId) {
  21741. light._waitingParentId = parsedLight.parentId;
  21742. }
  21743. // Animations
  21744. if (parsedLight.animations) {
  21745. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21746. var parsedAnimation = parsedLight.animations[animationIndex];
  21747. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21748. }
  21749. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21750. }
  21751. if (parsedLight.autoAnimate) {
  21752. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21753. }
  21754. return light;
  21755. };
  21756. Light.prototype._hookArrayForExcluded = function (array) {
  21757. var _this = this;
  21758. var oldPush = array.push;
  21759. array.push = function () {
  21760. var items = [];
  21761. for (var _i = 0; _i < arguments.length; _i++) {
  21762. items[_i] = arguments[_i];
  21763. }
  21764. var result = oldPush.apply(array, items);
  21765. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21766. var item = items_1[_a];
  21767. item._resyncLighSource(_this);
  21768. }
  21769. return result;
  21770. };
  21771. var oldSplice = array.splice;
  21772. array.splice = function (index, deleteCount) {
  21773. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21774. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21775. var item = deleted_1[_i];
  21776. item._resyncLighSource(_this);
  21777. }
  21778. return deleted;
  21779. };
  21780. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21781. var item = array_1[_i];
  21782. item._resyncLighSource(this);
  21783. }
  21784. };
  21785. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21786. var _this = this;
  21787. var oldPush = array.push;
  21788. array.push = function () {
  21789. var items = [];
  21790. for (var _i = 0; _i < arguments.length; _i++) {
  21791. items[_i] = arguments[_i];
  21792. }
  21793. var result = oldPush.apply(array, items);
  21794. _this._resyncMeshes();
  21795. return result;
  21796. };
  21797. var oldSplice = array.splice;
  21798. array.splice = function (index, deleteCount) {
  21799. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21800. _this._resyncMeshes();
  21801. return deleted;
  21802. };
  21803. this._resyncMeshes();
  21804. };
  21805. Light.prototype._resyncMeshes = function () {
  21806. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21807. var mesh = _a[_i];
  21808. mesh._resyncLighSource(this);
  21809. }
  21810. };
  21811. /**
  21812. * Forces the meshes to update their light related information in their rendering used effects
  21813. * @hidden Internal Use Only
  21814. */
  21815. Light.prototype._markMeshesAsLightDirty = function () {
  21816. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21817. var mesh = _a[_i];
  21818. if (mesh._lightSources.indexOf(this) !== -1) {
  21819. mesh._markSubMeshesAsLightDirty();
  21820. }
  21821. }
  21822. };
  21823. /**
  21824. * Recomputes the cached photometric scale if needed.
  21825. */
  21826. Light.prototype._computePhotometricScale = function () {
  21827. this._photometricScale = this._getPhotometricScale();
  21828. this.getScene().resetCachedMaterial();
  21829. };
  21830. /**
  21831. * Returns the Photometric Scale according to the light type and intensity mode.
  21832. */
  21833. Light.prototype._getPhotometricScale = function () {
  21834. var photometricScale = 0.0;
  21835. var lightTypeID = this.getTypeID();
  21836. //get photometric mode
  21837. var photometricMode = this.intensityMode;
  21838. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21839. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21840. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21841. }
  21842. else {
  21843. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21844. }
  21845. }
  21846. //compute photometric scale
  21847. switch (lightTypeID) {
  21848. case Light.LIGHTTYPEID_POINTLIGHT:
  21849. case Light.LIGHTTYPEID_SPOTLIGHT:
  21850. switch (photometricMode) {
  21851. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21852. photometricScale = 1.0 / (4.0 * Math.PI);
  21853. break;
  21854. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21855. photometricScale = 1.0;
  21856. break;
  21857. case Light.INTENSITYMODE_LUMINANCE:
  21858. photometricScale = this.radius * this.radius;
  21859. break;
  21860. }
  21861. break;
  21862. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21863. switch (photometricMode) {
  21864. case Light.INTENSITYMODE_ILLUMINANCE:
  21865. photometricScale = 1.0;
  21866. break;
  21867. case Light.INTENSITYMODE_LUMINANCE:
  21868. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21869. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21870. var apexAngleRadians = this.radius;
  21871. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21872. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21873. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21874. photometricScale = solidAngle;
  21875. break;
  21876. }
  21877. break;
  21878. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21879. // No fall off in hemisperic light.
  21880. photometricScale = 1.0;
  21881. break;
  21882. }
  21883. return photometricScale;
  21884. };
  21885. /**
  21886. * Reorder the light in the scene according to their defined priority.
  21887. * @hidden Internal Use Only
  21888. */
  21889. Light.prototype._reorderLightsInScene = function () {
  21890. var scene = this.getScene();
  21891. if (this._renderPriority != 0) {
  21892. scene.requireLightSorting = true;
  21893. }
  21894. this.getScene().sortLightsByPriority();
  21895. };
  21896. //lightmapMode Consts
  21897. Light._LIGHTMAP_DEFAULT = 0;
  21898. Light._LIGHTMAP_SPECULAR = 1;
  21899. Light._LIGHTMAP_SHADOWSONLY = 2;
  21900. // Intensity Mode Consts
  21901. Light._INTENSITYMODE_AUTOMATIC = 0;
  21902. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21903. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21904. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21905. Light._INTENSITYMODE_LUMINANCE = 4;
  21906. // Light types ids const.
  21907. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21908. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21909. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21910. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21911. __decorate([
  21912. BABYLON.serializeAsColor3()
  21913. ], Light.prototype, "diffuse", void 0);
  21914. __decorate([
  21915. BABYLON.serializeAsColor3()
  21916. ], Light.prototype, "specular", void 0);
  21917. __decorate([
  21918. BABYLON.serialize()
  21919. ], Light.prototype, "intensity", void 0);
  21920. __decorate([
  21921. BABYLON.serialize()
  21922. ], Light.prototype, "range", void 0);
  21923. __decorate([
  21924. BABYLON.serialize()
  21925. ], Light.prototype, "intensityMode", null);
  21926. __decorate([
  21927. BABYLON.serialize()
  21928. ], Light.prototype, "radius", null);
  21929. __decorate([
  21930. BABYLON.serialize()
  21931. ], Light.prototype, "_renderPriority", void 0);
  21932. __decorate([
  21933. BABYLON.expandToProperty("_reorderLightsInScene")
  21934. ], Light.prototype, "renderPriority", void 0);
  21935. __decorate([
  21936. BABYLON.serialize()
  21937. ], Light.prototype, "shadowEnabled", void 0);
  21938. __decorate([
  21939. BABYLON.serialize("excludeWithLayerMask")
  21940. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21941. __decorate([
  21942. BABYLON.serialize("includeOnlyWithLayerMask")
  21943. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21944. __decorate([
  21945. BABYLON.serialize("lightmapMode")
  21946. ], Light.prototype, "_lightmapMode", void 0);
  21947. return Light;
  21948. }(BABYLON.Node));
  21949. BABYLON.Light = Light;
  21950. })(BABYLON || (BABYLON = {}));
  21951. //# sourceMappingURL=babylon.light.js.map
  21952. var BABYLON;
  21953. (function (BABYLON) {
  21954. var Camera = /** @class */ (function (_super) {
  21955. __extends(Camera, _super);
  21956. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21957. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21958. var _this = _super.call(this, name, scene) || this;
  21959. /**
  21960. * The vector the camera should consider as up.
  21961. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21962. */
  21963. _this.upVector = BABYLON.Vector3.Up();
  21964. _this.orthoLeft = null;
  21965. _this.orthoRight = null;
  21966. _this.orthoBottom = null;
  21967. _this.orthoTop = null;
  21968. /**
  21969. * FOV is set in Radians. (default is 0.8)
  21970. */
  21971. _this.fov = 0.8;
  21972. _this.minZ = 1;
  21973. _this.maxZ = 10000.0;
  21974. _this.inertia = 0.9;
  21975. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21976. _this.isIntermediate = false;
  21977. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21978. /**
  21979. * Restricts the camera to viewing objects with the same layerMask.
  21980. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21981. */
  21982. _this.layerMask = 0x0FFFFFFF;
  21983. /**
  21984. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21985. */
  21986. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21987. // Camera rig members
  21988. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21989. _this._rigCameras = new Array();
  21990. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21991. _this._skipRendering = false;
  21992. _this.customRenderTargets = new Array();
  21993. // Observables
  21994. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21995. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21996. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21997. _this.onRestoreStateObservable = new BABYLON.Observable();
  21998. // Cache
  21999. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22000. _this._projectionMatrix = new BABYLON.Matrix();
  22001. _this._doNotComputeProjectionMatrix = false;
  22002. _this._worldMatrix = BABYLON.Matrix.Identity();
  22003. _this._postProcesses = new Array();
  22004. _this._transformMatrix = BABYLON.Matrix.Zero();
  22005. _this._activeMeshes = new BABYLON.SmartArray(256);
  22006. _this._globalPosition = BABYLON.Vector3.Zero();
  22007. _this._refreshFrustumPlanes = true;
  22008. _this.getScene().addCamera(_this);
  22009. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22010. _this.getScene().activeCamera = _this;
  22011. }
  22012. _this.position = position;
  22013. return _this;
  22014. }
  22015. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22016. get: function () {
  22017. return Camera._PERSPECTIVE_CAMERA;
  22018. },
  22019. enumerable: true,
  22020. configurable: true
  22021. });
  22022. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22023. get: function () {
  22024. return Camera._ORTHOGRAPHIC_CAMERA;
  22025. },
  22026. enumerable: true,
  22027. configurable: true
  22028. });
  22029. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22030. /**
  22031. * This is the default FOV mode for perspective cameras.
  22032. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22033. *
  22034. */
  22035. get: function () {
  22036. return Camera._FOVMODE_VERTICAL_FIXED;
  22037. },
  22038. enumerable: true,
  22039. configurable: true
  22040. });
  22041. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22042. /**
  22043. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22044. *
  22045. */
  22046. get: function () {
  22047. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22048. },
  22049. enumerable: true,
  22050. configurable: true
  22051. });
  22052. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22053. get: function () {
  22054. return Camera._RIG_MODE_NONE;
  22055. },
  22056. enumerable: true,
  22057. configurable: true
  22058. });
  22059. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22060. get: function () {
  22061. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22062. },
  22063. enumerable: true,
  22064. configurable: true
  22065. });
  22066. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22067. get: function () {
  22068. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22074. get: function () {
  22075. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22081. get: function () {
  22082. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22083. },
  22084. enumerable: true,
  22085. configurable: true
  22086. });
  22087. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22088. get: function () {
  22089. return Camera._RIG_MODE_VR;
  22090. },
  22091. enumerable: true,
  22092. configurable: true
  22093. });
  22094. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22095. get: function () {
  22096. return Camera._RIG_MODE_WEBVR;
  22097. },
  22098. enumerable: true,
  22099. configurable: true
  22100. });
  22101. /**
  22102. * Store current camera state (fov, position, etc..)
  22103. */
  22104. Camera.prototype.storeState = function () {
  22105. this._stateStored = true;
  22106. this._storedFov = this.fov;
  22107. return this;
  22108. };
  22109. /**
  22110. * Restores the camera state values if it has been stored. You must call storeState() first
  22111. */
  22112. Camera.prototype._restoreStateValues = function () {
  22113. if (!this._stateStored) {
  22114. return false;
  22115. }
  22116. this.fov = this._storedFov;
  22117. return true;
  22118. };
  22119. /**
  22120. * Restored camera state. You must call storeState() first
  22121. */
  22122. Camera.prototype.restoreState = function () {
  22123. if (this._restoreStateValues()) {
  22124. this.onRestoreStateObservable.notifyObservers(this);
  22125. return true;
  22126. }
  22127. return false;
  22128. };
  22129. Camera.prototype.getClassName = function () {
  22130. return "Camera";
  22131. };
  22132. /**
  22133. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22134. */
  22135. Camera.prototype.toString = function (fullDetails) {
  22136. var ret = "Name: " + this.name;
  22137. ret += ", type: " + this.getClassName();
  22138. if (this.animations) {
  22139. for (var i = 0; i < this.animations.length; i++) {
  22140. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22141. }
  22142. }
  22143. if (fullDetails) {
  22144. }
  22145. return ret;
  22146. };
  22147. Object.defineProperty(Camera.prototype, "globalPosition", {
  22148. get: function () {
  22149. return this._globalPosition;
  22150. },
  22151. enumerable: true,
  22152. configurable: true
  22153. });
  22154. Camera.prototype.getActiveMeshes = function () {
  22155. return this._activeMeshes;
  22156. };
  22157. Camera.prototype.isActiveMesh = function (mesh) {
  22158. return (this._activeMeshes.indexOf(mesh) !== -1);
  22159. };
  22160. /**
  22161. * Is this camera ready to be used/rendered
  22162. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22163. * @return true if the camera is ready
  22164. */
  22165. Camera.prototype.isReady = function (completeCheck) {
  22166. if (completeCheck === void 0) { completeCheck = false; }
  22167. if (completeCheck) {
  22168. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22169. var pp = _a[_i];
  22170. if (pp && !pp.isReady()) {
  22171. return false;
  22172. }
  22173. }
  22174. }
  22175. return _super.prototype.isReady.call(this, completeCheck);
  22176. };
  22177. //Cache
  22178. Camera.prototype._initCache = function () {
  22179. _super.prototype._initCache.call(this);
  22180. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22181. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22182. this._cache.mode = undefined;
  22183. this._cache.minZ = undefined;
  22184. this._cache.maxZ = undefined;
  22185. this._cache.fov = undefined;
  22186. this._cache.fovMode = undefined;
  22187. this._cache.aspectRatio = undefined;
  22188. this._cache.orthoLeft = undefined;
  22189. this._cache.orthoRight = undefined;
  22190. this._cache.orthoBottom = undefined;
  22191. this._cache.orthoTop = undefined;
  22192. this._cache.renderWidth = undefined;
  22193. this._cache.renderHeight = undefined;
  22194. };
  22195. Camera.prototype._updateCache = function (ignoreParentClass) {
  22196. if (!ignoreParentClass) {
  22197. _super.prototype._updateCache.call(this);
  22198. }
  22199. this._cache.position.copyFrom(this.position);
  22200. this._cache.upVector.copyFrom(this.upVector);
  22201. };
  22202. // Synchronized
  22203. Camera.prototype._isSynchronized = function () {
  22204. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22205. };
  22206. Camera.prototype._isSynchronizedViewMatrix = function () {
  22207. if (!_super.prototype._isSynchronized.call(this))
  22208. return false;
  22209. return this._cache.position.equals(this.position)
  22210. && this._cache.upVector.equals(this.upVector)
  22211. && this.isSynchronizedWithParent();
  22212. };
  22213. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22214. var check = this._cache.mode === this.mode
  22215. && this._cache.minZ === this.minZ
  22216. && this._cache.maxZ === this.maxZ;
  22217. if (!check) {
  22218. return false;
  22219. }
  22220. var engine = this.getEngine();
  22221. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22222. check = this._cache.fov === this.fov
  22223. && this._cache.fovMode === this.fovMode
  22224. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22225. }
  22226. else {
  22227. check = this._cache.orthoLeft === this.orthoLeft
  22228. && this._cache.orthoRight === this.orthoRight
  22229. && this._cache.orthoBottom === this.orthoBottom
  22230. && this._cache.orthoTop === this.orthoTop
  22231. && this._cache.renderWidth === engine.getRenderWidth()
  22232. && this._cache.renderHeight === engine.getRenderHeight();
  22233. }
  22234. return check;
  22235. };
  22236. // Controls
  22237. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22238. };
  22239. Camera.prototype.detachControl = function (element) {
  22240. };
  22241. Camera.prototype.update = function () {
  22242. this._checkInputs();
  22243. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22244. this._updateRigCameras();
  22245. }
  22246. };
  22247. Camera.prototype._checkInputs = function () {
  22248. this.onAfterCheckInputsObservable.notifyObservers(this);
  22249. };
  22250. Object.defineProperty(Camera.prototype, "rigCameras", {
  22251. get: function () {
  22252. return this._rigCameras;
  22253. },
  22254. enumerable: true,
  22255. configurable: true
  22256. });
  22257. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22258. get: function () {
  22259. return this._rigPostProcess;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. /**
  22265. * Internal, gets the first post proces.
  22266. * @returns the first post process to be run on this camera.
  22267. */
  22268. Camera.prototype._getFirstPostProcess = function () {
  22269. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22270. if (this._postProcesses[ppIndex] !== null) {
  22271. return this._postProcesses[ppIndex];
  22272. }
  22273. }
  22274. return null;
  22275. };
  22276. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22277. // invalidate framebuffer
  22278. var firstPostProcess = this._getFirstPostProcess();
  22279. if (firstPostProcess) {
  22280. firstPostProcess.markTextureDirty();
  22281. }
  22282. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22283. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22284. var cam = this._rigCameras[i];
  22285. var rigPostProcess = cam._rigPostProcess;
  22286. // for VR rig, there does not have to be a post process
  22287. if (rigPostProcess) {
  22288. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22289. if (isPass) {
  22290. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22291. cam.isIntermediate = this._postProcesses.length === 0;
  22292. }
  22293. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22294. rigPostProcess.markTextureDirty();
  22295. }
  22296. else {
  22297. cam._postProcesses = this._postProcesses.slice(0);
  22298. }
  22299. }
  22300. };
  22301. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22302. if (insertAt === void 0) { insertAt = null; }
  22303. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22304. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22305. return 0;
  22306. }
  22307. if (insertAt == null || insertAt < 0) {
  22308. this._postProcesses.push(postProcess);
  22309. }
  22310. else if (this._postProcesses[insertAt] === null) {
  22311. this._postProcesses[insertAt] = postProcess;
  22312. }
  22313. else {
  22314. this._postProcesses.splice(insertAt, 0, postProcess);
  22315. }
  22316. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22317. return this._postProcesses.indexOf(postProcess);
  22318. };
  22319. Camera.prototype.detachPostProcess = function (postProcess) {
  22320. var idx = this._postProcesses.indexOf(postProcess);
  22321. if (idx !== -1) {
  22322. this._postProcesses[idx] = null;
  22323. }
  22324. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22325. };
  22326. Camera.prototype.getWorldMatrix = function () {
  22327. if (this._isSynchronizedViewMatrix()) {
  22328. return this._worldMatrix;
  22329. }
  22330. // Getting the the view matrix will also compute the world matrix.
  22331. this.getViewMatrix();
  22332. return this._worldMatrix;
  22333. };
  22334. Camera.prototype._getViewMatrix = function () {
  22335. return BABYLON.Matrix.Identity();
  22336. };
  22337. Camera.prototype.getViewMatrix = function (force) {
  22338. if (!force && this._isSynchronizedViewMatrix()) {
  22339. return this._computedViewMatrix;
  22340. }
  22341. this.updateCache();
  22342. this._computedViewMatrix = this._getViewMatrix();
  22343. this._currentRenderId = this.getScene().getRenderId();
  22344. this._childRenderId = this._currentRenderId;
  22345. this._refreshFrustumPlanes = true;
  22346. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22347. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22348. }
  22349. this.onViewMatrixChangedObservable.notifyObservers(this);
  22350. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22351. return this._computedViewMatrix;
  22352. };
  22353. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22354. this._doNotComputeProjectionMatrix = true;
  22355. if (projection !== undefined) {
  22356. this._projectionMatrix = projection;
  22357. }
  22358. };
  22359. ;
  22360. Camera.prototype.unfreezeProjectionMatrix = function () {
  22361. this._doNotComputeProjectionMatrix = false;
  22362. };
  22363. ;
  22364. Camera.prototype.getProjectionMatrix = function (force) {
  22365. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22366. return this._projectionMatrix;
  22367. }
  22368. // Cache
  22369. this._cache.mode = this.mode;
  22370. this._cache.minZ = this.minZ;
  22371. this._cache.maxZ = this.maxZ;
  22372. // Matrix
  22373. this._refreshFrustumPlanes = true;
  22374. var engine = this.getEngine();
  22375. var scene = this.getScene();
  22376. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22377. this._cache.fov = this.fov;
  22378. this._cache.fovMode = this.fovMode;
  22379. this._cache.aspectRatio = engine.getAspectRatio(this);
  22380. if (this.minZ <= 0) {
  22381. this.minZ = 0.1;
  22382. }
  22383. if (scene.useRightHandedSystem) {
  22384. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22385. }
  22386. else {
  22387. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22388. }
  22389. }
  22390. else {
  22391. var halfWidth = engine.getRenderWidth() / 2.0;
  22392. var halfHeight = engine.getRenderHeight() / 2.0;
  22393. if (scene.useRightHandedSystem) {
  22394. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22395. }
  22396. else {
  22397. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22398. }
  22399. this._cache.orthoLeft = this.orthoLeft;
  22400. this._cache.orthoRight = this.orthoRight;
  22401. this._cache.orthoBottom = this.orthoBottom;
  22402. this._cache.orthoTop = this.orthoTop;
  22403. this._cache.renderWidth = engine.getRenderWidth();
  22404. this._cache.renderHeight = engine.getRenderHeight();
  22405. }
  22406. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22407. return this._projectionMatrix;
  22408. };
  22409. Camera.prototype.getTranformationMatrix = function () {
  22410. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22411. return this._transformMatrix;
  22412. };
  22413. Camera.prototype.updateFrustumPlanes = function () {
  22414. if (!this._refreshFrustumPlanes) {
  22415. return;
  22416. }
  22417. this.getTranformationMatrix();
  22418. if (!this._frustumPlanes) {
  22419. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22420. }
  22421. else {
  22422. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22423. }
  22424. this._refreshFrustumPlanes = false;
  22425. };
  22426. Camera.prototype.isInFrustum = function (target) {
  22427. this.updateFrustumPlanes();
  22428. return target.isInFrustum(this._frustumPlanes);
  22429. };
  22430. Camera.prototype.isCompletelyInFrustum = function (target) {
  22431. this.updateFrustumPlanes();
  22432. return target.isCompletelyInFrustum(this._frustumPlanes);
  22433. };
  22434. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22435. if (length === void 0) { length = 100; }
  22436. if (!transform) {
  22437. transform = this.getWorldMatrix();
  22438. }
  22439. if (!origin) {
  22440. origin = this.position;
  22441. }
  22442. var forward = new BABYLON.Vector3(0, 0, 1);
  22443. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22444. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22445. return new BABYLON.Ray(origin, direction, length);
  22446. };
  22447. /**
  22448. * Releases resources associated with this node.
  22449. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22450. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22451. */
  22452. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22453. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22454. // Observables
  22455. this.onViewMatrixChangedObservable.clear();
  22456. this.onProjectionMatrixChangedObservable.clear();
  22457. this.onAfterCheckInputsObservable.clear();
  22458. this.onRestoreStateObservable.clear();
  22459. // Inputs
  22460. if (this.inputs) {
  22461. this.inputs.clear();
  22462. }
  22463. // Animations
  22464. this.getScene().stopAnimation(this);
  22465. // Remove from scene
  22466. this.getScene().removeCamera(this);
  22467. while (this._rigCameras.length > 0) {
  22468. var camera = this._rigCameras.pop();
  22469. if (camera) {
  22470. camera.dispose();
  22471. }
  22472. }
  22473. // Postprocesses
  22474. if (this._rigPostProcess) {
  22475. this._rigPostProcess.dispose(this);
  22476. this._rigPostProcess = null;
  22477. this._postProcesses = [];
  22478. }
  22479. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22480. this._rigPostProcess = null;
  22481. this._postProcesses = [];
  22482. }
  22483. else {
  22484. var i = this._postProcesses.length;
  22485. while (--i >= 0) {
  22486. var postProcess = this._postProcesses[i];
  22487. if (postProcess) {
  22488. postProcess.dispose(this);
  22489. }
  22490. }
  22491. }
  22492. // Render targets
  22493. var i = this.customRenderTargets.length;
  22494. while (--i >= 0) {
  22495. this.customRenderTargets[i].dispose();
  22496. }
  22497. this.customRenderTargets = [];
  22498. // Active Meshes
  22499. this._activeMeshes.dispose();
  22500. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22501. };
  22502. Object.defineProperty(Camera.prototype, "leftCamera", {
  22503. // ---- Camera rigs section ----
  22504. get: function () {
  22505. if (this._rigCameras.length < 1) {
  22506. return null;
  22507. }
  22508. return this._rigCameras[0];
  22509. },
  22510. enumerable: true,
  22511. configurable: true
  22512. });
  22513. Object.defineProperty(Camera.prototype, "rightCamera", {
  22514. get: function () {
  22515. if (this._rigCameras.length < 2) {
  22516. return null;
  22517. }
  22518. return this._rigCameras[1];
  22519. },
  22520. enumerable: true,
  22521. configurable: true
  22522. });
  22523. Camera.prototype.getLeftTarget = function () {
  22524. if (this._rigCameras.length < 1) {
  22525. return null;
  22526. }
  22527. return this._rigCameras[0].getTarget();
  22528. };
  22529. Camera.prototype.getRightTarget = function () {
  22530. if (this._rigCameras.length < 2) {
  22531. return null;
  22532. }
  22533. return this._rigCameras[1].getTarget();
  22534. };
  22535. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22536. if (this.cameraRigMode === mode) {
  22537. return;
  22538. }
  22539. while (this._rigCameras.length > 0) {
  22540. var camera = this._rigCameras.pop();
  22541. if (camera) {
  22542. camera.dispose();
  22543. }
  22544. }
  22545. this.cameraRigMode = mode;
  22546. this._cameraRigParams = {};
  22547. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22548. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22549. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22550. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22551. // create the rig cameras, unless none
  22552. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22553. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22554. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22555. if (leftCamera && rightCamera) {
  22556. this._rigCameras.push(leftCamera);
  22557. this._rigCameras.push(rightCamera);
  22558. }
  22559. }
  22560. switch (this.cameraRigMode) {
  22561. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22562. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22563. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22564. break;
  22565. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22566. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22567. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22568. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22569. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22570. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22571. break;
  22572. case Camera.RIG_MODE_VR:
  22573. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22574. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22575. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22576. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22577. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22578. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22579. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22580. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22581. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22582. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22583. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22584. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22585. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22586. if (metrics.compensateDistortion) {
  22587. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22588. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22589. }
  22590. break;
  22591. case Camera.RIG_MODE_WEBVR:
  22592. if (rigParams.vrDisplay) {
  22593. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22594. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22595. //Left eye
  22596. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22597. this._rigCameras[0].setCameraRigParameter("left", true);
  22598. //leaving this for future reference
  22599. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22600. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22601. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22602. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22603. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22604. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22605. this._rigCameras[0].parent = this;
  22606. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22607. //Right eye
  22608. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22609. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22610. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22611. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22612. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22613. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22614. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22615. this._rigCameras[1].parent = this;
  22616. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22617. if (Camera.UseAlternateWebVRRendering) {
  22618. this._rigCameras[1]._skipRendering = true;
  22619. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22620. }
  22621. }
  22622. break;
  22623. }
  22624. this._cascadePostProcessesToRigCams();
  22625. this.update();
  22626. };
  22627. Camera.prototype._getVRProjectionMatrix = function () {
  22628. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22629. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22630. return this._projectionMatrix;
  22631. };
  22632. Camera.prototype._updateCameraRotationMatrix = function () {
  22633. //Here for WebVR
  22634. };
  22635. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22636. //Here for WebVR
  22637. };
  22638. /**
  22639. * This function MUST be overwritten by the different WebVR cameras available.
  22640. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22641. */
  22642. Camera.prototype._getWebVRProjectionMatrix = function () {
  22643. return BABYLON.Matrix.Identity();
  22644. };
  22645. /**
  22646. * This function MUST be overwritten by the different WebVR cameras available.
  22647. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22648. */
  22649. Camera.prototype._getWebVRViewMatrix = function () {
  22650. return BABYLON.Matrix.Identity();
  22651. };
  22652. Camera.prototype.setCameraRigParameter = function (name, value) {
  22653. if (!this._cameraRigParams) {
  22654. this._cameraRigParams = {};
  22655. }
  22656. this._cameraRigParams[name] = value;
  22657. //provisionnally:
  22658. if (name === "interaxialDistance") {
  22659. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22660. }
  22661. };
  22662. /**
  22663. * needs to be overridden by children so sub has required properties to be copied
  22664. */
  22665. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22666. return null;
  22667. };
  22668. /**
  22669. * May need to be overridden by children
  22670. */
  22671. Camera.prototype._updateRigCameras = function () {
  22672. for (var i = 0; i < this._rigCameras.length; i++) {
  22673. this._rigCameras[i].minZ = this.minZ;
  22674. this._rigCameras[i].maxZ = this.maxZ;
  22675. this._rigCameras[i].fov = this.fov;
  22676. }
  22677. // only update viewport when ANAGLYPH
  22678. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22679. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22680. }
  22681. };
  22682. Camera.prototype._setupInputs = function () {
  22683. };
  22684. Camera.prototype.serialize = function () {
  22685. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22686. // Type
  22687. serializationObject.type = this.getClassName();
  22688. // Parent
  22689. if (this.parent) {
  22690. serializationObject.parentId = this.parent.id;
  22691. }
  22692. if (this.inputs) {
  22693. this.inputs.serialize(serializationObject);
  22694. }
  22695. // Animations
  22696. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22697. serializationObject.ranges = this.serializeAnimationRanges();
  22698. return serializationObject;
  22699. };
  22700. Camera.prototype.clone = function (name) {
  22701. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22702. };
  22703. Camera.prototype.getDirection = function (localAxis) {
  22704. var result = BABYLON.Vector3.Zero();
  22705. this.getDirectionToRef(localAxis, result);
  22706. return result;
  22707. };
  22708. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22709. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22710. };
  22711. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22712. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22713. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22714. switch (type) {
  22715. case "ArcRotateCamera":
  22716. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22717. case "DeviceOrientationCamera":
  22718. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22719. case "FollowCamera":
  22720. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22721. case "ArcFollowCamera":
  22722. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22723. case "GamepadCamera":
  22724. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22725. case "TouchCamera":
  22726. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22727. case "VirtualJoysticksCamera":
  22728. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22729. case "WebVRFreeCamera":
  22730. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22731. case "WebVRGamepadCamera":
  22732. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22733. case "VRDeviceOrientationFreeCamera":
  22734. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22735. case "VRDeviceOrientationGamepadCamera":
  22736. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22737. case "AnaglyphArcRotateCamera":
  22738. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22739. case "AnaglyphFreeCamera":
  22740. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22741. case "AnaglyphGamepadCamera":
  22742. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22743. case "AnaglyphUniversalCamera":
  22744. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22745. case "StereoscopicArcRotateCamera":
  22746. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22747. case "StereoscopicFreeCamera":
  22748. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22749. case "StereoscopicGamepadCamera":
  22750. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22751. case "StereoscopicUniversalCamera":
  22752. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22753. case "FreeCamera": // Forcing Universal here
  22754. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22755. default: // Universal Camera is the default value
  22756. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22757. }
  22758. };
  22759. Camera.prototype.computeWorldMatrix = function () {
  22760. return this.getWorldMatrix();
  22761. };
  22762. Camera.Parse = function (parsedCamera, scene) {
  22763. var type = parsedCamera.type;
  22764. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22765. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22766. // Parent
  22767. if (parsedCamera.parentId) {
  22768. camera._waitingParentId = parsedCamera.parentId;
  22769. }
  22770. //If camera has an input manager, let it parse inputs settings
  22771. if (camera.inputs) {
  22772. camera.inputs.parse(parsedCamera);
  22773. camera._setupInputs();
  22774. }
  22775. if (camera.setPosition) { // need to force position
  22776. camera.position.copyFromFloats(0, 0, 0);
  22777. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22778. }
  22779. // Target
  22780. if (parsedCamera.target) {
  22781. if (camera.setTarget) {
  22782. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22783. }
  22784. }
  22785. // Apply 3d rig, when found
  22786. if (parsedCamera.cameraRigMode) {
  22787. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22788. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22789. }
  22790. // Animations
  22791. if (parsedCamera.animations) {
  22792. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22793. var parsedAnimation = parsedCamera.animations[animationIndex];
  22794. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22795. }
  22796. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22797. }
  22798. if (parsedCamera.autoAnimate) {
  22799. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22800. }
  22801. return camera;
  22802. };
  22803. // Statics
  22804. Camera._PERSPECTIVE_CAMERA = 0;
  22805. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22806. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22807. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22808. Camera._RIG_MODE_NONE = 0;
  22809. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22810. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22811. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22812. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22813. Camera._RIG_MODE_VR = 20;
  22814. Camera._RIG_MODE_WEBVR = 21;
  22815. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22816. Camera.UseAlternateWebVRRendering = false;
  22817. __decorate([
  22818. BABYLON.serializeAsVector3()
  22819. ], Camera.prototype, "position", void 0);
  22820. __decorate([
  22821. BABYLON.serializeAsVector3()
  22822. ], Camera.prototype, "upVector", void 0);
  22823. __decorate([
  22824. BABYLON.serialize()
  22825. ], Camera.prototype, "orthoLeft", void 0);
  22826. __decorate([
  22827. BABYLON.serialize()
  22828. ], Camera.prototype, "orthoRight", void 0);
  22829. __decorate([
  22830. BABYLON.serialize()
  22831. ], Camera.prototype, "orthoBottom", void 0);
  22832. __decorate([
  22833. BABYLON.serialize()
  22834. ], Camera.prototype, "orthoTop", void 0);
  22835. __decorate([
  22836. BABYLON.serialize()
  22837. ], Camera.prototype, "fov", void 0);
  22838. __decorate([
  22839. BABYLON.serialize()
  22840. ], Camera.prototype, "minZ", void 0);
  22841. __decorate([
  22842. BABYLON.serialize()
  22843. ], Camera.prototype, "maxZ", void 0);
  22844. __decorate([
  22845. BABYLON.serialize()
  22846. ], Camera.prototype, "inertia", void 0);
  22847. __decorate([
  22848. BABYLON.serialize()
  22849. ], Camera.prototype, "mode", void 0);
  22850. __decorate([
  22851. BABYLON.serialize()
  22852. ], Camera.prototype, "layerMask", void 0);
  22853. __decorate([
  22854. BABYLON.serialize()
  22855. ], Camera.prototype, "fovMode", void 0);
  22856. __decorate([
  22857. BABYLON.serialize()
  22858. ], Camera.prototype, "cameraRigMode", void 0);
  22859. __decorate([
  22860. BABYLON.serialize()
  22861. ], Camera.prototype, "interaxialDistance", void 0);
  22862. __decorate([
  22863. BABYLON.serialize()
  22864. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22865. return Camera;
  22866. }(BABYLON.Node));
  22867. BABYLON.Camera = Camera;
  22868. })(BABYLON || (BABYLON = {}));
  22869. //# sourceMappingURL=babylon.camera.js.map
  22870. var BABYLON;
  22871. (function (BABYLON) {
  22872. var RenderingManager = /** @class */ (function () {
  22873. function RenderingManager(scene) {
  22874. this._renderingGroups = new Array();
  22875. this._autoClearDepthStencil = {};
  22876. this._customOpaqueSortCompareFn = {};
  22877. this._customAlphaTestSortCompareFn = {};
  22878. this._customTransparentSortCompareFn = {};
  22879. this._renderinGroupInfo = null;
  22880. this._scene = scene;
  22881. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22882. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22883. }
  22884. }
  22885. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22886. if (depth === void 0) { depth = true; }
  22887. if (stencil === void 0) { stencil = true; }
  22888. if (this._depthStencilBufferAlreadyCleaned) {
  22889. return;
  22890. }
  22891. this._scene.getEngine().clear(null, false, depth, stencil);
  22892. this._depthStencilBufferAlreadyCleaned = true;
  22893. };
  22894. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22895. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22896. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22897. var info = null;
  22898. if (observable) {
  22899. if (!this._renderinGroupInfo) {
  22900. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22901. }
  22902. info = this._renderinGroupInfo;
  22903. info.scene = this._scene;
  22904. info.camera = this._scene.activeCamera;
  22905. }
  22906. // Dispatch sprites
  22907. if (renderSprites) {
  22908. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22909. var manager = this._scene.spriteManagers[index];
  22910. this.dispatchSprites(manager);
  22911. }
  22912. }
  22913. // Render
  22914. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22915. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22916. var renderingGroup = this._renderingGroups[index];
  22917. if (!renderingGroup && !observable)
  22918. continue;
  22919. var renderingGroupMask = 0;
  22920. // Fire PRECLEAR stage
  22921. if (observable && info) {
  22922. renderingGroupMask = Math.pow(2, index);
  22923. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22924. info.renderingGroupId = index;
  22925. observable.notifyObservers(info, renderingGroupMask);
  22926. }
  22927. // Clear depth/stencil if needed
  22928. if (RenderingManager.AUTOCLEAR) {
  22929. var autoClear = this._autoClearDepthStencil[index];
  22930. if (autoClear && autoClear.autoClear) {
  22931. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22932. }
  22933. }
  22934. if (observable && info) {
  22935. // Fire PREOPAQUE stage
  22936. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22937. observable.notifyObservers(info, renderingGroupMask);
  22938. // Fire PRETRANSPARENT stage
  22939. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22940. observable.notifyObservers(info, renderingGroupMask);
  22941. }
  22942. if (renderingGroup)
  22943. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22944. // Fire POSTTRANSPARENT stage
  22945. if (observable && info) {
  22946. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22947. observable.notifyObservers(info, renderingGroupMask);
  22948. }
  22949. }
  22950. };
  22951. RenderingManager.prototype.reset = function () {
  22952. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22953. var renderingGroup = this._renderingGroups[index];
  22954. if (renderingGroup) {
  22955. renderingGroup.prepare();
  22956. }
  22957. }
  22958. };
  22959. RenderingManager.prototype.dispose = function () {
  22960. this.freeRenderingGroups();
  22961. this._renderingGroups.length = 0;
  22962. };
  22963. /**
  22964. * Clear the info related to rendering groups preventing retention points during dispose.
  22965. */
  22966. RenderingManager.prototype.freeRenderingGroups = function () {
  22967. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22968. var renderingGroup = this._renderingGroups[index];
  22969. if (renderingGroup) {
  22970. renderingGroup.dispose();
  22971. }
  22972. }
  22973. };
  22974. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22975. if (this._renderingGroups[renderingGroupId] === undefined) {
  22976. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22977. }
  22978. };
  22979. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22980. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22981. this._prepareRenderingGroup(renderingGroupId);
  22982. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22983. };
  22984. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22985. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22986. this._prepareRenderingGroup(renderingGroupId);
  22987. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22988. };
  22989. /**
  22990. * @param subMesh The submesh to dispatch
  22991. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22992. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22993. */
  22994. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22995. if (mesh === undefined) {
  22996. mesh = subMesh.getMesh();
  22997. }
  22998. var renderingGroupId = mesh.renderingGroupId || 0;
  22999. this._prepareRenderingGroup(renderingGroupId);
  23000. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23001. };
  23002. /**
  23003. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23004. * This allowed control for front to back rendering or reversly depending of the special needs.
  23005. *
  23006. * @param renderingGroupId The rendering group id corresponding to its index
  23007. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23008. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23009. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23010. */
  23011. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23012. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23013. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23014. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23015. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23016. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23017. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23018. if (this._renderingGroups[renderingGroupId]) {
  23019. var group = this._renderingGroups[renderingGroupId];
  23020. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23021. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23022. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23023. }
  23024. };
  23025. /**
  23026. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23027. *
  23028. * @param renderingGroupId The rendering group id corresponding to its index
  23029. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23030. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23031. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23032. */
  23033. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23034. if (depth === void 0) { depth = true; }
  23035. if (stencil === void 0) { stencil = true; }
  23036. this._autoClearDepthStencil[renderingGroupId] = {
  23037. autoClear: autoClearDepthStencil,
  23038. depth: depth,
  23039. stencil: stencil
  23040. };
  23041. };
  23042. /**
  23043. * The max id used for rendering groups (not included)
  23044. */
  23045. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23046. /**
  23047. * The min id used for rendering groups (included)
  23048. */
  23049. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23050. /**
  23051. * Used to globally prevent autoclearing scenes.
  23052. */
  23053. RenderingManager.AUTOCLEAR = true;
  23054. return RenderingManager;
  23055. }());
  23056. BABYLON.RenderingManager = RenderingManager;
  23057. })(BABYLON || (BABYLON = {}));
  23058. //# sourceMappingURL=babylon.renderingManager.js.map
  23059. var BABYLON;
  23060. (function (BABYLON) {
  23061. var RenderingGroup = /** @class */ (function () {
  23062. /**
  23063. * Creates a new rendering group.
  23064. * @param index The rendering group index
  23065. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23066. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23067. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23068. */
  23069. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23070. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23071. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23072. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23073. this.index = index;
  23074. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23075. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23076. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23077. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23078. this._particleSystems = new BABYLON.SmartArray(256);
  23079. this._spriteManagers = new BABYLON.SmartArray(256);
  23080. this._edgesRenderers = new BABYLON.SmartArray(16);
  23081. this._scene = scene;
  23082. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23083. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23084. this.transparentSortCompareFn = transparentSortCompareFn;
  23085. }
  23086. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23087. /**
  23088. * Set the opaque sort comparison function.
  23089. * If null the sub meshes will be render in the order they were created
  23090. */
  23091. set: function (value) {
  23092. this._opaqueSortCompareFn = value;
  23093. if (value) {
  23094. this._renderOpaque = this.renderOpaqueSorted;
  23095. }
  23096. else {
  23097. this._renderOpaque = RenderingGroup.renderUnsorted;
  23098. }
  23099. },
  23100. enumerable: true,
  23101. configurable: true
  23102. });
  23103. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23104. /**
  23105. * Set the alpha test sort comparison function.
  23106. * If null the sub meshes will be render in the order they were created
  23107. */
  23108. set: function (value) {
  23109. this._alphaTestSortCompareFn = value;
  23110. if (value) {
  23111. this._renderAlphaTest = this.renderAlphaTestSorted;
  23112. }
  23113. else {
  23114. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23115. }
  23116. },
  23117. enumerable: true,
  23118. configurable: true
  23119. });
  23120. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23121. /**
  23122. * Set the transparent sort comparison function.
  23123. * If null the sub meshes will be render in the order they were created
  23124. */
  23125. set: function (value) {
  23126. if (value) {
  23127. this._transparentSortCompareFn = value;
  23128. }
  23129. else {
  23130. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23131. }
  23132. this._renderTransparent = this.renderTransparentSorted;
  23133. },
  23134. enumerable: true,
  23135. configurable: true
  23136. });
  23137. /**
  23138. * Render all the sub meshes contained in the group.
  23139. * @param customRenderFunction Used to override the default render behaviour of the group.
  23140. * @returns true if rendered some submeshes.
  23141. */
  23142. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23143. if (customRenderFunction) {
  23144. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23145. return;
  23146. }
  23147. var engine = this._scene.getEngine();
  23148. // Depth only
  23149. if (this._depthOnlySubMeshes.length !== 0) {
  23150. engine.setColorWrite(false);
  23151. this._renderAlphaTest(this._depthOnlySubMeshes);
  23152. engine.setColorWrite(true);
  23153. }
  23154. // Opaque
  23155. if (this._opaqueSubMeshes.length !== 0) {
  23156. this._renderOpaque(this._opaqueSubMeshes);
  23157. }
  23158. // Alpha test
  23159. if (this._alphaTestSubMeshes.length !== 0) {
  23160. this._renderAlphaTest(this._alphaTestSubMeshes);
  23161. }
  23162. var stencilState = engine.getStencilBuffer();
  23163. engine.setStencilBuffer(false);
  23164. // Sprites
  23165. if (renderSprites) {
  23166. this._renderSprites();
  23167. }
  23168. // Particles
  23169. if (renderParticles) {
  23170. this._renderParticles(activeMeshes);
  23171. }
  23172. if (this.onBeforeTransparentRendering) {
  23173. this.onBeforeTransparentRendering();
  23174. }
  23175. // Transparent
  23176. if (this._transparentSubMeshes.length !== 0) {
  23177. this._renderTransparent(this._transparentSubMeshes);
  23178. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23179. }
  23180. // Set back stencil to false in case it changes before the edge renderer.
  23181. engine.setStencilBuffer(false);
  23182. // Edges
  23183. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23184. this._edgesRenderers.data[edgesRendererIndex].render();
  23185. }
  23186. // Restore Stencil state.
  23187. engine.setStencilBuffer(stencilState);
  23188. };
  23189. /**
  23190. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23191. * @param subMeshes The submeshes to render
  23192. */
  23193. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23194. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23195. };
  23196. /**
  23197. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23198. * @param subMeshes The submeshes to render
  23199. */
  23200. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23201. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23202. };
  23203. /**
  23204. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23205. * @param subMeshes The submeshes to render
  23206. */
  23207. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23208. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23209. };
  23210. /**
  23211. * Renders the submeshes in a specified order.
  23212. * @param subMeshes The submeshes to sort before render
  23213. * @param sortCompareFn The comparison function use to sort
  23214. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23215. * @param transparent Specifies to activate blending if true
  23216. */
  23217. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23218. var subIndex = 0;
  23219. var subMesh;
  23220. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23221. for (; subIndex < subMeshes.length; subIndex++) {
  23222. subMesh = subMeshes.data[subIndex];
  23223. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23224. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23225. }
  23226. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23227. if (sortCompareFn) {
  23228. sortedArray.sort(sortCompareFn);
  23229. }
  23230. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23231. subMesh = sortedArray[subIndex];
  23232. if (transparent) {
  23233. var material = subMesh.getMaterial();
  23234. if (material && material.needDepthPrePass) {
  23235. var engine = material.getScene().getEngine();
  23236. engine.setColorWrite(false);
  23237. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23238. subMesh.render(false);
  23239. engine.setColorWrite(true);
  23240. }
  23241. }
  23242. subMesh.render(transparent);
  23243. }
  23244. };
  23245. /**
  23246. * Renders the submeshes in the order they were dispatched (no sort applied).
  23247. * @param subMeshes The submeshes to render
  23248. */
  23249. RenderingGroup.renderUnsorted = function (subMeshes) {
  23250. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23251. var submesh = subMeshes.data[subIndex];
  23252. submesh.render(false);
  23253. }
  23254. };
  23255. /**
  23256. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23257. * are rendered back to front if in the same alpha index.
  23258. *
  23259. * @param a The first submesh
  23260. * @param b The second submesh
  23261. * @returns The result of the comparison
  23262. */
  23263. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23264. // Alpha index first
  23265. if (a._alphaIndex > b._alphaIndex) {
  23266. return 1;
  23267. }
  23268. if (a._alphaIndex < b._alphaIndex) {
  23269. return -1;
  23270. }
  23271. // Then distance to camera
  23272. return RenderingGroup.backToFrontSortCompare(a, b);
  23273. };
  23274. /**
  23275. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23276. * are rendered back to front.
  23277. *
  23278. * @param a The first submesh
  23279. * @param b The second submesh
  23280. * @returns The result of the comparison
  23281. */
  23282. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23283. // Then distance to camera
  23284. if (a._distanceToCamera < b._distanceToCamera) {
  23285. return 1;
  23286. }
  23287. if (a._distanceToCamera > b._distanceToCamera) {
  23288. return -1;
  23289. }
  23290. return 0;
  23291. };
  23292. /**
  23293. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23294. * are rendered front to back (prevent overdraw).
  23295. *
  23296. * @param a The first submesh
  23297. * @param b The second submesh
  23298. * @returns The result of the comparison
  23299. */
  23300. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23301. // Then distance to camera
  23302. if (a._distanceToCamera < b._distanceToCamera) {
  23303. return -1;
  23304. }
  23305. if (a._distanceToCamera > b._distanceToCamera) {
  23306. return 1;
  23307. }
  23308. return 0;
  23309. };
  23310. /**
  23311. * Resets the different lists of submeshes to prepare a new frame.
  23312. */
  23313. RenderingGroup.prototype.prepare = function () {
  23314. this._opaqueSubMeshes.reset();
  23315. this._transparentSubMeshes.reset();
  23316. this._alphaTestSubMeshes.reset();
  23317. this._depthOnlySubMeshes.reset();
  23318. this._particleSystems.reset();
  23319. this._spriteManagers.reset();
  23320. this._edgesRenderers.reset();
  23321. };
  23322. RenderingGroup.prototype.dispose = function () {
  23323. this._opaqueSubMeshes.dispose();
  23324. this._transparentSubMeshes.dispose();
  23325. this._alphaTestSubMeshes.dispose();
  23326. this._depthOnlySubMeshes.dispose();
  23327. this._particleSystems.dispose();
  23328. this._spriteManagers.dispose();
  23329. this._edgesRenderers.dispose();
  23330. };
  23331. /**
  23332. * Inserts the submesh in its correct queue depending on its material.
  23333. * @param subMesh The submesh to dispatch
  23334. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23335. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23336. */
  23337. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23338. // Get mesh and materials if not provided
  23339. if (mesh === undefined) {
  23340. mesh = subMesh.getMesh();
  23341. }
  23342. if (material === undefined) {
  23343. material = subMesh.getMaterial();
  23344. }
  23345. if (material === null || material === undefined) {
  23346. return;
  23347. }
  23348. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23349. this._transparentSubMeshes.push(subMesh);
  23350. }
  23351. else if (material.needAlphaTesting()) { // Alpha test
  23352. if (material.needDepthPrePass) {
  23353. this._depthOnlySubMeshes.push(subMesh);
  23354. }
  23355. this._alphaTestSubMeshes.push(subMesh);
  23356. }
  23357. else {
  23358. if (material.needDepthPrePass) {
  23359. this._depthOnlySubMeshes.push(subMesh);
  23360. }
  23361. this._opaqueSubMeshes.push(subMesh); // Opaque
  23362. }
  23363. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23364. this._edgesRenderers.push(mesh._edgesRenderer);
  23365. }
  23366. };
  23367. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23368. this._spriteManagers.push(spriteManager);
  23369. };
  23370. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23371. this._particleSystems.push(particleSystem);
  23372. };
  23373. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23374. if (this._particleSystems.length === 0) {
  23375. return;
  23376. }
  23377. // Particles
  23378. var activeCamera = this._scene.activeCamera;
  23379. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23380. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23381. var particleSystem = this._particleSystems.data[particleIndex];
  23382. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23383. continue;
  23384. }
  23385. var emitter = particleSystem.emitter;
  23386. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23387. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23388. }
  23389. }
  23390. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23391. };
  23392. RenderingGroup.prototype._renderSprites = function () {
  23393. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23394. return;
  23395. }
  23396. // Sprites
  23397. var activeCamera = this._scene.activeCamera;
  23398. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23399. for (var id = 0; id < this._spriteManagers.length; id++) {
  23400. var spriteManager = this._spriteManagers.data[id];
  23401. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23402. spriteManager.render();
  23403. }
  23404. }
  23405. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23406. };
  23407. return RenderingGroup;
  23408. }());
  23409. BABYLON.RenderingGroup = RenderingGroup;
  23410. })(BABYLON || (BABYLON = {}));
  23411. //# sourceMappingURL=babylon.renderingGroup.js.map
  23412. var BABYLON;
  23413. (function (BABYLON) {
  23414. /** @hidden */
  23415. var ClickInfo = /** @class */ (function () {
  23416. function ClickInfo() {
  23417. this._singleClick = false;
  23418. this._doubleClick = false;
  23419. this._hasSwiped = false;
  23420. this._ignore = false;
  23421. }
  23422. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23423. get: function () {
  23424. return this._singleClick;
  23425. },
  23426. set: function (b) {
  23427. this._singleClick = b;
  23428. },
  23429. enumerable: true,
  23430. configurable: true
  23431. });
  23432. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23433. get: function () {
  23434. return this._doubleClick;
  23435. },
  23436. set: function (b) {
  23437. this._doubleClick = b;
  23438. },
  23439. enumerable: true,
  23440. configurable: true
  23441. });
  23442. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23443. get: function () {
  23444. return this._hasSwiped;
  23445. },
  23446. set: function (b) {
  23447. this._hasSwiped = b;
  23448. },
  23449. enumerable: true,
  23450. configurable: true
  23451. });
  23452. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23453. get: function () {
  23454. return this._ignore;
  23455. },
  23456. set: function (b) {
  23457. this._ignore = b;
  23458. },
  23459. enumerable: true,
  23460. configurable: true
  23461. });
  23462. return ClickInfo;
  23463. }());
  23464. /**
  23465. * This class is used by the onRenderingGroupObservable
  23466. */
  23467. var RenderingGroupInfo = /** @class */ (function () {
  23468. function RenderingGroupInfo() {
  23469. }
  23470. /**
  23471. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23472. * This stage will be fired no matter what
  23473. */
  23474. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23475. /**
  23476. * Called before opaque object are rendered.
  23477. * This stage will be fired only if there's 3D Opaque content to render
  23478. */
  23479. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23480. /**
  23481. * Called after the opaque objects are rendered and before the transparent ones
  23482. * This stage will be fired only if there's 3D transparent content to render
  23483. */
  23484. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23485. /**
  23486. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23487. * This stage will be fired no matter what
  23488. */
  23489. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23490. return RenderingGroupInfo;
  23491. }());
  23492. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23493. /**
  23494. * Represents a scene to be rendered by the engine.
  23495. * @see http://doc.babylonjs.com/features/scene
  23496. */
  23497. var Scene = /** @class */ (function () {
  23498. /**
  23499. * Creates a new Scene
  23500. * @param engine defines the engine to use to render this scene
  23501. */
  23502. function Scene(engine) {
  23503. // Members
  23504. /**
  23505. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23506. */
  23507. this.autoClear = true;
  23508. /**
  23509. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23510. */
  23511. this.autoClearDepthAndStencil = true;
  23512. /**
  23513. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23514. */
  23515. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23516. /**
  23517. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23518. */
  23519. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23520. this._forceWireframe = false;
  23521. this._forcePointsCloud = false;
  23522. /**
  23523. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23524. */
  23525. this.forceShowBoundingBoxes = false;
  23526. /**
  23527. * Gets or sets a boolean indicating if animations are enabled
  23528. */
  23529. this.animationsEnabled = true;
  23530. this._animationPropertiesOverride = null;
  23531. /**
  23532. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23533. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23534. */
  23535. this.useConstantAnimationDeltaTime = false;
  23536. /**
  23537. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23538. * Please note that it requires to run a ray cast through the scene on every frame
  23539. */
  23540. this.constantlyUpdateMeshUnderPointer = false;
  23541. /**
  23542. * Defines the HTML cursor to use when hovering over interactive elements
  23543. */
  23544. this.hoverCursor = "pointer";
  23545. /**
  23546. * Defines the HTML default cursor to use (empty by default)
  23547. */
  23548. this.defaultCursor = "";
  23549. /**
  23550. * This is used to call preventDefault() on pointer down
  23551. * in order to block unwanted artifacts like system double clicks
  23552. */
  23553. this.preventDefaultOnPointerDown = true;
  23554. // Metadata
  23555. /**
  23556. * Gets or sets user defined metadata
  23557. */
  23558. this.metadata = null;
  23559. /**
  23560. * Use this array to add regular expressions used to disable offline support for specific urls
  23561. */
  23562. this.disableOfflineSupportExceptionRules = new Array();
  23563. /**
  23564. * An event triggered when the scene is disposed.
  23565. */
  23566. this.onDisposeObservable = new BABYLON.Observable();
  23567. this._onDisposeObserver = null;
  23568. /**
  23569. * An event triggered before rendering the scene (right after animations and physics)
  23570. */
  23571. this.onBeforeRenderObservable = new BABYLON.Observable();
  23572. this._onBeforeRenderObserver = null;
  23573. /**
  23574. * An event triggered after rendering the scene
  23575. */
  23576. this.onAfterRenderObservable = new BABYLON.Observable();
  23577. this._onAfterRenderObserver = null;
  23578. /**
  23579. * An event triggered before animating the scene
  23580. */
  23581. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23582. /**
  23583. * An event triggered after animations processing
  23584. */
  23585. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23586. /**
  23587. * An event triggered before draw calls are ready to be sent
  23588. */
  23589. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23590. /**
  23591. * An event triggered after draw calls have been sent
  23592. */
  23593. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23594. /**
  23595. * An event triggered when physic simulation is about to be run
  23596. */
  23597. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23598. /**
  23599. * An event triggered when physic simulation has been done
  23600. */
  23601. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23602. /**
  23603. * An event triggered when the scene is ready
  23604. */
  23605. this.onReadyObservable = new BABYLON.Observable();
  23606. /**
  23607. * An event triggered before rendering a camera
  23608. */
  23609. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23610. this._onBeforeCameraRenderObserver = null;
  23611. /**
  23612. * An event triggered after rendering a camera
  23613. */
  23614. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23615. this._onAfterCameraRenderObserver = null;
  23616. /**
  23617. * An event triggered when active meshes evaluation is about to start
  23618. */
  23619. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23620. /**
  23621. * An event triggered when active meshes evaluation is done
  23622. */
  23623. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23624. /**
  23625. * An event triggered when particles rendering is about to start
  23626. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23627. */
  23628. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23629. /**
  23630. * An event triggered when particles rendering is done
  23631. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23632. */
  23633. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23634. /**
  23635. * An event triggered when sprites rendering is about to start
  23636. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23637. */
  23638. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23639. /**
  23640. * An event triggered when sprites rendering is done
  23641. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23642. */
  23643. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23644. /**
  23645. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23646. */
  23647. this.onDataLoadedObservable = new BABYLON.Observable();
  23648. /**
  23649. * An event triggered when a camera is created
  23650. */
  23651. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23652. /**
  23653. * An event triggered when a camera is removed
  23654. */
  23655. this.onCameraRemovedObservable = new BABYLON.Observable();
  23656. /**
  23657. * An event triggered when a light is created
  23658. */
  23659. this.onNewLightAddedObservable = new BABYLON.Observable();
  23660. /**
  23661. * An event triggered when a light is removed
  23662. */
  23663. this.onLightRemovedObservable = new BABYLON.Observable();
  23664. /**
  23665. * An event triggered when a geometry is created
  23666. */
  23667. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23668. /**
  23669. * An event triggered when a geometry is removed
  23670. */
  23671. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23672. /**
  23673. * An event triggered when a transform node is created
  23674. */
  23675. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23676. /**
  23677. * An event triggered when a transform node is removed
  23678. */
  23679. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23680. /**
  23681. * An event triggered when a mesh is created
  23682. */
  23683. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23684. /**
  23685. * An event triggered when a mesh is removed
  23686. */
  23687. this.onMeshRemovedObservable = new BABYLON.Observable();
  23688. /**
  23689. * An event triggered when render targets are about to be rendered
  23690. * Can happen multiple times per frame.
  23691. */
  23692. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23693. /**
  23694. * An event triggered when render targets were rendered.
  23695. * Can happen multiple times per frame.
  23696. */
  23697. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23698. /**
  23699. * An event triggered before calculating deterministic simulation step
  23700. */
  23701. this.onBeforeStepObservable = new BABYLON.Observable();
  23702. /**
  23703. * An event triggered after calculating deterministic simulation step
  23704. */
  23705. this.onAfterStepObservable = new BABYLON.Observable();
  23706. /**
  23707. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23708. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23709. * 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)
  23710. */
  23711. this.onRenderingGroupObservable = new BABYLON.Observable();
  23712. // Animations
  23713. /**
  23714. * Gets a list of Animations associated with the scene
  23715. */
  23716. this.animations = [];
  23717. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23718. /**
  23719. * 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).
  23720. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23721. */
  23722. this.onPrePointerObservable = new BABYLON.Observable();
  23723. /**
  23724. * Observable event triggered each time an input event is received from the rendering canvas
  23725. */
  23726. this.onPointerObservable = new BABYLON.Observable();
  23727. this._meshPickProceed = false;
  23728. this._currentPickResult = null;
  23729. this._previousPickResult = null;
  23730. this._totalPointersPressed = 0;
  23731. this._doubleClickOccured = false;
  23732. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23733. this.cameraToUseForPointers = null;
  23734. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23735. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23736. this._startingPointerTime = 0;
  23737. this._previousStartingPointerTime = 0;
  23738. // Deterministic lockstep
  23739. this._timeAccumulator = 0;
  23740. this._currentStepId = 0;
  23741. this._currentInternalStep = 0;
  23742. // Keyboard
  23743. /**
  23744. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23745. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23746. */
  23747. this.onPreKeyboardObservable = new BABYLON.Observable();
  23748. /**
  23749. * Observable event triggered each time an keyboard event is received from the hosting window
  23750. */
  23751. this.onKeyboardObservable = new BABYLON.Observable();
  23752. // Coordinates system
  23753. this._useRightHandedSystem = false;
  23754. // Fog
  23755. this._fogEnabled = true;
  23756. this._fogMode = Scene.FOGMODE_NONE;
  23757. /**
  23758. * Gets or sets the fog color to use
  23759. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23760. */
  23761. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23762. /**
  23763. * Gets or sets the fog density to use
  23764. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23765. */
  23766. this.fogDensity = 0.1;
  23767. /**
  23768. * Gets or sets the fog start distance to use
  23769. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23770. */
  23771. this.fogStart = 0;
  23772. /**
  23773. * Gets or sets the fog end distance to use
  23774. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23775. */
  23776. this.fogEnd = 1000.0;
  23777. // Lights
  23778. this._shadowsEnabled = true;
  23779. this._lightsEnabled = true;
  23780. /**
  23781. * All of the lights added to this scene
  23782. * @see http://doc.babylonjs.com/babylon101/lights
  23783. */
  23784. this.lights = new Array();
  23785. // Cameras
  23786. /** All of the cameras added to this scene.
  23787. * @see http://doc.babylonjs.com/babylon101/cameras
  23788. */
  23789. this.cameras = new Array();
  23790. /** All of the active cameras added to this scene. */
  23791. this.activeCameras = new Array();
  23792. // Meshes
  23793. /**
  23794. * All of the tranform nodes added to this scene
  23795. * @see http://doc.babylonjs.com/how_to/transformnode
  23796. */
  23797. this.transformNodes = new Array();
  23798. /**
  23799. * All of the (abstract) meshes added to this scene
  23800. */
  23801. this.meshes = new Array();
  23802. /**
  23803. * All of the animation groups added to this scene
  23804. * @see http://doc.babylonjs.com/how_to/group
  23805. */
  23806. this.animationGroups = new Array();
  23807. // Geometries
  23808. this._geometries = new Array();
  23809. /**
  23810. * All of the materials added to this scene
  23811. * @see http://doc.babylonjs.com/babylon101/materials
  23812. */
  23813. this.materials = new Array();
  23814. /**
  23815. * All of the multi-materials added to this scene
  23816. * @see http://doc.babylonjs.com/how_to/multi_materials
  23817. */
  23818. this.multiMaterials = new Array();
  23819. // Textures
  23820. this._texturesEnabled = true;
  23821. /**
  23822. * All of the textures added to this scene
  23823. */
  23824. this.textures = new Array();
  23825. // Particles
  23826. /**
  23827. * Gets or sets a boolean indicating if particles are enabled on this scene
  23828. */
  23829. this.particlesEnabled = true;
  23830. /**
  23831. * All of the particle systems added to this scene
  23832. * @see http://doc.babylonjs.com/babylon101/particles
  23833. */
  23834. this.particleSystems = new Array();
  23835. // Sprites
  23836. /**
  23837. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23838. */
  23839. this.spritesEnabled = true;
  23840. /**
  23841. * All of the sprite managers added to this scene
  23842. * @see http://doc.babylonjs.com/babylon101/sprites
  23843. */
  23844. this.spriteManagers = new Array();
  23845. /**
  23846. * The list of layers (background and foreground) of the scene
  23847. */
  23848. this.layers = new Array();
  23849. /**
  23850. * The list of effect layers (highlights/glow) added to the scene
  23851. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23852. * @see http://doc.babylonjs.com/how_to/glow_layer
  23853. */
  23854. this.effectLayers = new Array();
  23855. // Skeletons
  23856. this._skeletonsEnabled = true;
  23857. /**
  23858. * The list of skeletons added to the scene
  23859. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23860. */
  23861. this.skeletons = new Array();
  23862. // Morph targets
  23863. /**
  23864. * The list of morph target managers added to the scene
  23865. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23866. */
  23867. this.morphTargetManagers = new Array();
  23868. // Lens flares
  23869. /**
  23870. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23871. */
  23872. this.lensFlaresEnabled = true;
  23873. /**
  23874. * The list of lens flare system added to the scene
  23875. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23876. */
  23877. this.lensFlareSystems = new Array();
  23878. // Collisions
  23879. /**
  23880. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23881. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23882. */
  23883. this.collisionsEnabled = true;
  23884. /**
  23885. * Defines the gravity applied to this scene (used only for collisions)
  23886. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23887. */
  23888. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23889. // Postprocesses
  23890. /**
  23891. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23892. */
  23893. this.postProcessesEnabled = true;
  23894. /**
  23895. * The list of postprocesses added to the scene
  23896. */
  23897. this.postProcesses = new Array();
  23898. // Customs render targets
  23899. /**
  23900. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23901. */
  23902. this.renderTargetsEnabled = true;
  23903. /**
  23904. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23905. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23906. */
  23907. this.dumpNextRenderTargets = false;
  23908. /**
  23909. * The list of user defined render targets added to the scene
  23910. */
  23911. this.customRenderTargets = new Array();
  23912. /**
  23913. * Gets the list of meshes imported to the scene through SceneLoader
  23914. */
  23915. this.importedMeshesFiles = new Array();
  23916. // Probes
  23917. /**
  23918. * Gets or sets a boolean indicating if probes are enabled on this scene
  23919. */
  23920. this.probesEnabled = true;
  23921. /**
  23922. * The list of reflection probes added to the scene
  23923. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23924. */
  23925. this.reflectionProbes = new Array();
  23926. /** @hidden */
  23927. this._actionManagers = new Array();
  23928. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23929. // Procedural textures
  23930. /**
  23931. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23932. */
  23933. this.proceduralTexturesEnabled = true;
  23934. /**
  23935. * The list of procedural textures added to the scene
  23936. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23937. */
  23938. this.proceduralTextures = new Array();
  23939. /**
  23940. * The list of sound tracks added to the scene
  23941. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23942. */
  23943. this.soundTracks = new Array();
  23944. this._audioEnabled = true;
  23945. this._headphone = false;
  23946. // Performance counters
  23947. this._totalVertices = new BABYLON.PerfCounter();
  23948. /** @hidden */
  23949. this._activeIndices = new BABYLON.PerfCounter();
  23950. /** @hidden */
  23951. this._activeParticles = new BABYLON.PerfCounter();
  23952. /** @hidden */
  23953. this._activeBones = new BABYLON.PerfCounter();
  23954. this._animationTime = 0;
  23955. /**
  23956. * Gets or sets a general scale for animation speed
  23957. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23958. */
  23959. this.animationTimeScale = 1;
  23960. this._renderId = 0;
  23961. this._executeWhenReadyTimeoutId = -1;
  23962. this._intermediateRendering = false;
  23963. this._viewUpdateFlag = -1;
  23964. this._projectionUpdateFlag = -1;
  23965. this._alternateViewUpdateFlag = -1;
  23966. this._alternateProjectionUpdateFlag = -1;
  23967. /** @hidden */
  23968. this._toBeDisposed = new BABYLON.SmartArray(256);
  23969. this._activeRequests = new Array();
  23970. this._pendingData = new Array();
  23971. this._isDisposed = false;
  23972. /**
  23973. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23974. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23975. */
  23976. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23977. this._activeMeshes = new BABYLON.SmartArray(256);
  23978. this._processedMaterials = new BABYLON.SmartArray(256);
  23979. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23980. /** @hidden */
  23981. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23982. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23983. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23984. /** @hidden */
  23985. this._activeAnimatables = new Array();
  23986. this._transformMatrix = BABYLON.Matrix.Zero();
  23987. this._useAlternateCameraConfiguration = false;
  23988. this._alternateRendering = false;
  23989. /**
  23990. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23991. * This is useful if there are more lights that the maximum simulteanous authorized
  23992. */
  23993. this.requireLightSorting = false;
  23994. this._depthRenderer = {};
  23995. this._activeMeshesFrozen = false;
  23996. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23997. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23998. this._engine.scenes.push(this);
  23999. this._uid = null;
  24000. this._renderingManager = new BABYLON.RenderingManager(this);
  24001. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24002. if (BABYLON.OutlineRenderer) {
  24003. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24004. }
  24005. if (BABYLON.Tools.IsWindowObjectExist()) {
  24006. this.attachControl();
  24007. }
  24008. //simplification queue
  24009. if (BABYLON.SimplificationQueue) {
  24010. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24011. }
  24012. //collision coordinator initialization. For now legacy per default.
  24013. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24014. // Uniform Buffer
  24015. this._createUbo();
  24016. // Default Image processing definition.
  24017. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24018. }
  24019. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24020. /** The fog is deactivated */
  24021. get: function () {
  24022. return Scene._FOGMODE_NONE;
  24023. },
  24024. enumerable: true,
  24025. configurable: true
  24026. });
  24027. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24028. /** The fog density is following an exponential function */
  24029. get: function () {
  24030. return Scene._FOGMODE_EXP;
  24031. },
  24032. enumerable: true,
  24033. configurable: true
  24034. });
  24035. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24036. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24037. get: function () {
  24038. return Scene._FOGMODE_EXP2;
  24039. },
  24040. enumerable: true,
  24041. configurable: true
  24042. });
  24043. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24044. /** The fog density is following a linear function. */
  24045. get: function () {
  24046. return Scene._FOGMODE_LINEAR;
  24047. },
  24048. enumerable: true,
  24049. configurable: true
  24050. });
  24051. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24052. /**
  24053. * Texture used in all pbr material as the reflection texture.
  24054. * As in the majority of the scene they are the same (exception for multi room and so on),
  24055. * this is easier to reference from here than from all the materials.
  24056. */
  24057. get: function () {
  24058. return this._environmentTexture;
  24059. },
  24060. /**
  24061. * Texture used in all pbr material as the reflection texture.
  24062. * As in the majority of the scene they are the same (exception for multi room and so on),
  24063. * this is easier to set here than in all the materials.
  24064. */
  24065. set: function (value) {
  24066. if (this._environmentTexture === value) {
  24067. return;
  24068. }
  24069. this._environmentTexture = value;
  24070. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24071. },
  24072. enumerable: true,
  24073. configurable: true
  24074. });
  24075. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24076. /**
  24077. * Default image processing configuration used either in the rendering
  24078. * Forward main pass or through the imageProcessingPostProcess if present.
  24079. * As in the majority of the scene they are the same (exception for multi camera),
  24080. * this is easier to reference from here than from all the materials and post process.
  24081. *
  24082. * No setter as we it is a shared configuration, you can set the values instead.
  24083. */
  24084. get: function () {
  24085. return this._imageProcessingConfiguration;
  24086. },
  24087. enumerable: true,
  24088. configurable: true
  24089. });
  24090. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24091. get: function () {
  24092. return this._forceWireframe;
  24093. },
  24094. /**
  24095. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24096. */
  24097. set: function (value) {
  24098. if (this._forceWireframe === value) {
  24099. return;
  24100. }
  24101. this._forceWireframe = value;
  24102. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24103. },
  24104. enumerable: true,
  24105. configurable: true
  24106. });
  24107. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24108. get: function () {
  24109. return this._forcePointsCloud;
  24110. },
  24111. /**
  24112. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24113. */
  24114. set: function (value) {
  24115. if (this._forcePointsCloud === value) {
  24116. return;
  24117. }
  24118. this._forcePointsCloud = value;
  24119. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24120. },
  24121. enumerable: true,
  24122. configurable: true
  24123. });
  24124. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24125. /**
  24126. * Gets or sets the animation properties override
  24127. */
  24128. get: function () {
  24129. return this._animationPropertiesOverride;
  24130. },
  24131. set: function (value) {
  24132. this._animationPropertiesOverride = value;
  24133. },
  24134. enumerable: true,
  24135. configurable: true
  24136. });
  24137. Object.defineProperty(Scene.prototype, "onDispose", {
  24138. /** Sets a function to be executed when this scene is disposed. */
  24139. set: function (callback) {
  24140. if (this._onDisposeObserver) {
  24141. this.onDisposeObservable.remove(this._onDisposeObserver);
  24142. }
  24143. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24144. },
  24145. enumerable: true,
  24146. configurable: true
  24147. });
  24148. Object.defineProperty(Scene.prototype, "beforeRender", {
  24149. /** Sets a function to be executed before rendering this scene */
  24150. set: function (callback) {
  24151. if (this._onBeforeRenderObserver) {
  24152. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24153. }
  24154. if (callback) {
  24155. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24156. }
  24157. },
  24158. enumerable: true,
  24159. configurable: true
  24160. });
  24161. Object.defineProperty(Scene.prototype, "afterRender", {
  24162. /** Sets a function to be executed after rendering this scene */
  24163. set: function (callback) {
  24164. if (this._onAfterRenderObserver) {
  24165. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24166. }
  24167. if (callback) {
  24168. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24169. }
  24170. },
  24171. enumerable: true,
  24172. configurable: true
  24173. });
  24174. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24175. /** Sets a function to be executed before rendering a camera*/
  24176. set: function (callback) {
  24177. if (this._onBeforeCameraRenderObserver) {
  24178. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24179. }
  24180. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24181. },
  24182. enumerable: true,
  24183. configurable: true
  24184. });
  24185. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24186. /** Sets a function to be executed after rendering a camera*/
  24187. set: function (callback) {
  24188. if (this._onAfterCameraRenderObserver) {
  24189. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24190. }
  24191. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24192. },
  24193. enumerable: true,
  24194. configurable: true
  24195. });
  24196. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24197. /**
  24198. * Gets the gamepad manager associated with the scene
  24199. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24200. */
  24201. get: function () {
  24202. if (!this._gamepadManager) {
  24203. this._gamepadManager = new BABYLON.GamepadManager(this);
  24204. }
  24205. return this._gamepadManager;
  24206. },
  24207. enumerable: true,
  24208. configurable: true
  24209. });
  24210. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24211. /**
  24212. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24213. */
  24214. get: function () {
  24215. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24216. },
  24217. enumerable: true,
  24218. configurable: true
  24219. });
  24220. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24221. get: function () {
  24222. return this._useRightHandedSystem;
  24223. },
  24224. /**
  24225. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24226. */
  24227. set: function (value) {
  24228. if (this._useRightHandedSystem === value) {
  24229. return;
  24230. }
  24231. this._useRightHandedSystem = value;
  24232. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24233. },
  24234. enumerable: true,
  24235. configurable: true
  24236. });
  24237. /**
  24238. * Sets the step Id used by deterministic lock step
  24239. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24240. * @param newStepId defines the step Id
  24241. */
  24242. Scene.prototype.setStepId = function (newStepId) {
  24243. this._currentStepId = newStepId;
  24244. };
  24245. ;
  24246. /**
  24247. * Gets the step Id used by deterministic lock step
  24248. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24249. * @returns the step Id
  24250. */
  24251. Scene.prototype.getStepId = function () {
  24252. return this._currentStepId;
  24253. };
  24254. ;
  24255. /**
  24256. * Gets the internal step used by deterministic lock step
  24257. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24258. * @returns the internal step
  24259. */
  24260. Scene.prototype.getInternalStep = function () {
  24261. return this._currentInternalStep;
  24262. };
  24263. ;
  24264. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24265. get: function () {
  24266. return this._fogEnabled;
  24267. },
  24268. /**
  24269. * Gets or sets a boolean indicating if fog is enabled on this scene
  24270. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24271. */
  24272. set: function (value) {
  24273. if (this._fogEnabled === value) {
  24274. return;
  24275. }
  24276. this._fogEnabled = value;
  24277. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24278. },
  24279. enumerable: true,
  24280. configurable: true
  24281. });
  24282. Object.defineProperty(Scene.prototype, "fogMode", {
  24283. get: function () {
  24284. return this._fogMode;
  24285. },
  24286. /**
  24287. * Gets or sets the fog mode to use
  24288. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24289. */
  24290. set: function (value) {
  24291. if (this._fogMode === value) {
  24292. return;
  24293. }
  24294. this._fogMode = value;
  24295. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24296. },
  24297. enumerable: true,
  24298. configurable: true
  24299. });
  24300. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24301. get: function () {
  24302. return this._shadowsEnabled;
  24303. },
  24304. /**
  24305. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24306. */
  24307. set: function (value) {
  24308. if (this._shadowsEnabled === value) {
  24309. return;
  24310. }
  24311. this._shadowsEnabled = value;
  24312. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24313. },
  24314. enumerable: true,
  24315. configurable: true
  24316. });
  24317. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24318. get: function () {
  24319. return this._lightsEnabled;
  24320. },
  24321. /**
  24322. * Gets or sets a boolean indicating if lights are enabled on this scene
  24323. */
  24324. set: function (value) {
  24325. if (this._lightsEnabled === value) {
  24326. return;
  24327. }
  24328. this._lightsEnabled = value;
  24329. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24330. },
  24331. enumerable: true,
  24332. configurable: true
  24333. });
  24334. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24335. /** The default material used on meshes when no material is affected */
  24336. get: function () {
  24337. if (!this._defaultMaterial) {
  24338. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24339. }
  24340. return this._defaultMaterial;
  24341. },
  24342. /** The default material used on meshes when no material is affected */
  24343. set: function (value) {
  24344. this._defaultMaterial = value;
  24345. },
  24346. enumerable: true,
  24347. configurable: true
  24348. });
  24349. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24350. get: function () {
  24351. return this._texturesEnabled;
  24352. },
  24353. /**
  24354. * Gets or sets a boolean indicating if textures are enabled on this scene
  24355. */
  24356. set: function (value) {
  24357. if (this._texturesEnabled === value) {
  24358. return;
  24359. }
  24360. this._texturesEnabled = value;
  24361. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24362. },
  24363. enumerable: true,
  24364. configurable: true
  24365. });
  24366. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24367. get: function () {
  24368. return this._skeletonsEnabled;
  24369. },
  24370. /**
  24371. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24372. */
  24373. set: function (value) {
  24374. if (this._skeletonsEnabled === value) {
  24375. return;
  24376. }
  24377. this._skeletonsEnabled = value;
  24378. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24379. },
  24380. enumerable: true,
  24381. configurable: true
  24382. });
  24383. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24384. /**
  24385. * Gets the postprocess render pipeline manager
  24386. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24387. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24388. */
  24389. get: function () {
  24390. if (!this._postProcessRenderPipelineManager) {
  24391. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24392. }
  24393. return this._postProcessRenderPipelineManager;
  24394. },
  24395. enumerable: true,
  24396. configurable: true
  24397. });
  24398. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24399. /**
  24400. * Gets the main soundtrack associated with the scene
  24401. */
  24402. get: function () {
  24403. if (!this._mainSoundTrack) {
  24404. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24405. }
  24406. return this._mainSoundTrack;
  24407. },
  24408. enumerable: true,
  24409. configurable: true
  24410. });
  24411. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24412. /** @hidden */
  24413. get: function () {
  24414. return this._alternateRendering;
  24415. },
  24416. enumerable: true,
  24417. configurable: true
  24418. });
  24419. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24420. /**
  24421. * Gets the list of frustum planes (built from the active camera)
  24422. */
  24423. get: function () {
  24424. return this._frustumPlanes;
  24425. },
  24426. enumerable: true,
  24427. configurable: true
  24428. });
  24429. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24430. /**
  24431. * Gets the current geometry buffer associated to the scene.
  24432. */
  24433. get: function () {
  24434. return this._geometryBufferRenderer;
  24435. },
  24436. /**
  24437. * Sets the current geometry buffer for the scene.
  24438. */
  24439. set: function (geometryBufferRenderer) {
  24440. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24441. this._geometryBufferRenderer = geometryBufferRenderer;
  24442. }
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(Scene.prototype, "debugLayer", {
  24448. /**
  24449. * Gets the debug layer associated with the scene
  24450. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24451. */
  24452. get: function () {
  24453. if (!this._debugLayer) {
  24454. this._debugLayer = new BABYLON.DebugLayer(this);
  24455. }
  24456. return this._debugLayer;
  24457. },
  24458. enumerable: true,
  24459. configurable: true
  24460. });
  24461. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24462. /**
  24463. * Gets a boolean indicating if collisions are processed on a web worker
  24464. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24465. */
  24466. get: function () {
  24467. return this._workerCollisions;
  24468. },
  24469. set: function (enabled) {
  24470. if (!BABYLON.CollisionCoordinatorLegacy) {
  24471. return;
  24472. }
  24473. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24474. this._workerCollisions = enabled;
  24475. if (this.collisionCoordinator) {
  24476. this.collisionCoordinator.destroy();
  24477. }
  24478. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24479. this.collisionCoordinator.init(this);
  24480. },
  24481. enumerable: true,
  24482. configurable: true
  24483. });
  24484. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24485. /**
  24486. * Gets the octree used to boost mesh selection (picking)
  24487. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24488. */
  24489. get: function () {
  24490. return this._selectionOctree;
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24496. /**
  24497. * Gets the mesh that is currently under the pointer
  24498. */
  24499. get: function () {
  24500. return this._pointerOverMesh;
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. Object.defineProperty(Scene.prototype, "pointerX", {
  24506. /**
  24507. * Gets the current on-screen X position of the pointer
  24508. */
  24509. get: function () {
  24510. return this._pointerX;
  24511. },
  24512. enumerable: true,
  24513. configurable: true
  24514. });
  24515. Object.defineProperty(Scene.prototype, "pointerY", {
  24516. /**
  24517. * Gets the current on-screen Y position of the pointer
  24518. */
  24519. get: function () {
  24520. return this._pointerY;
  24521. },
  24522. enumerable: true,
  24523. configurable: true
  24524. });
  24525. /**
  24526. * Gets the cached material (ie. the latest rendered one)
  24527. * @returns the cached material
  24528. */
  24529. Scene.prototype.getCachedMaterial = function () {
  24530. return this._cachedMaterial;
  24531. };
  24532. /**
  24533. * Gets the cached effect (ie. the latest rendered one)
  24534. * @returns the cached effect
  24535. */
  24536. Scene.prototype.getCachedEffect = function () {
  24537. return this._cachedEffect;
  24538. };
  24539. /**
  24540. * Gets the cached visibility state (ie. the latest rendered one)
  24541. * @returns the cached visibility state
  24542. */
  24543. Scene.prototype.getCachedVisibility = function () {
  24544. return this._cachedVisibility;
  24545. };
  24546. /**
  24547. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24548. * @param material defines the current material
  24549. * @param effect defines the current effect
  24550. * @param visibility defines the current visibility state
  24551. * @returns true if one parameter is not cached
  24552. */
  24553. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24554. if (visibility === void 0) { visibility = 1; }
  24555. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24556. };
  24557. /**
  24558. * Gets the bounding box renderer associated with the scene
  24559. * @returns a BoundingBoxRenderer
  24560. */
  24561. Scene.prototype.getBoundingBoxRenderer = function () {
  24562. if (!this._boundingBoxRenderer) {
  24563. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24564. }
  24565. return this._boundingBoxRenderer;
  24566. };
  24567. /**
  24568. * Gets the outline renderer associated with the scene
  24569. * @returns a OutlineRenderer
  24570. */
  24571. Scene.prototype.getOutlineRenderer = function () {
  24572. return this._outlineRenderer;
  24573. };
  24574. /**
  24575. * Gets the engine associated with the scene
  24576. * @returns an Engine
  24577. */
  24578. Scene.prototype.getEngine = function () {
  24579. return this._engine;
  24580. };
  24581. /**
  24582. * Gets the total number of vertices rendered per frame
  24583. * @returns the total number of vertices rendered per frame
  24584. */
  24585. Scene.prototype.getTotalVertices = function () {
  24586. return this._totalVertices.current;
  24587. };
  24588. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24589. /**
  24590. * Gets the performance counter for total vertices
  24591. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24592. */
  24593. get: function () {
  24594. return this._totalVertices;
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. /**
  24600. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24601. * @returns the total number of active indices rendered per frame
  24602. */
  24603. Scene.prototype.getActiveIndices = function () {
  24604. return this._activeIndices.current;
  24605. };
  24606. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24607. /**
  24608. * Gets the performance counter for active indices
  24609. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24610. */
  24611. get: function () {
  24612. return this._activeIndices;
  24613. },
  24614. enumerable: true,
  24615. configurable: true
  24616. });
  24617. /**
  24618. * Gets the total number of active particles rendered per frame
  24619. * @returns the total number of active particles rendered per frame
  24620. */
  24621. Scene.prototype.getActiveParticles = function () {
  24622. return this._activeParticles.current;
  24623. };
  24624. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24625. /**
  24626. * Gets the performance counter for active particles
  24627. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24628. */
  24629. get: function () {
  24630. return this._activeParticles;
  24631. },
  24632. enumerable: true,
  24633. configurable: true
  24634. });
  24635. /**
  24636. * Gets the total number of active bones rendered per frame
  24637. * @returns the total number of active bones rendered per frame
  24638. */
  24639. Scene.prototype.getActiveBones = function () {
  24640. return this._activeBones.current;
  24641. };
  24642. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24643. /**
  24644. * Gets the performance counter for active bones
  24645. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24646. */
  24647. get: function () {
  24648. return this._activeBones;
  24649. },
  24650. enumerable: true,
  24651. configurable: true
  24652. });
  24653. /** @hidden */
  24654. Scene.prototype.getInterFramePerfCounter = function () {
  24655. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24656. return 0;
  24657. };
  24658. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24659. /** @hidden */
  24660. get: function () {
  24661. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24662. return null;
  24663. },
  24664. enumerable: true,
  24665. configurable: true
  24666. });
  24667. /** @hidden */
  24668. Scene.prototype.getLastFrameDuration = function () {
  24669. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24670. return 0;
  24671. };
  24672. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24673. /** @hidden */
  24674. get: function () {
  24675. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24676. return null;
  24677. },
  24678. enumerable: true,
  24679. configurable: true
  24680. });
  24681. /** @hidden */
  24682. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24683. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24684. return 0;
  24685. };
  24686. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24687. /** @hidden */
  24688. get: function () {
  24689. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24690. return null;
  24691. },
  24692. enumerable: true,
  24693. configurable: true
  24694. });
  24695. /**
  24696. * Gets the array of active meshes
  24697. * @returns an array of AbstractMesh
  24698. */
  24699. Scene.prototype.getActiveMeshes = function () {
  24700. return this._activeMeshes;
  24701. };
  24702. /** @hidden */
  24703. Scene.prototype.getRenderTargetsDuration = function () {
  24704. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24705. return 0;
  24706. };
  24707. /** @hidden */
  24708. Scene.prototype.getRenderDuration = function () {
  24709. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24710. return 0;
  24711. };
  24712. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24713. /** @hidden */
  24714. get: function () {
  24715. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24716. return null;
  24717. },
  24718. enumerable: true,
  24719. configurable: true
  24720. });
  24721. /** @hidden */
  24722. Scene.prototype.getParticlesDuration = function () {
  24723. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24724. return 0;
  24725. };
  24726. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24727. /** @hidden */
  24728. get: function () {
  24729. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24730. return null;
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. /** @hidden */
  24736. Scene.prototype.getSpritesDuration = function () {
  24737. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24738. return 0;
  24739. };
  24740. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24741. /** @hidden */
  24742. get: function () {
  24743. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24744. return null;
  24745. },
  24746. enumerable: true,
  24747. configurable: true
  24748. });
  24749. /**
  24750. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24751. * @returns a number
  24752. */
  24753. Scene.prototype.getAnimationRatio = function () {
  24754. return this._animationRatio;
  24755. };
  24756. /**
  24757. * Gets an unique Id for the current frame
  24758. * @returns a number
  24759. */
  24760. Scene.prototype.getRenderId = function () {
  24761. return this._renderId;
  24762. };
  24763. /** Call this function if you want to manually increment the render Id*/
  24764. Scene.prototype.incrementRenderId = function () {
  24765. this._renderId++;
  24766. };
  24767. Scene.prototype._updatePointerPosition = function (evt) {
  24768. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24769. if (!canvasRect) {
  24770. return;
  24771. }
  24772. this._pointerX = evt.clientX - canvasRect.left;
  24773. this._pointerY = evt.clientY - canvasRect.top;
  24774. this._unTranslatedPointerX = this._pointerX;
  24775. this._unTranslatedPointerY = this._pointerY;
  24776. };
  24777. Scene.prototype._createUbo = function () {
  24778. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24779. this._sceneUbo.addUniform("viewProjection", 16);
  24780. this._sceneUbo.addUniform("view", 16);
  24781. };
  24782. Scene.prototype._createAlternateUbo = function () {
  24783. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24784. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24785. this._alternateSceneUbo.addUniform("view", 16);
  24786. };
  24787. // Pointers handling
  24788. /**
  24789. * Use this method to simulate a pointer move on a mesh
  24790. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24791. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24792. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24793. * @returns the current scene
  24794. */
  24795. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24796. var evt = new PointerEvent("pointermove", pointerEventInit);
  24797. return this._processPointerMove(pickResult, evt);
  24798. };
  24799. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24800. var canvas = this._engine.getRenderingCanvas();
  24801. if (!canvas) {
  24802. return this;
  24803. }
  24804. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24805. this.setPointerOverSprite(null);
  24806. this.setPointerOverMesh(pickResult.pickedMesh);
  24807. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24808. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24809. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24810. }
  24811. else {
  24812. canvas.style.cursor = this.hoverCursor;
  24813. }
  24814. }
  24815. else {
  24816. canvas.style.cursor = this.defaultCursor;
  24817. }
  24818. }
  24819. else {
  24820. this.setPointerOverMesh(null);
  24821. // Sprites
  24822. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24823. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24824. this.setPointerOverSprite(pickResult.pickedSprite);
  24825. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24826. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24827. }
  24828. else {
  24829. canvas.style.cursor = this.hoverCursor;
  24830. }
  24831. }
  24832. else {
  24833. this.setPointerOverSprite(null);
  24834. // Restore pointer
  24835. canvas.style.cursor = this.defaultCursor;
  24836. }
  24837. }
  24838. if (pickResult) {
  24839. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24840. if (this.onPointerMove) {
  24841. this.onPointerMove(evt, pickResult, type);
  24842. }
  24843. if (this.onPointerObservable.hasObservers()) {
  24844. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24845. this.onPointerObservable.notifyObservers(pi, type);
  24846. }
  24847. }
  24848. return this;
  24849. };
  24850. /**
  24851. * Use this method to simulate a pointer down on a mesh
  24852. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24853. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24854. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24855. * @returns the current scene
  24856. */
  24857. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24858. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24859. return this._processPointerDown(pickResult, evt);
  24860. };
  24861. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24862. var _this = this;
  24863. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24864. this._pickedDownMesh = pickResult.pickedMesh;
  24865. var actionManager = pickResult.pickedMesh.actionManager;
  24866. if (actionManager) {
  24867. if (actionManager.hasPickTriggers) {
  24868. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24869. switch (evt.button) {
  24870. case 0:
  24871. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24872. break;
  24873. case 1:
  24874. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24875. break;
  24876. case 2:
  24877. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24878. break;
  24879. }
  24880. }
  24881. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24882. window.setTimeout(function () {
  24883. 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);
  24884. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24885. if (_this._totalPointersPressed !== 0 &&
  24886. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24887. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24888. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24889. _this._startingPointerTime = 0;
  24890. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24891. }
  24892. }
  24893. }, Scene.LongPressDelay);
  24894. }
  24895. }
  24896. }
  24897. if (pickResult) {
  24898. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24899. if (this.onPointerDown) {
  24900. this.onPointerDown(evt, pickResult, type);
  24901. }
  24902. if (this.onPointerObservable.hasObservers()) {
  24903. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24904. this.onPointerObservable.notifyObservers(pi, type);
  24905. }
  24906. }
  24907. return this;
  24908. };
  24909. /**
  24910. * Use this method to simulate a pointer up on a mesh
  24911. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24912. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24913. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24914. * @returns the current scene
  24915. */
  24916. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24917. var evt = new PointerEvent("pointerup", pointerEventInit);
  24918. var clickInfo = new ClickInfo();
  24919. clickInfo.singleClick = true;
  24920. clickInfo.ignore = true;
  24921. return this._processPointerUp(pickResult, evt, clickInfo);
  24922. };
  24923. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24924. if (pickResult && pickResult && pickResult.pickedMesh) {
  24925. this._pickedUpMesh = pickResult.pickedMesh;
  24926. if (this._pickedDownMesh === this._pickedUpMesh) {
  24927. if (this.onPointerPick) {
  24928. this.onPointerPick(evt, pickResult);
  24929. }
  24930. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24931. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24932. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24933. this.onPointerObservable.notifyObservers(pi, type_1);
  24934. }
  24935. }
  24936. if (pickResult.pickedMesh.actionManager) {
  24937. if (clickInfo.ignore) {
  24938. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24939. }
  24940. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24941. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24942. }
  24943. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24944. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24945. }
  24946. }
  24947. }
  24948. if (this._pickedDownMesh &&
  24949. this._pickedDownMesh.actionManager &&
  24950. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24951. this._pickedDownMesh !== this._pickedUpMesh) {
  24952. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24953. }
  24954. var type = BABYLON.PointerEventTypes.POINTERUP;
  24955. if (this.onPointerObservable.hasObservers()) {
  24956. if (!clickInfo.ignore) {
  24957. if (!clickInfo.hasSwiped) {
  24958. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24959. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24960. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24961. this.onPointerObservable.notifyObservers(pi, type_2);
  24962. }
  24963. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24964. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24965. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24966. this.onPointerObservable.notifyObservers(pi, type_3);
  24967. }
  24968. }
  24969. }
  24970. else {
  24971. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24972. this.onPointerObservable.notifyObservers(pi, type);
  24973. }
  24974. }
  24975. if (this.onPointerUp) {
  24976. this.onPointerUp(evt, pickResult, type);
  24977. }
  24978. return this;
  24979. };
  24980. /**
  24981. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24982. * @param attachUp defines if you want to attach events to pointerup
  24983. * @param attachDown defines if you want to attach events to pointerdown
  24984. * @param attachMove defines if you want to attach events to pointermove
  24985. */
  24986. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24987. var _this = this;
  24988. if (attachUp === void 0) { attachUp = true; }
  24989. if (attachDown === void 0) { attachDown = true; }
  24990. if (attachMove === void 0) { attachMove = true; }
  24991. this._initActionManager = function (act, clickInfo) {
  24992. if (!_this._meshPickProceed) {
  24993. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24994. _this._currentPickResult = pickResult;
  24995. if (pickResult) {
  24996. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24997. }
  24998. _this._meshPickProceed = true;
  24999. }
  25000. return act;
  25001. };
  25002. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25003. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25004. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25005. btn !== _this._previousButtonPressed) {
  25006. _this._doubleClickOccured = false;
  25007. clickInfo.singleClick = true;
  25008. clickInfo.ignore = false;
  25009. cb(clickInfo, _this._currentPickResult);
  25010. }
  25011. };
  25012. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25013. var clickInfo = new ClickInfo();
  25014. _this._currentPickResult = null;
  25015. var act = null;
  25016. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25017. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25018. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25019. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25020. act = _this._initActionManager(act, clickInfo);
  25021. if (act)
  25022. checkPicking = act.hasPickTriggers;
  25023. }
  25024. if (checkPicking) {
  25025. var btn = evt.button;
  25026. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25027. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25028. if (!clickInfo.hasSwiped) {
  25029. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25030. if (!checkSingleClickImmediately) {
  25031. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25032. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25033. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25034. act = _this._initActionManager(act, clickInfo);
  25035. if (act)
  25036. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25037. }
  25038. }
  25039. if (checkSingleClickImmediately) {
  25040. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25041. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25042. btn !== _this._previousButtonPressed) {
  25043. clickInfo.singleClick = true;
  25044. cb(clickInfo, _this._currentPickResult);
  25045. }
  25046. }
  25047. // at least one double click is required to be check and exclusive double click is enabled
  25048. else {
  25049. // wait that no double click has been raised during the double click delay
  25050. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25051. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25052. }
  25053. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25054. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25055. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25056. act = _this._initActionManager(act, clickInfo);
  25057. if (act)
  25058. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25059. }
  25060. if (checkDoubleClick) {
  25061. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25062. if (btn === _this._previousButtonPressed &&
  25063. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25064. !_this._doubleClickOccured) {
  25065. // pointer has not moved for 2 clicks, it's a double click
  25066. if (!clickInfo.hasSwiped &&
  25067. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25068. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25069. _this._previousStartingPointerTime = 0;
  25070. _this._doubleClickOccured = true;
  25071. clickInfo.doubleClick = true;
  25072. clickInfo.ignore = false;
  25073. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25074. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25075. }
  25076. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25077. cb(clickInfo, _this._currentPickResult);
  25078. }
  25079. // if the two successive clicks are too far, it's just two simple clicks
  25080. else {
  25081. _this._doubleClickOccured = false;
  25082. _this._previousStartingPointerTime = _this._startingPointerTime;
  25083. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25084. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25085. _this._previousButtonPressed = btn;
  25086. if (Scene.ExclusiveDoubleClickMode) {
  25087. if (_this._previousDelayedSimpleClickTimeout) {
  25088. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25089. }
  25090. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25091. cb(clickInfo, _this._previousPickResult);
  25092. }
  25093. else {
  25094. cb(clickInfo, _this._currentPickResult);
  25095. }
  25096. }
  25097. }
  25098. // just the first click of the double has been raised
  25099. else {
  25100. _this._doubleClickOccured = false;
  25101. _this._previousStartingPointerTime = _this._startingPointerTime;
  25102. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25103. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25104. _this._previousButtonPressed = btn;
  25105. }
  25106. }
  25107. }
  25108. }
  25109. clickInfo.ignore = true;
  25110. cb(clickInfo, _this._currentPickResult);
  25111. };
  25112. this._spritePredicate = function (sprite) {
  25113. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25114. };
  25115. this._onPointerMove = function (evt) {
  25116. _this._updatePointerPosition(evt);
  25117. // PreObservable support
  25118. if (_this.onPrePointerObservable.hasObservers()) {
  25119. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25120. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25121. _this.onPrePointerObservable.notifyObservers(pi, type);
  25122. if (pi.skipOnPointerObservable) {
  25123. return;
  25124. }
  25125. }
  25126. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25127. return;
  25128. }
  25129. if (!_this.pointerMovePredicate) {
  25130. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25131. }
  25132. // Meshes
  25133. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25134. _this._processPointerMove(pickResult, evt);
  25135. };
  25136. this._onPointerDown = function (evt) {
  25137. _this._totalPointersPressed++;
  25138. _this._pickedDownMesh = null;
  25139. _this._meshPickProceed = false;
  25140. _this._updatePointerPosition(evt);
  25141. if (_this.preventDefaultOnPointerDown && canvas) {
  25142. evt.preventDefault();
  25143. canvas.focus();
  25144. }
  25145. // PreObservable support
  25146. if (_this.onPrePointerObservable.hasObservers()) {
  25147. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25148. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25149. _this.onPrePointerObservable.notifyObservers(pi, type);
  25150. if (pi.skipOnPointerObservable) {
  25151. return;
  25152. }
  25153. }
  25154. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25155. return;
  25156. }
  25157. _this._startingPointerPosition.x = _this._pointerX;
  25158. _this._startingPointerPosition.y = _this._pointerY;
  25159. _this._startingPointerTime = Date.now();
  25160. if (!_this.pointerDownPredicate) {
  25161. _this.pointerDownPredicate = function (mesh) {
  25162. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25163. };
  25164. }
  25165. // Meshes
  25166. _this._pickedDownMesh = null;
  25167. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25168. _this._processPointerDown(pickResult, evt);
  25169. // Sprites
  25170. _this._pickedDownSprite = null;
  25171. if (_this.spriteManagers.length > 0) {
  25172. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25173. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25174. if (pickResult.pickedSprite.actionManager) {
  25175. _this._pickedDownSprite = pickResult.pickedSprite;
  25176. switch (evt.button) {
  25177. case 0:
  25178. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25179. break;
  25180. case 1:
  25181. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25182. break;
  25183. case 2:
  25184. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25185. break;
  25186. }
  25187. if (pickResult.pickedSprite.actionManager) {
  25188. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25189. }
  25190. }
  25191. }
  25192. }
  25193. };
  25194. this._onPointerUp = function (evt) {
  25195. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25196. return; // So we need to test it the pointer down was pressed before.
  25197. }
  25198. _this._totalPointersPressed--;
  25199. _this._pickedUpMesh = null;
  25200. _this._meshPickProceed = false;
  25201. _this._updatePointerPosition(evt);
  25202. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25203. // PreObservable support
  25204. if (_this.onPrePointerObservable.hasObservers()) {
  25205. if (!clickInfo.ignore) {
  25206. if (!clickInfo.hasSwiped) {
  25207. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25208. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25209. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25210. _this.onPrePointerObservable.notifyObservers(pi, type);
  25211. if (pi.skipOnPointerObservable) {
  25212. return;
  25213. }
  25214. }
  25215. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25216. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25217. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25218. _this.onPrePointerObservable.notifyObservers(pi, type);
  25219. if (pi.skipOnPointerObservable) {
  25220. return;
  25221. }
  25222. }
  25223. }
  25224. }
  25225. else {
  25226. var type = BABYLON.PointerEventTypes.POINTERUP;
  25227. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25228. _this.onPrePointerObservable.notifyObservers(pi, type);
  25229. if (pi.skipOnPointerObservable) {
  25230. return;
  25231. }
  25232. }
  25233. }
  25234. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25235. return;
  25236. }
  25237. if (!_this.pointerUpPredicate) {
  25238. _this.pointerUpPredicate = function (mesh) {
  25239. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25240. };
  25241. }
  25242. // Meshes
  25243. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25244. _this._initActionManager(null, clickInfo);
  25245. }
  25246. if (!pickResult) {
  25247. pickResult = _this._currentPickResult;
  25248. }
  25249. _this._processPointerUp(pickResult, evt, clickInfo);
  25250. // Sprites
  25251. if (_this.spriteManagers.length > 0) {
  25252. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25253. if (spritePickResult) {
  25254. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25255. if (spritePickResult.pickedSprite.actionManager) {
  25256. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25257. if (spritePickResult.pickedSprite.actionManager) {
  25258. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25259. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25260. }
  25261. }
  25262. }
  25263. }
  25264. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25265. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25266. }
  25267. }
  25268. }
  25269. _this._previousPickResult = _this._currentPickResult;
  25270. });
  25271. };
  25272. this._onKeyDown = function (evt) {
  25273. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25274. if (_this.onPreKeyboardObservable.hasObservers()) {
  25275. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25276. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25277. if (pi.skipOnPointerObservable) {
  25278. return;
  25279. }
  25280. }
  25281. if (_this.onKeyboardObservable.hasObservers()) {
  25282. var pi = new BABYLON.KeyboardInfo(type, evt);
  25283. _this.onKeyboardObservable.notifyObservers(pi, type);
  25284. }
  25285. if (_this.actionManager) {
  25286. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25287. }
  25288. };
  25289. this._onKeyUp = function (evt) {
  25290. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25291. if (_this.onPreKeyboardObservable.hasObservers()) {
  25292. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25293. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25294. if (pi.skipOnPointerObservable) {
  25295. return;
  25296. }
  25297. }
  25298. if (_this.onKeyboardObservable.hasObservers()) {
  25299. var pi = new BABYLON.KeyboardInfo(type, evt);
  25300. _this.onKeyboardObservable.notifyObservers(pi, type);
  25301. }
  25302. if (_this.actionManager) {
  25303. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25304. }
  25305. };
  25306. var engine = this.getEngine();
  25307. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25308. if (!canvas) {
  25309. return;
  25310. }
  25311. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25312. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25313. });
  25314. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25315. if (!canvas) {
  25316. return;
  25317. }
  25318. canvas.removeEventListener("keydown", _this._onKeyDown);
  25319. canvas.removeEventListener("keyup", _this._onKeyUp);
  25320. });
  25321. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25322. var canvas = this._engine.getRenderingCanvas();
  25323. if (!canvas) {
  25324. return;
  25325. }
  25326. if (attachMove) {
  25327. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25328. // Wheel
  25329. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25330. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25331. }
  25332. if (attachDown) {
  25333. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25334. }
  25335. if (attachUp) {
  25336. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25337. }
  25338. canvas.tabIndex = 1;
  25339. };
  25340. /** Detaches all event handlers*/
  25341. Scene.prototype.detachControl = function () {
  25342. var engine = this.getEngine();
  25343. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25344. var canvas = engine.getRenderingCanvas();
  25345. if (!canvas) {
  25346. return;
  25347. }
  25348. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25349. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25350. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25351. if (this._onCanvasBlurObserver) {
  25352. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25353. }
  25354. if (this._onCanvasFocusObserver) {
  25355. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25356. }
  25357. // Wheel
  25358. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25359. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25360. // Keyboard
  25361. canvas.removeEventListener("keydown", this._onKeyDown);
  25362. canvas.removeEventListener("keyup", this._onKeyUp);
  25363. // Observables
  25364. this.onKeyboardObservable.clear();
  25365. this.onPreKeyboardObservable.clear();
  25366. this.onPointerObservable.clear();
  25367. this.onPrePointerObservable.clear();
  25368. };
  25369. /**
  25370. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25371. * Delay loaded resources are not taking in account
  25372. * @return true if all required resources are ready
  25373. */
  25374. Scene.prototype.isReady = function () {
  25375. if (this._isDisposed) {
  25376. return false;
  25377. }
  25378. if (this._pendingData.length > 0) {
  25379. return false;
  25380. }
  25381. var index;
  25382. var engine = this.getEngine();
  25383. // Geometries
  25384. for (index = 0; index < this._geometries.length; index++) {
  25385. var geometry = this._geometries[index];
  25386. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25387. return false;
  25388. }
  25389. }
  25390. // Meshes
  25391. for (index = 0; index < this.meshes.length; index++) {
  25392. var mesh = this.meshes[index];
  25393. if (!mesh.isEnabled()) {
  25394. continue;
  25395. }
  25396. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25397. continue;
  25398. }
  25399. if (!mesh.isReady(true)) {
  25400. return false;
  25401. }
  25402. // Effect layers
  25403. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25404. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25405. var layer = _a[_i];
  25406. if (!layer.hasMesh(mesh)) {
  25407. continue;
  25408. }
  25409. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25410. var subMesh = _c[_b];
  25411. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25412. return false;
  25413. }
  25414. }
  25415. }
  25416. }
  25417. // Post-processes
  25418. if (this.activeCameras && this.activeCameras.length > 0) {
  25419. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25420. var camera = _e[_d];
  25421. if (!camera.isReady(true)) {
  25422. return false;
  25423. }
  25424. }
  25425. }
  25426. else if (this.activeCamera) {
  25427. if (!this.activeCamera.isReady(true)) {
  25428. return false;
  25429. }
  25430. }
  25431. // Particles
  25432. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25433. var particleSystem = _g[_f];
  25434. if (!particleSystem.isReady()) {
  25435. return false;
  25436. }
  25437. }
  25438. return true;
  25439. };
  25440. /** Resets all cached information relative to material (including effect and visibility) */
  25441. Scene.prototype.resetCachedMaterial = function () {
  25442. this._cachedMaterial = null;
  25443. this._cachedEffect = null;
  25444. this._cachedVisibility = null;
  25445. };
  25446. /**
  25447. * Registers a function to be called before every frame render
  25448. * @param func defines the function to register
  25449. */
  25450. Scene.prototype.registerBeforeRender = function (func) {
  25451. this.onBeforeRenderObservable.add(func);
  25452. };
  25453. /**
  25454. * Unregisters a function called before every frame render
  25455. * @param func defines the function to unregister
  25456. */
  25457. Scene.prototype.unregisterBeforeRender = function (func) {
  25458. this.onBeforeRenderObservable.removeCallback(func);
  25459. };
  25460. /**
  25461. * Registers a function to be called after every frame render
  25462. * @param func defines the function to register
  25463. */
  25464. Scene.prototype.registerAfterRender = function (func) {
  25465. this.onAfterRenderObservable.add(func);
  25466. };
  25467. /**
  25468. * Unregisters a function called after every frame render
  25469. * @param func defines the function to unregister
  25470. */
  25471. Scene.prototype.unregisterAfterRender = function (func) {
  25472. this.onAfterRenderObservable.removeCallback(func);
  25473. };
  25474. Scene.prototype._executeOnceBeforeRender = function (func) {
  25475. var _this = this;
  25476. var execFunc = function () {
  25477. func();
  25478. setTimeout(function () {
  25479. _this.unregisterBeforeRender(execFunc);
  25480. });
  25481. };
  25482. this.registerBeforeRender(execFunc);
  25483. };
  25484. /**
  25485. * The provided function will run before render once and will be disposed afterwards.
  25486. * A timeout delay can be provided so that the function will be executed in N ms.
  25487. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25488. * @param func The function to be executed.
  25489. * @param timeout optional delay in ms
  25490. */
  25491. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25492. var _this = this;
  25493. if (timeout !== undefined) {
  25494. setTimeout(function () {
  25495. _this._executeOnceBeforeRender(func);
  25496. }, timeout);
  25497. }
  25498. else {
  25499. this._executeOnceBeforeRender(func);
  25500. }
  25501. };
  25502. /** @hidden */
  25503. Scene.prototype._addPendingData = function (data) {
  25504. this._pendingData.push(data);
  25505. };
  25506. /** @hidden */
  25507. Scene.prototype._removePendingData = function (data) {
  25508. var wasLoading = this.isLoading;
  25509. var index = this._pendingData.indexOf(data);
  25510. if (index !== -1) {
  25511. this._pendingData.splice(index, 1);
  25512. }
  25513. if (wasLoading && !this.isLoading) {
  25514. this.onDataLoadedObservable.notifyObservers(this);
  25515. }
  25516. };
  25517. /**
  25518. * Returns the number of items waiting to be loaded
  25519. * @returns the number of items waiting to be loaded
  25520. */
  25521. Scene.prototype.getWaitingItemsCount = function () {
  25522. return this._pendingData.length;
  25523. };
  25524. Object.defineProperty(Scene.prototype, "isLoading", {
  25525. /**
  25526. * Returns a boolean indicating if the scene is still loading data
  25527. */
  25528. get: function () {
  25529. return this._pendingData.length > 0;
  25530. },
  25531. enumerable: true,
  25532. configurable: true
  25533. });
  25534. /**
  25535. * Registers a function to be executed when the scene is ready
  25536. * @param {Function} func - the function to be executed
  25537. */
  25538. Scene.prototype.executeWhenReady = function (func) {
  25539. var _this = this;
  25540. this.onReadyObservable.add(func);
  25541. if (this._executeWhenReadyTimeoutId !== -1) {
  25542. return;
  25543. }
  25544. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25545. _this._checkIsReady();
  25546. }, 150);
  25547. };
  25548. /**
  25549. * Returns a promise that resolves when the scene is ready
  25550. * @returns A promise that resolves when the scene is ready
  25551. */
  25552. Scene.prototype.whenReadyAsync = function () {
  25553. var _this = this;
  25554. return new Promise(function (resolve) {
  25555. _this.executeWhenReady(function () {
  25556. resolve();
  25557. });
  25558. });
  25559. };
  25560. /** @hidden */
  25561. Scene.prototype._checkIsReady = function () {
  25562. var _this = this;
  25563. if (this.isReady()) {
  25564. this.onReadyObservable.notifyObservers(this);
  25565. this.onReadyObservable.clear();
  25566. this._executeWhenReadyTimeoutId = -1;
  25567. return;
  25568. }
  25569. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25570. _this._checkIsReady();
  25571. }, 150);
  25572. };
  25573. // Animations
  25574. /**
  25575. * Will start the animation sequence of a given target
  25576. * @param target defines the target
  25577. * @param from defines from which frame should animation start
  25578. * @param to defines until which frame should animation run.
  25579. * @param weight defines the weight to apply to the animation (1.0 by default)
  25580. * @param loop defines if the animation loops
  25581. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25582. * @param onAnimationEnd defines the function to be executed when the animation ends
  25583. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25584. * @returns the animatable object created for this animation
  25585. */
  25586. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25587. if (weight === void 0) { weight = 1.0; }
  25588. if (speedRatio === void 0) { speedRatio = 1.0; }
  25589. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25590. returnedAnimatable.weight = weight;
  25591. return returnedAnimatable;
  25592. };
  25593. /**
  25594. * Will start the animation sequence of a given target
  25595. * @param target defines the target
  25596. * @param from defines from which frame should animation start
  25597. * @param to defines until which frame should animation run.
  25598. * @param loop defines if the animation loops
  25599. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25600. * @param onAnimationEnd defines the function to be executed when the animation ends
  25601. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25602. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25603. * @returns the animatable object created for this animation
  25604. */
  25605. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25606. if (speedRatio === void 0) { speedRatio = 1.0; }
  25607. if (stopCurrent === void 0) { stopCurrent = true; }
  25608. if (from > to && speedRatio > 0) {
  25609. speedRatio *= -1;
  25610. }
  25611. if (stopCurrent) {
  25612. this.stopAnimation(target);
  25613. }
  25614. if (!animatable) {
  25615. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25616. }
  25617. // Local animations
  25618. if (target.animations) {
  25619. animatable.appendAnimations(target, target.animations);
  25620. }
  25621. // Children animations
  25622. if (target.getAnimatables) {
  25623. var animatables = target.getAnimatables();
  25624. for (var index = 0; index < animatables.length; index++) {
  25625. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25626. }
  25627. }
  25628. animatable.reset();
  25629. return animatable;
  25630. };
  25631. /**
  25632. * Begin a new animation on a given node
  25633. * @param target defines the target where the animation will take place
  25634. * @param animations defines the list of animations to start
  25635. * @param from defines the initial value
  25636. * @param to defines the final value
  25637. * @param loop defines if you want animation to loop (off by default)
  25638. * @param speedRatio defines the speed ratio to apply to all animations
  25639. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25640. * @returns the list of created animatables
  25641. */
  25642. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25643. if (speedRatio === undefined) {
  25644. speedRatio = 1.0;
  25645. }
  25646. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25647. return animatable;
  25648. };
  25649. /**
  25650. * Begin a new animation on a given node and its hierarchy
  25651. * @param target defines the root node where the animation will take place
  25652. * @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.
  25653. * @param animations defines the list of animations to start
  25654. * @param from defines the initial value
  25655. * @param to defines the final value
  25656. * @param loop defines if you want animation to loop (off by default)
  25657. * @param speedRatio defines the speed ratio to apply to all animations
  25658. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25659. * @returns the list of animatables created for all nodes
  25660. */
  25661. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25662. var children = target.getDescendants(directDescendantsOnly);
  25663. var result = [];
  25664. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25665. var child = children_1[_i];
  25666. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25667. }
  25668. return result;
  25669. };
  25670. /**
  25671. * Gets the animatable associated with a specific target
  25672. * @param target defines the target of the animatable
  25673. * @returns the required animatable if found
  25674. */
  25675. Scene.prototype.getAnimatableByTarget = function (target) {
  25676. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25677. if (this._activeAnimatables[index].target === target) {
  25678. return this._activeAnimatables[index];
  25679. }
  25680. }
  25681. return null;
  25682. };
  25683. /**
  25684. * Gets all animatables associated with a given target
  25685. * @param target defines the target to look animatables for
  25686. * @returns an array of Animatables
  25687. */
  25688. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25689. var result = [];
  25690. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25691. if (this._activeAnimatables[index].target === target) {
  25692. result.push(this._activeAnimatables[index]);
  25693. }
  25694. }
  25695. return result;
  25696. };
  25697. Object.defineProperty(Scene.prototype, "animatables", {
  25698. /**
  25699. * Gets all animatable attached to the scene
  25700. */
  25701. get: function () {
  25702. return this._activeAnimatables;
  25703. },
  25704. enumerable: true,
  25705. configurable: true
  25706. });
  25707. /**
  25708. * Will stop the animation of the given target
  25709. * @param target - the target
  25710. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25711. */
  25712. Scene.prototype.stopAnimation = function (target, animationName) {
  25713. var animatables = this.getAllAnimatablesByTarget(target);
  25714. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25715. var animatable = animatables_1[_i];
  25716. animatable.stop(animationName);
  25717. }
  25718. };
  25719. /**
  25720. * Stops and removes all animations that have been applied to the scene
  25721. */
  25722. Scene.prototype.stopAllAnimations = function () {
  25723. if (this._activeAnimatables) {
  25724. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25725. this._activeAnimatables[i].stop();
  25726. }
  25727. this._activeAnimatables = [];
  25728. }
  25729. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25730. var group = _a[_i];
  25731. group.stop();
  25732. }
  25733. };
  25734. Scene.prototype._animate = function () {
  25735. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25736. return;
  25737. }
  25738. // Getting time
  25739. var now = BABYLON.Tools.Now;
  25740. if (!this._animationTimeLast) {
  25741. if (this._pendingData.length > 0) {
  25742. return;
  25743. }
  25744. this._animationTimeLast = now;
  25745. }
  25746. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25747. this._animationTime += deltaTime;
  25748. this._animationTimeLast = now;
  25749. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25750. this._activeAnimatables[index]._animate(this._animationTime);
  25751. }
  25752. // Late animation bindings
  25753. this._processLateAnimationBindings();
  25754. };
  25755. /** @hidden */
  25756. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25757. var target = runtimeAnimation.target;
  25758. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25759. if (!target._lateAnimationHolders) {
  25760. target._lateAnimationHolders = {};
  25761. }
  25762. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25763. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25764. totalWeight: 0,
  25765. animations: []
  25766. };
  25767. }
  25768. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25769. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25770. };
  25771. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25772. var normalizer = 1.0;
  25773. var finalPosition = BABYLON.Tmp.Vector3[0];
  25774. var finalScaling = BABYLON.Tmp.Vector3[1];
  25775. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25776. var startIndex = 0;
  25777. var originalAnimation = holder.animations[0];
  25778. var scale = 1;
  25779. if (holder.totalWeight < 1.0) {
  25780. // We need to mix the original value in
  25781. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25782. scale = 1.0 - holder.totalWeight;
  25783. }
  25784. else {
  25785. startIndex = 1;
  25786. // We need to normalize the weights
  25787. normalizer = holder.totalWeight;
  25788. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25789. scale = originalAnimation.weight / normalizer;
  25790. if (scale == 1) {
  25791. return originalAnimation.currentValue;
  25792. }
  25793. }
  25794. finalScaling.scaleInPlace(scale);
  25795. finalPosition.scaleInPlace(scale);
  25796. finalQuaternion.scaleInPlace(scale);
  25797. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25798. var runtimeAnimation = holder.animations[animIndex];
  25799. var scale = runtimeAnimation.weight / normalizer;
  25800. var currentPosition = BABYLON.Tmp.Vector3[2];
  25801. var currentScaling = BABYLON.Tmp.Vector3[3];
  25802. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25803. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25804. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25805. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25806. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25807. }
  25808. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25809. return originalAnimation._workValue;
  25810. };
  25811. Scene.prototype._processLateAnimationBindings = function () {
  25812. if (!this._registeredForLateAnimationBindings.length) {
  25813. return;
  25814. }
  25815. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25816. var target = this._registeredForLateAnimationBindings.data[index];
  25817. for (var path in target._lateAnimationHolders) {
  25818. var holder = target._lateAnimationHolders[path];
  25819. var originalAnimation = holder.animations[0];
  25820. var originalValue = originalAnimation.originalValue;
  25821. var finalTarget = originalAnimation.target;
  25822. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25823. var finalValue = void 0;
  25824. if (matrixDecomposeMode) {
  25825. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25826. }
  25827. else {
  25828. var startIndex = 0;
  25829. var normalizer = 1.0;
  25830. if (holder.totalWeight < 1.0) {
  25831. // We need to mix the original value in
  25832. if (originalValue.scale) {
  25833. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25834. }
  25835. else {
  25836. finalValue = originalValue * (1.0 - holder.totalWeight);
  25837. }
  25838. }
  25839. else {
  25840. // We need to normalize the weights
  25841. normalizer = holder.totalWeight;
  25842. var scale_1 = originalAnimation.weight / normalizer;
  25843. if (scale_1 !== 1) {
  25844. if (originalAnimation.currentValue.scale) {
  25845. finalValue = originalAnimation.currentValue.scale(scale_1);
  25846. }
  25847. else {
  25848. finalValue = originalAnimation.currentValue * scale_1;
  25849. }
  25850. }
  25851. else {
  25852. finalValue = originalAnimation.currentValue;
  25853. }
  25854. startIndex = 1;
  25855. }
  25856. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25857. var runtimeAnimation = holder.animations[animIndex];
  25858. var scale = runtimeAnimation.weight / normalizer;
  25859. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25860. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25861. }
  25862. else {
  25863. finalValue += runtimeAnimation.currentValue * scale;
  25864. }
  25865. }
  25866. }
  25867. finalTarget[path] = finalValue;
  25868. }
  25869. target._lateAnimationHolders = {};
  25870. }
  25871. this._registeredForLateAnimationBindings.reset();
  25872. };
  25873. // Matrix
  25874. /** @hidden */
  25875. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25876. this._useAlternateCameraConfiguration = active;
  25877. };
  25878. /**
  25879. * Gets the current view matrix
  25880. * @returns a Matrix
  25881. */
  25882. Scene.prototype.getViewMatrix = function () {
  25883. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25884. };
  25885. /**
  25886. * Gets the current projection matrix
  25887. * @returns a Matrix
  25888. */
  25889. Scene.prototype.getProjectionMatrix = function () {
  25890. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25891. };
  25892. /**
  25893. * Gets the current transform matrix
  25894. * @returns a Matrix made of View * Projection
  25895. */
  25896. Scene.prototype.getTransformMatrix = function () {
  25897. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25898. };
  25899. /**
  25900. * Sets the current transform matrix
  25901. * @param view defines the View matrix to use
  25902. * @param projection defines the Projection matrix to use
  25903. */
  25904. Scene.prototype.setTransformMatrix = function (view, projection) {
  25905. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25906. return;
  25907. }
  25908. this._viewUpdateFlag = view.updateFlag;
  25909. this._projectionUpdateFlag = projection.updateFlag;
  25910. this._viewMatrix = view;
  25911. this._projectionMatrix = projection;
  25912. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25913. // Update frustum
  25914. if (!this._frustumPlanes) {
  25915. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25916. }
  25917. else {
  25918. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25919. }
  25920. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25921. var otherCamera = this.activeCamera._alternateCamera;
  25922. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25923. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25924. }
  25925. if (this._sceneUbo.useUbo) {
  25926. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25927. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25928. this._sceneUbo.update();
  25929. }
  25930. };
  25931. /** @hidden */
  25932. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25933. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25934. return;
  25935. }
  25936. this._alternateViewUpdateFlag = view.updateFlag;
  25937. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25938. this._alternateViewMatrix = view;
  25939. this._alternateProjectionMatrix = projection;
  25940. if (!this._alternateTransformMatrix) {
  25941. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25942. }
  25943. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25944. if (!this._alternateSceneUbo) {
  25945. this._createAlternateUbo();
  25946. }
  25947. if (this._alternateSceneUbo.useUbo) {
  25948. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25949. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25950. this._alternateSceneUbo.update();
  25951. }
  25952. };
  25953. /**
  25954. * Gets the uniform buffer used to store scene data
  25955. * @returns a UniformBuffer
  25956. */
  25957. Scene.prototype.getSceneUniformBuffer = function () {
  25958. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25959. };
  25960. /**
  25961. * Gets an unique (relatively to the current scene) Id
  25962. * @returns an unique number for the scene
  25963. */
  25964. Scene.prototype.getUniqueId = function () {
  25965. var result = Scene._uniqueIdCounter;
  25966. Scene._uniqueIdCounter++;
  25967. return result;
  25968. };
  25969. /**
  25970. * Add a mesh to the list of scene's meshes
  25971. * @param newMesh defines the mesh to add
  25972. */
  25973. Scene.prototype.addMesh = function (newMesh) {
  25974. this.meshes.push(newMesh);
  25975. //notify the collision coordinator
  25976. if (this.collisionCoordinator) {
  25977. this.collisionCoordinator.onMeshAdded(newMesh);
  25978. }
  25979. newMesh._resyncLightSources();
  25980. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25981. };
  25982. /**
  25983. * Remove a mesh for the list of scene's meshes
  25984. * @param toRemove defines the mesh to remove
  25985. * @returns the index where the mesh was in the mesh list
  25986. */
  25987. Scene.prototype.removeMesh = function (toRemove) {
  25988. var index = this.meshes.indexOf(toRemove);
  25989. if (index !== -1) {
  25990. // Remove from the scene if mesh found
  25991. this.meshes.splice(index, 1);
  25992. }
  25993. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25994. return index;
  25995. };
  25996. /**
  25997. * Add a transform node to the list of scene's transform nodes
  25998. * @param newTransformNode defines the transform node to add
  25999. */
  26000. Scene.prototype.addTransformNode = function (newTransformNode) {
  26001. this.transformNodes.push(newTransformNode);
  26002. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26003. };
  26004. /**
  26005. * Remove a transform node for the list of scene's transform nodes
  26006. * @param toRemove defines the transform node to remove
  26007. * @returns the index where the transform node was in the transform node list
  26008. */
  26009. Scene.prototype.removeTransformNode = function (toRemove) {
  26010. var index = this.transformNodes.indexOf(toRemove);
  26011. if (index !== -1) {
  26012. // Remove from the scene if found
  26013. this.transformNodes.splice(index, 1);
  26014. }
  26015. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26016. return index;
  26017. };
  26018. /**
  26019. * Remove a skeleton for the list of scene's skeletons
  26020. * @param toRemove defines the skeleton to remove
  26021. * @returns the index where the skeleton was in the skeleton list
  26022. */
  26023. Scene.prototype.removeSkeleton = function (toRemove) {
  26024. var index = this.skeletons.indexOf(toRemove);
  26025. if (index !== -1) {
  26026. // Remove from the scene if found
  26027. this.skeletons.splice(index, 1);
  26028. }
  26029. return index;
  26030. };
  26031. /**
  26032. * Remove a morph target for the list of scene's morph targets
  26033. * @param toRemove defines the morph target to remove
  26034. * @returns the index where the morph target was in the morph target list
  26035. */
  26036. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26037. var index = this.morphTargetManagers.indexOf(toRemove);
  26038. if (index !== -1) {
  26039. // Remove from the scene if found
  26040. this.morphTargetManagers.splice(index, 1);
  26041. }
  26042. return index;
  26043. };
  26044. /**
  26045. * Remove a light for the list of scene's lights
  26046. * @param toRemove defines the light to remove
  26047. * @returns the index where the light was in the light list
  26048. */
  26049. Scene.prototype.removeLight = function (toRemove) {
  26050. var index = this.lights.indexOf(toRemove);
  26051. if (index !== -1) {
  26052. // Remove from meshes
  26053. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26054. var mesh = _a[_i];
  26055. mesh._removeLightSource(toRemove);
  26056. }
  26057. // Remove from the scene if mesh found
  26058. this.lights.splice(index, 1);
  26059. this.sortLightsByPriority();
  26060. }
  26061. this.onLightRemovedObservable.notifyObservers(toRemove);
  26062. return index;
  26063. };
  26064. /**
  26065. * Remove a camera for the list of scene's cameras
  26066. * @param toRemove defines the camera to remove
  26067. * @returns the index where the camera was in the camera list
  26068. */
  26069. Scene.prototype.removeCamera = function (toRemove) {
  26070. var index = this.cameras.indexOf(toRemove);
  26071. if (index !== -1) {
  26072. // Remove from the scene if mesh found
  26073. this.cameras.splice(index, 1);
  26074. }
  26075. // Remove from activeCameras
  26076. var index2 = this.activeCameras.indexOf(toRemove);
  26077. if (index2 !== -1) {
  26078. // Remove from the scene if mesh found
  26079. this.activeCameras.splice(index2, 1);
  26080. }
  26081. // Reset the activeCamera
  26082. if (this.activeCamera === toRemove) {
  26083. if (this.cameras.length > 0) {
  26084. this.activeCamera = this.cameras[0];
  26085. }
  26086. else {
  26087. this.activeCamera = null;
  26088. }
  26089. }
  26090. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26091. return index;
  26092. };
  26093. /**
  26094. * Remove a particle system for the list of scene's particle systems
  26095. * @param toRemove defines the particle system to remove
  26096. * @returns the index where the particle system was in the particle system list
  26097. */
  26098. Scene.prototype.removeParticleSystem = function (toRemove) {
  26099. var index = this.particleSystems.indexOf(toRemove);
  26100. if (index !== -1) {
  26101. this.particleSystems.splice(index, 1);
  26102. }
  26103. return index;
  26104. };
  26105. /**
  26106. * Remove a animation for the list of scene's animations
  26107. * @param toRemove defines the animation to remove
  26108. * @returns the index where the animation was in the animation list
  26109. */
  26110. Scene.prototype.removeAnimation = function (toRemove) {
  26111. var index = this.animations.indexOf(toRemove);
  26112. if (index !== -1) {
  26113. this.animations.splice(index, 1);
  26114. }
  26115. return index;
  26116. };
  26117. /**
  26118. * Removes the given animation group from this scene.
  26119. * @param toRemove The animation group to remove
  26120. * @returns The index of the removed animation group
  26121. */
  26122. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26123. var index = this.animationGroups.indexOf(toRemove);
  26124. if (index !== -1) {
  26125. this.animationGroups.splice(index, 1);
  26126. }
  26127. return index;
  26128. };
  26129. /**
  26130. * Removes the given multi-material from this scene.
  26131. * @param toRemove The multi-material to remove
  26132. * @returns The index of the removed multi-material
  26133. */
  26134. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26135. var index = this.multiMaterials.indexOf(toRemove);
  26136. if (index !== -1) {
  26137. this.multiMaterials.splice(index, 1);
  26138. }
  26139. return index;
  26140. };
  26141. /**
  26142. * Removes the given material from this scene.
  26143. * @param toRemove The material to remove
  26144. * @returns The index of the removed material
  26145. */
  26146. Scene.prototype.removeMaterial = function (toRemove) {
  26147. var index = this.materials.indexOf(toRemove);
  26148. if (index !== -1) {
  26149. this.materials.splice(index, 1);
  26150. }
  26151. return index;
  26152. };
  26153. /**
  26154. * Removes the given lens flare system from this scene.
  26155. * @param toRemove The lens flare system to remove
  26156. * @returns The index of the removed lens flare system
  26157. */
  26158. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26159. var index = this.lensFlareSystems.indexOf(toRemove);
  26160. if (index !== -1) {
  26161. this.lensFlareSystems.splice(index, 1);
  26162. }
  26163. return index;
  26164. };
  26165. /**
  26166. * Removes the given action manager from this scene.
  26167. * @param toRemove The action manager to remove
  26168. * @returns The index of the removed action manager
  26169. */
  26170. Scene.prototype.removeActionManager = function (toRemove) {
  26171. var index = this._actionManagers.indexOf(toRemove);
  26172. if (index !== -1) {
  26173. this._actionManagers.splice(index, 1);
  26174. }
  26175. return index;
  26176. };
  26177. /**
  26178. * Removes the given effect layer from this scene.
  26179. * @param toRemove defines the effect layer to remove
  26180. * @returns the index of the removed effect layer
  26181. */
  26182. Scene.prototype.removeEffectLayer = function (toRemove) {
  26183. var index = this.effectLayers.indexOf(toRemove);
  26184. if (index !== -1) {
  26185. this.effectLayers.splice(index, 1);
  26186. }
  26187. return index;
  26188. };
  26189. /**
  26190. * Removes the given texture from this scene.
  26191. * @param toRemove The texture to remove
  26192. * @returns The index of the removed texture
  26193. */
  26194. Scene.prototype.removeTexture = function (toRemove) {
  26195. var index = this.textures.indexOf(toRemove);
  26196. if (index !== -1) {
  26197. this.textures.splice(index, 1);
  26198. }
  26199. return index;
  26200. };
  26201. /**
  26202. * Adds the given light to this scene
  26203. * @param newLight The light to add
  26204. */
  26205. Scene.prototype.addLight = function (newLight) {
  26206. this.lights.push(newLight);
  26207. this.sortLightsByPriority();
  26208. // Add light to all meshes (To support if the light is removed and then readded)
  26209. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26210. var mesh = _a[_i];
  26211. if (mesh._lightSources.indexOf(newLight) === -1) {
  26212. mesh._lightSources.push(newLight);
  26213. mesh._resyncLightSources();
  26214. }
  26215. }
  26216. this.onNewLightAddedObservable.notifyObservers(newLight);
  26217. };
  26218. /**
  26219. * Sorts the list list based on light priorities
  26220. */
  26221. Scene.prototype.sortLightsByPriority = function () {
  26222. if (this.requireLightSorting) {
  26223. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26224. }
  26225. };
  26226. /**
  26227. * Adds the given camera to this scene
  26228. * @param newCamera The camera to add
  26229. */
  26230. Scene.prototype.addCamera = function (newCamera) {
  26231. this.cameras.push(newCamera);
  26232. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26233. };
  26234. /**
  26235. * Adds the given skeleton to this scene
  26236. * @param newSkeleton The skeleton to add
  26237. */
  26238. Scene.prototype.addSkeleton = function (newSkeleton) {
  26239. this.skeletons.push(newSkeleton);
  26240. };
  26241. /**
  26242. * Adds the given particle system to this scene
  26243. * @param newParticleSystem The particle system to add
  26244. */
  26245. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26246. this.particleSystems.push(newParticleSystem);
  26247. };
  26248. /**
  26249. * Adds the given animation to this scene
  26250. * @param newAnimation The animation to add
  26251. */
  26252. Scene.prototype.addAnimation = function (newAnimation) {
  26253. this.animations.push(newAnimation);
  26254. };
  26255. /**
  26256. * Adds the given animation group to this scene.
  26257. * @param newAnimationGroup The animation group to add
  26258. */
  26259. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26260. this.animationGroups.push(newAnimationGroup);
  26261. };
  26262. /**
  26263. * Adds the given multi-material to this scene
  26264. * @param newMultiMaterial The multi-material to add
  26265. */
  26266. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26267. this.multiMaterials.push(newMultiMaterial);
  26268. };
  26269. /**
  26270. * Adds the given material to this scene
  26271. * @param newMaterial The material to add
  26272. */
  26273. Scene.prototype.addMaterial = function (newMaterial) {
  26274. this.materials.push(newMaterial);
  26275. };
  26276. /**
  26277. * Adds the given morph target to this scene
  26278. * @param newMorphTargetManager The morph target to add
  26279. */
  26280. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26281. this.morphTargetManagers.push(newMorphTargetManager);
  26282. };
  26283. /**
  26284. * Adds the given geometry to this scene
  26285. * @param newGeometry The geometry to add
  26286. */
  26287. Scene.prototype.addGeometry = function (newGeometry) {
  26288. this._geometries.push(newGeometry);
  26289. };
  26290. /**
  26291. * Adds the given lens flare system to this scene
  26292. * @param newLensFlareSystem The lens flare system to add
  26293. */
  26294. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26295. this.lensFlareSystems.push(newLensFlareSystem);
  26296. };
  26297. /**
  26298. * Adds the given effect layer to this scene
  26299. * @param newEffectLayer defines the effect layer to add
  26300. */
  26301. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26302. this.effectLayers.push(newEffectLayer);
  26303. };
  26304. /**
  26305. * Adds the given action manager to this scene
  26306. * @param newActionManager The action manager to add
  26307. */
  26308. Scene.prototype.addActionManager = function (newActionManager) {
  26309. this._actionManagers.push(newActionManager);
  26310. };
  26311. /**
  26312. * Adds the given texture to this scene.
  26313. * @param newTexture The texture to add
  26314. */
  26315. Scene.prototype.addTexture = function (newTexture) {
  26316. this.textures.push(newTexture);
  26317. };
  26318. /**
  26319. * Switch active camera
  26320. * @param newCamera defines the new active camera
  26321. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26322. */
  26323. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26324. if (attachControl === void 0) { attachControl = true; }
  26325. var canvas = this._engine.getRenderingCanvas();
  26326. if (!canvas) {
  26327. return;
  26328. }
  26329. if (this.activeCamera) {
  26330. this.activeCamera.detachControl(canvas);
  26331. }
  26332. this.activeCamera = newCamera;
  26333. if (attachControl) {
  26334. newCamera.attachControl(canvas);
  26335. }
  26336. };
  26337. /**
  26338. * sets the active camera of the scene using its ID
  26339. * @param id defines the camera's ID
  26340. * @return the new active camera or null if none found.
  26341. */
  26342. Scene.prototype.setActiveCameraByID = function (id) {
  26343. var camera = this.getCameraByID(id);
  26344. if (camera) {
  26345. this.activeCamera = camera;
  26346. return camera;
  26347. }
  26348. return null;
  26349. };
  26350. /**
  26351. * sets the active camera of the scene using its name
  26352. * @param name defines the camera's name
  26353. * @returns the new active camera or null if none found.
  26354. */
  26355. Scene.prototype.setActiveCameraByName = function (name) {
  26356. var camera = this.getCameraByName(name);
  26357. if (camera) {
  26358. this.activeCamera = camera;
  26359. return camera;
  26360. }
  26361. return null;
  26362. };
  26363. /**
  26364. * get an animation group using its name
  26365. * @param name defines the material's name
  26366. * @return the animation group or null if none found.
  26367. */
  26368. Scene.prototype.getAnimationGroupByName = function (name) {
  26369. for (var index = 0; index < this.animationGroups.length; index++) {
  26370. if (this.animationGroups[index].name === name) {
  26371. return this.animationGroups[index];
  26372. }
  26373. }
  26374. return null;
  26375. };
  26376. /**
  26377. * get a material using its id
  26378. * @param id defines the material's ID
  26379. * @return the material or null if none found.
  26380. */
  26381. Scene.prototype.getMaterialByID = function (id) {
  26382. for (var index = 0; index < this.materials.length; index++) {
  26383. if (this.materials[index].id === id) {
  26384. return this.materials[index];
  26385. }
  26386. }
  26387. return null;
  26388. };
  26389. /**
  26390. * Gets a material using its name
  26391. * @param name defines the material's name
  26392. * @return the material or null if none found.
  26393. */
  26394. Scene.prototype.getMaterialByName = function (name) {
  26395. for (var index = 0; index < this.materials.length; index++) {
  26396. if (this.materials[index].name === name) {
  26397. return this.materials[index];
  26398. }
  26399. }
  26400. return null;
  26401. };
  26402. /**
  26403. * Gets a lens flare system using its name
  26404. * @param name defines the name to look for
  26405. * @returns the lens flare system or null if not found
  26406. */
  26407. Scene.prototype.getLensFlareSystemByName = function (name) {
  26408. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26409. if (this.lensFlareSystems[index].name === name) {
  26410. return this.lensFlareSystems[index];
  26411. }
  26412. }
  26413. return null;
  26414. };
  26415. /**
  26416. * Gets a lens flare system using its id
  26417. * @param id defines the id to look for
  26418. * @returns the lens flare system or null if not found
  26419. */
  26420. Scene.prototype.getLensFlareSystemByID = function (id) {
  26421. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26422. if (this.lensFlareSystems[index].id === id) {
  26423. return this.lensFlareSystems[index];
  26424. }
  26425. }
  26426. return null;
  26427. };
  26428. /**
  26429. * Gets a camera using its id
  26430. * @param id defines the id to look for
  26431. * @returns the camera or null if not found
  26432. */
  26433. Scene.prototype.getCameraByID = function (id) {
  26434. for (var index = 0; index < this.cameras.length; index++) {
  26435. if (this.cameras[index].id === id) {
  26436. return this.cameras[index];
  26437. }
  26438. }
  26439. return null;
  26440. };
  26441. /**
  26442. * Gets a camera using its unique id
  26443. * @param uniqueId defines the unique id to look for
  26444. * @returns the camera or null if not found
  26445. */
  26446. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26447. for (var index = 0; index < this.cameras.length; index++) {
  26448. if (this.cameras[index].uniqueId === uniqueId) {
  26449. return this.cameras[index];
  26450. }
  26451. }
  26452. return null;
  26453. };
  26454. /**
  26455. * Gets a camera using its name
  26456. * @param name defines the camera's name
  26457. * @return the camera or null if none found.
  26458. */
  26459. Scene.prototype.getCameraByName = function (name) {
  26460. for (var index = 0; index < this.cameras.length; index++) {
  26461. if (this.cameras[index].name === name) {
  26462. return this.cameras[index];
  26463. }
  26464. }
  26465. return null;
  26466. };
  26467. /**
  26468. * Gets a bone using its id
  26469. * @param id defines the bone's id
  26470. * @return the bone or null if not found
  26471. */
  26472. Scene.prototype.getBoneByID = function (id) {
  26473. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26474. var skeleton = this.skeletons[skeletonIndex];
  26475. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26476. if (skeleton.bones[boneIndex].id === id) {
  26477. return skeleton.bones[boneIndex];
  26478. }
  26479. }
  26480. }
  26481. return null;
  26482. };
  26483. /**
  26484. * Gets a bone using its id
  26485. * @param name defines the bone's name
  26486. * @return the bone or null if not found
  26487. */
  26488. Scene.prototype.getBoneByName = function (name) {
  26489. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26490. var skeleton = this.skeletons[skeletonIndex];
  26491. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26492. if (skeleton.bones[boneIndex].name === name) {
  26493. return skeleton.bones[boneIndex];
  26494. }
  26495. }
  26496. }
  26497. return null;
  26498. };
  26499. /**
  26500. * Gets a light node using its name
  26501. * @param name defines the the light's name
  26502. * @return the light or null if none found.
  26503. */
  26504. Scene.prototype.getLightByName = function (name) {
  26505. for (var index = 0; index < this.lights.length; index++) {
  26506. if (this.lights[index].name === name) {
  26507. return this.lights[index];
  26508. }
  26509. }
  26510. return null;
  26511. };
  26512. /**
  26513. * Gets a light node using its id
  26514. * @param id defines the light's id
  26515. * @return the light or null if none found.
  26516. */
  26517. Scene.prototype.getLightByID = function (id) {
  26518. for (var index = 0; index < this.lights.length; index++) {
  26519. if (this.lights[index].id === id) {
  26520. return this.lights[index];
  26521. }
  26522. }
  26523. return null;
  26524. };
  26525. /**
  26526. * Gets a light node using its scene-generated unique ID
  26527. * @param uniqueId defines the light's unique id
  26528. * @return the light or null if none found.
  26529. */
  26530. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26531. for (var index = 0; index < this.lights.length; index++) {
  26532. if (this.lights[index].uniqueId === uniqueId) {
  26533. return this.lights[index];
  26534. }
  26535. }
  26536. return null;
  26537. };
  26538. /**
  26539. * Gets a particle system by id
  26540. * @param id defines the particle system id
  26541. * @return the corresponding system or null if none found
  26542. */
  26543. Scene.prototype.getParticleSystemByID = function (id) {
  26544. for (var index = 0; index < this.particleSystems.length; index++) {
  26545. if (this.particleSystems[index].id === id) {
  26546. return this.particleSystems[index];
  26547. }
  26548. }
  26549. return null;
  26550. };
  26551. /**
  26552. * Gets a geometry using its ID
  26553. * @param id defines the geometry's id
  26554. * @return the geometry or null if none found.
  26555. */
  26556. Scene.prototype.getGeometryByID = function (id) {
  26557. for (var index = 0; index < this._geometries.length; index++) {
  26558. if (this._geometries[index].id === id) {
  26559. return this._geometries[index];
  26560. }
  26561. }
  26562. return null;
  26563. };
  26564. /**
  26565. * Add a new geometry to this scene
  26566. * @param geometry defines the geometry to be added to the scene.
  26567. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26568. * @return a boolean defining if the geometry was added or not
  26569. */
  26570. Scene.prototype.pushGeometry = function (geometry, force) {
  26571. if (!force && this.getGeometryByID(geometry.id)) {
  26572. return false;
  26573. }
  26574. this._geometries.push(geometry);
  26575. //notify the collision coordinator
  26576. if (this.collisionCoordinator) {
  26577. this.collisionCoordinator.onGeometryAdded(geometry);
  26578. }
  26579. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26580. return true;
  26581. };
  26582. /**
  26583. * Removes an existing geometry
  26584. * @param geometry defines the geometry to be removed from the scene
  26585. * @return a boolean defining if the geometry was removed or not
  26586. */
  26587. Scene.prototype.removeGeometry = function (geometry) {
  26588. var index = this._geometries.indexOf(geometry);
  26589. if (index > -1) {
  26590. this._geometries.splice(index, 1);
  26591. //notify the collision coordinator
  26592. if (this.collisionCoordinator) {
  26593. this.collisionCoordinator.onGeometryDeleted(geometry);
  26594. }
  26595. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26596. return true;
  26597. }
  26598. return false;
  26599. };
  26600. /**
  26601. * Gets the list of geometries attached to the scene
  26602. * @returns an array of Geometry
  26603. */
  26604. Scene.prototype.getGeometries = function () {
  26605. return this._geometries;
  26606. };
  26607. /**
  26608. * Gets the first added mesh found of a given ID
  26609. * @param id defines the id to search for
  26610. * @return the mesh found or null if not found at all
  26611. */
  26612. Scene.prototype.getMeshByID = function (id) {
  26613. for (var index = 0; index < this.meshes.length; index++) {
  26614. if (this.meshes[index].id === id) {
  26615. return this.meshes[index];
  26616. }
  26617. }
  26618. return null;
  26619. };
  26620. /**
  26621. * Gets a list of meshes using their id
  26622. * @param id defines the id to search for
  26623. * @returns a list of meshes
  26624. */
  26625. Scene.prototype.getMeshesByID = function (id) {
  26626. return this.meshes.filter(function (m) {
  26627. return m.id === id;
  26628. });
  26629. };
  26630. /**
  26631. * Gets the first added transform node found of a given ID
  26632. * @param id defines the id to search for
  26633. * @return the found transform node or null if not found at all.
  26634. */
  26635. Scene.prototype.getTransformNodeByID = function (id) {
  26636. for (var index = 0; index < this.transformNodes.length; index++) {
  26637. if (this.transformNodes[index].id === id) {
  26638. return this.transformNodes[index];
  26639. }
  26640. }
  26641. return null;
  26642. };
  26643. /**
  26644. * Gets a list of transform nodes using their id
  26645. * @param id defines the id to search for
  26646. * @returns a list of transform nodes
  26647. */
  26648. Scene.prototype.getTransformNodesByID = function (id) {
  26649. return this.transformNodes.filter(function (m) {
  26650. return m.id === id;
  26651. });
  26652. };
  26653. /**
  26654. * Gets a mesh with its auto-generated unique id
  26655. * @param uniqueId defines the unique id to search for
  26656. * @return the found mesh or null if not found at all.
  26657. */
  26658. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26659. for (var index = 0; index < this.meshes.length; index++) {
  26660. if (this.meshes[index].uniqueId === uniqueId) {
  26661. return this.meshes[index];
  26662. }
  26663. }
  26664. return null;
  26665. };
  26666. /**
  26667. * Gets a the last added mesh using a given id
  26668. * @param id defines the id to search for
  26669. * @return the found mesh or null if not found at all.
  26670. */
  26671. Scene.prototype.getLastMeshByID = function (id) {
  26672. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26673. if (this.meshes[index].id === id) {
  26674. return this.meshes[index];
  26675. }
  26676. }
  26677. return null;
  26678. };
  26679. /**
  26680. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26681. * @param id defines the id to search for
  26682. * @return the found node or null if not found at all
  26683. */
  26684. Scene.prototype.getLastEntryByID = function (id) {
  26685. var index;
  26686. for (index = this.meshes.length - 1; index >= 0; index--) {
  26687. if (this.meshes[index].id === id) {
  26688. return this.meshes[index];
  26689. }
  26690. }
  26691. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26692. if (this.transformNodes[index].id === id) {
  26693. return this.transformNodes[index];
  26694. }
  26695. }
  26696. for (index = this.cameras.length - 1; index >= 0; index--) {
  26697. if (this.cameras[index].id === id) {
  26698. return this.cameras[index];
  26699. }
  26700. }
  26701. for (index = this.lights.length - 1; index >= 0; index--) {
  26702. if (this.lights[index].id === id) {
  26703. return this.lights[index];
  26704. }
  26705. }
  26706. return null;
  26707. };
  26708. /**
  26709. * Gets a node (Mesh, Camera, Light) using a given id
  26710. * @param id defines the id to search for
  26711. * @return the found node or null if not found at all
  26712. */
  26713. Scene.prototype.getNodeByID = function (id) {
  26714. var mesh = this.getMeshByID(id);
  26715. if (mesh) {
  26716. return mesh;
  26717. }
  26718. var light = this.getLightByID(id);
  26719. if (light) {
  26720. return light;
  26721. }
  26722. var camera = this.getCameraByID(id);
  26723. if (camera) {
  26724. return camera;
  26725. }
  26726. var bone = this.getBoneByID(id);
  26727. return bone;
  26728. };
  26729. /**
  26730. * Gets a node (Mesh, Camera, Light) using a given name
  26731. * @param name defines the name to search for
  26732. * @return the found node or null if not found at all.
  26733. */
  26734. Scene.prototype.getNodeByName = function (name) {
  26735. var mesh = this.getMeshByName(name);
  26736. if (mesh) {
  26737. return mesh;
  26738. }
  26739. var light = this.getLightByName(name);
  26740. if (light) {
  26741. return light;
  26742. }
  26743. var camera = this.getCameraByName(name);
  26744. if (camera) {
  26745. return camera;
  26746. }
  26747. var bone = this.getBoneByName(name);
  26748. return bone;
  26749. };
  26750. /**
  26751. * Gets a mesh using a given name
  26752. * @param name defines the name to search for
  26753. * @return the found mesh or null if not found at all.
  26754. */
  26755. Scene.prototype.getMeshByName = function (name) {
  26756. for (var index = 0; index < this.meshes.length; index++) {
  26757. if (this.meshes[index].name === name) {
  26758. return this.meshes[index];
  26759. }
  26760. }
  26761. return null;
  26762. };
  26763. /**
  26764. * Gets a transform node using a given name
  26765. * @param name defines the name to search for
  26766. * @return the found transform node or null if not found at all.
  26767. */
  26768. Scene.prototype.getTransformNodeByName = function (name) {
  26769. for (var index = 0; index < this.transformNodes.length; index++) {
  26770. if (this.transformNodes[index].name === name) {
  26771. return this.transformNodes[index];
  26772. }
  26773. }
  26774. return null;
  26775. };
  26776. /**
  26777. * Gets a sound using a given name
  26778. * @param name defines the name to search for
  26779. * @return the found sound or null if not found at all.
  26780. */
  26781. Scene.prototype.getSoundByName = function (name) {
  26782. var index;
  26783. if (BABYLON.AudioEngine) {
  26784. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26785. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26786. return this.mainSoundTrack.soundCollection[index];
  26787. }
  26788. }
  26789. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26790. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26791. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26792. return this.soundTracks[sdIndex].soundCollection[index];
  26793. }
  26794. }
  26795. }
  26796. }
  26797. return null;
  26798. };
  26799. /**
  26800. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26801. * @param id defines the id to search for
  26802. * @return the found skeleton or null if not found at all.
  26803. */
  26804. Scene.prototype.getLastSkeletonByID = function (id) {
  26805. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26806. if (this.skeletons[index].id === id) {
  26807. return this.skeletons[index];
  26808. }
  26809. }
  26810. return null;
  26811. };
  26812. /**
  26813. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26814. * @param id defines the id to search for
  26815. * @return the found skeleton or null if not found at all.
  26816. */
  26817. Scene.prototype.getSkeletonById = function (id) {
  26818. for (var index = 0; index < this.skeletons.length; index++) {
  26819. if (this.skeletons[index].id === id) {
  26820. return this.skeletons[index];
  26821. }
  26822. }
  26823. return null;
  26824. };
  26825. /**
  26826. * Gets a skeleton using a given name
  26827. * @param name defines the name to search for
  26828. * @return the found skeleton or null if not found at all.
  26829. */
  26830. Scene.prototype.getSkeletonByName = function (name) {
  26831. for (var index = 0; index < this.skeletons.length; index++) {
  26832. if (this.skeletons[index].name === name) {
  26833. return this.skeletons[index];
  26834. }
  26835. }
  26836. return null;
  26837. };
  26838. /**
  26839. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26840. * @param id defines the id to search for
  26841. * @return the found morph target manager or null if not found at all.
  26842. */
  26843. Scene.prototype.getMorphTargetManagerById = function (id) {
  26844. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26845. if (this.morphTargetManagers[index].uniqueId === id) {
  26846. return this.morphTargetManagers[index];
  26847. }
  26848. }
  26849. return null;
  26850. };
  26851. /**
  26852. * Gets a boolean indicating if the given mesh is active
  26853. * @param mesh defines the mesh to look for
  26854. * @returns true if the mesh is in the active list
  26855. */
  26856. Scene.prototype.isActiveMesh = function (mesh) {
  26857. return (this._activeMeshes.indexOf(mesh) !== -1);
  26858. };
  26859. /**
  26860. * Return a the first highlight layer of the scene with a given name.
  26861. * @param name The name of the highlight layer to look for.
  26862. * @return The highlight layer if found otherwise null.
  26863. */
  26864. Scene.prototype.getHighlightLayerByName = function (name) {
  26865. for (var index = 0; index < this.effectLayers.length; index++) {
  26866. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26867. return this.effectLayers[index];
  26868. }
  26869. }
  26870. return null;
  26871. };
  26872. /**
  26873. * Return a the first highlight layer of the scene with a given name.
  26874. * @param name The name of the highlight layer to look for.
  26875. * @return The highlight layer if found otherwise null.
  26876. */
  26877. Scene.prototype.getGlowLayerByName = function (name) {
  26878. for (var index = 0; index < this.effectLayers.length; index++) {
  26879. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26880. return this.effectLayers[index];
  26881. }
  26882. }
  26883. return null;
  26884. };
  26885. Object.defineProperty(Scene.prototype, "uid", {
  26886. /**
  26887. * Return a unique id as a string which can serve as an identifier for the scene
  26888. */
  26889. get: function () {
  26890. if (!this._uid) {
  26891. this._uid = BABYLON.Tools.RandomId();
  26892. }
  26893. return this._uid;
  26894. },
  26895. enumerable: true,
  26896. configurable: true
  26897. });
  26898. /**
  26899. * Add an externaly attached data from its key.
  26900. * This method call will fail and return false, if such key already exists.
  26901. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26902. * @param key the unique key that identifies the data
  26903. * @param data the data object to associate to the key for this Engine instance
  26904. * @return true if no such key were already present and the data was added successfully, false otherwise
  26905. */
  26906. Scene.prototype.addExternalData = function (key, data) {
  26907. if (!this._externalData) {
  26908. this._externalData = new BABYLON.StringDictionary();
  26909. }
  26910. return this._externalData.add(key, data);
  26911. };
  26912. /**
  26913. * Get an externaly attached data from its key
  26914. * @param key the unique key that identifies the data
  26915. * @return the associated data, if present (can be null), or undefined if not present
  26916. */
  26917. Scene.prototype.getExternalData = function (key) {
  26918. if (!this._externalData) {
  26919. return null;
  26920. }
  26921. return this._externalData.get(key);
  26922. };
  26923. /**
  26924. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26925. * @param key the unique key that identifies the data
  26926. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26927. * @return the associated data, can be null if the factory returned null.
  26928. */
  26929. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26930. if (!this._externalData) {
  26931. this._externalData = new BABYLON.StringDictionary();
  26932. }
  26933. return this._externalData.getOrAddWithFactory(key, factory);
  26934. };
  26935. /**
  26936. * Remove an externaly attached data from the Engine instance
  26937. * @param key the unique key that identifies the data
  26938. * @return true if the data was successfully removed, false if it doesn't exist
  26939. */
  26940. Scene.prototype.removeExternalData = function (key) {
  26941. return this._externalData.remove(key);
  26942. };
  26943. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26944. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26945. if (mesh.showSubMeshesBoundingBox) {
  26946. var boundingInfo = subMesh.getBoundingInfo();
  26947. if (boundingInfo !== null && boundingInfo !== undefined) {
  26948. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26949. }
  26950. }
  26951. var material = subMesh.getMaterial();
  26952. if (material !== null && material !== undefined) {
  26953. // Render targets
  26954. if (material.getRenderTargetTextures !== undefined) {
  26955. if (this._processedMaterials.indexOf(material) === -1) {
  26956. this._processedMaterials.push(material);
  26957. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26958. }
  26959. }
  26960. // Dispatch
  26961. this._activeIndices.addCount(subMesh.indexCount, false);
  26962. this._renderingManager.dispatch(subMesh, mesh, material);
  26963. }
  26964. }
  26965. };
  26966. /**
  26967. * Clear the processed materials smart array preventing retention point in material dispose.
  26968. */
  26969. Scene.prototype.freeProcessedMaterials = function () {
  26970. this._processedMaterials.dispose();
  26971. };
  26972. /**
  26973. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26974. */
  26975. Scene.prototype.freeActiveMeshes = function () {
  26976. this._activeMeshes.dispose();
  26977. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26978. this.activeCamera._activeMeshes.dispose();
  26979. }
  26980. if (this.activeCameras) {
  26981. for (var i = 0; i < this.activeCameras.length; i++) {
  26982. var activeCamera = this.activeCameras[i];
  26983. if (activeCamera && activeCamera._activeMeshes) {
  26984. activeCamera._activeMeshes.dispose();
  26985. }
  26986. }
  26987. }
  26988. };
  26989. /**
  26990. * Clear the info related to rendering groups preventing retention points during dispose.
  26991. */
  26992. Scene.prototype.freeRenderingGroups = function () {
  26993. if (this._renderingManager) {
  26994. this._renderingManager.freeRenderingGroups();
  26995. }
  26996. if (this.textures) {
  26997. for (var i = 0; i < this.textures.length; i++) {
  26998. var texture = this.textures[i];
  26999. if (texture && texture.renderList) {
  27000. texture.freeRenderingGroups();
  27001. }
  27002. }
  27003. }
  27004. };
  27005. /** @hidden */
  27006. Scene.prototype._isInIntermediateRendering = function () {
  27007. return this._intermediateRendering;
  27008. };
  27009. /**
  27010. * Defines the current active mesh candidate provider
  27011. * @param provider defines the provider to use
  27012. */
  27013. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27014. this._activeMeshCandidateProvider = provider;
  27015. };
  27016. /**
  27017. * Gets the current active mesh candidate provider
  27018. * @returns the current active mesh candidate provider
  27019. */
  27020. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27021. return this._activeMeshCandidateProvider;
  27022. };
  27023. /**
  27024. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27025. * @returns the current scene
  27026. */
  27027. Scene.prototype.freezeActiveMeshes = function () {
  27028. if (!this.activeCamera) {
  27029. return this;
  27030. }
  27031. if (!this._frustumPlanes) {
  27032. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27033. }
  27034. this._evaluateActiveMeshes();
  27035. this._activeMeshesFrozen = true;
  27036. return this;
  27037. };
  27038. /**
  27039. * Use this function to restart evaluating active meshes on every frame
  27040. * @returns the current scene
  27041. */
  27042. Scene.prototype.unfreezeActiveMeshes = function () {
  27043. this._activeMeshesFrozen = false;
  27044. return this;
  27045. };
  27046. Scene.prototype._evaluateActiveMeshes = function () {
  27047. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27048. return;
  27049. }
  27050. if (!this.activeCamera) {
  27051. return;
  27052. }
  27053. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27054. this.activeCamera._activeMeshes.reset();
  27055. this._activeMeshes.reset();
  27056. this._renderingManager.reset();
  27057. this._processedMaterials.reset();
  27058. this._activeParticleSystems.reset();
  27059. this._activeSkeletons.reset();
  27060. this._softwareSkinnedMeshes.reset();
  27061. if (this._boundingBoxRenderer) {
  27062. this._boundingBoxRenderer.reset();
  27063. }
  27064. // Meshes
  27065. var meshes;
  27066. var len;
  27067. var checkIsEnabled = true;
  27068. // Determine mesh candidates
  27069. if (this._activeMeshCandidateProvider !== undefined) {
  27070. // Use _activeMeshCandidateProvider
  27071. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27072. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27073. if (meshes !== undefined) {
  27074. len = meshes.length;
  27075. }
  27076. else {
  27077. len = 0;
  27078. }
  27079. }
  27080. else if (this._selectionOctree !== undefined) {
  27081. // Octree
  27082. var selection = this._selectionOctree.select(this._frustumPlanes);
  27083. meshes = selection.data;
  27084. len = selection.length;
  27085. }
  27086. else {
  27087. // Full scene traversal
  27088. len = this.meshes.length;
  27089. meshes = this.meshes;
  27090. }
  27091. // Check each mesh
  27092. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27093. mesh = meshes[meshIndex];
  27094. if (mesh.isBlocked) {
  27095. continue;
  27096. }
  27097. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27098. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27099. continue;
  27100. }
  27101. mesh.computeWorldMatrix();
  27102. // Intersections
  27103. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27104. this._meshesForIntersections.pushNoDuplicate(mesh);
  27105. }
  27106. // Switch to current LOD
  27107. meshLOD = mesh.getLOD(this.activeCamera);
  27108. if (meshLOD === undefined || meshLOD === null) {
  27109. continue;
  27110. }
  27111. mesh._preActivate();
  27112. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27113. this._activeMeshes.push(mesh);
  27114. this.activeCamera._activeMeshes.push(mesh);
  27115. mesh._activate(this._renderId);
  27116. if (meshLOD !== mesh) {
  27117. meshLOD._activate(this._renderId);
  27118. }
  27119. this._activeMesh(mesh, meshLOD);
  27120. }
  27121. }
  27122. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27123. // Particle systems
  27124. if (this.particlesEnabled) {
  27125. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27126. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27127. var particleSystem = this.particleSystems[particleIndex];
  27128. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27129. continue;
  27130. }
  27131. var emitter = particleSystem.emitter;
  27132. if (!emitter.position || emitter.isEnabled()) {
  27133. this._activeParticleSystems.push(particleSystem);
  27134. particleSystem.animate();
  27135. this._renderingManager.dispatchParticles(particleSystem);
  27136. }
  27137. }
  27138. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27139. }
  27140. };
  27141. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27142. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27143. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27144. mesh.skeleton.prepare();
  27145. }
  27146. if (!mesh.computeBonesUsingShaders) {
  27147. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27148. }
  27149. }
  27150. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27151. var boundingInfo = sourceMesh.getBoundingInfo();
  27152. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27153. }
  27154. if (mesh !== undefined && mesh !== null
  27155. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27156. // Submeshes Octrees
  27157. var len;
  27158. var subMeshes;
  27159. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27160. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27161. len = intersections.length;
  27162. subMeshes = intersections.data;
  27163. }
  27164. else {
  27165. subMeshes = mesh.subMeshes;
  27166. len = subMeshes.length;
  27167. }
  27168. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27169. subMesh = subMeshes[subIndex];
  27170. this._evaluateSubMesh(subMesh, mesh);
  27171. }
  27172. }
  27173. };
  27174. /**
  27175. * Update the transform matrix to update from the current active camera
  27176. * @param force defines a boolean used to force the update even if cache is up to date
  27177. */
  27178. Scene.prototype.updateTransformMatrix = function (force) {
  27179. if (!this.activeCamera) {
  27180. return;
  27181. }
  27182. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27183. };
  27184. /**
  27185. * 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)
  27186. * @param alternateCamera defines the camera to use
  27187. */
  27188. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27189. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27190. };
  27191. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27192. if (camera && camera._skipRendering) {
  27193. return;
  27194. }
  27195. var engine = this._engine;
  27196. this.activeCamera = camera;
  27197. if (!this.activeCamera)
  27198. throw new Error("Active camera not set");
  27199. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27200. // Viewport
  27201. engine.setViewport(this.activeCamera.viewport);
  27202. // Camera
  27203. this.resetCachedMaterial();
  27204. this._renderId++;
  27205. this.updateTransformMatrix();
  27206. if (camera._alternateCamera) {
  27207. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27208. this._alternateRendering = true;
  27209. }
  27210. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27211. // Meshes
  27212. this._evaluateActiveMeshes();
  27213. // Software skinning
  27214. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27215. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27216. mesh.applySkeleton(mesh.skeleton);
  27217. }
  27218. // Render targets
  27219. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27220. var needsRestoreFrameBuffer = false;
  27221. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27222. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27223. }
  27224. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27225. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27226. }
  27227. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27228. this._intermediateRendering = true;
  27229. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27230. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27231. var renderTarget = this._renderTargets.data[renderIndex];
  27232. if (renderTarget._shouldRender()) {
  27233. this._renderId++;
  27234. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27235. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27236. }
  27237. }
  27238. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27239. this._intermediateRendering = false;
  27240. this._renderId++;
  27241. needsRestoreFrameBuffer = true; // Restore back buffer
  27242. }
  27243. // Render EffecttLayer Texture
  27244. var stencilState = this._engine.getStencilBuffer();
  27245. var renderEffects = false;
  27246. var needStencil = false;
  27247. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27248. this._intermediateRendering = true;
  27249. for (var i = 0; i < this.effectLayers.length; i++) {
  27250. var effectLayer = this.effectLayers[i];
  27251. if (effectLayer.shouldRender() &&
  27252. (!effectLayer.camera ||
  27253. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27254. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27255. renderEffects = true;
  27256. needStencil = needStencil || effectLayer.needStencil();
  27257. var renderTarget = effectLayer._mainTexture;
  27258. if (renderTarget._shouldRender()) {
  27259. this._renderId++;
  27260. renderTarget.render(false, false);
  27261. needsRestoreFrameBuffer = true;
  27262. }
  27263. }
  27264. }
  27265. this._intermediateRendering = false;
  27266. this._renderId++;
  27267. }
  27268. if (needsRestoreFrameBuffer) {
  27269. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27270. }
  27271. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27272. // Prepare Frame
  27273. this.postProcessManager._prepareFrame();
  27274. // Backgrounds
  27275. var layerIndex;
  27276. var layer;
  27277. if (this.layers.length) {
  27278. engine.setDepthBuffer(false);
  27279. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27280. layer = this.layers[layerIndex];
  27281. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27282. layer.render();
  27283. }
  27284. }
  27285. engine.setDepthBuffer(true);
  27286. }
  27287. // Activate effect Layer stencil
  27288. if (needStencil) {
  27289. this._engine.setStencilBuffer(true);
  27290. }
  27291. // Render
  27292. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27293. this._renderingManager.render(null, null, true, true);
  27294. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27295. // Restore effect Layer stencil
  27296. if (needStencil) {
  27297. this._engine.setStencilBuffer(stencilState);
  27298. }
  27299. // Bounding boxes
  27300. if (this._boundingBoxRenderer) {
  27301. this._boundingBoxRenderer.render();
  27302. }
  27303. // Lens flares
  27304. if (this.lensFlaresEnabled) {
  27305. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27306. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27307. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27308. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27309. lensFlareSystem.render();
  27310. }
  27311. }
  27312. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27313. }
  27314. // Effect Layer
  27315. if (renderEffects) {
  27316. engine.setDepthBuffer(false);
  27317. for (var i = 0; i < this.effectLayers.length; i++) {
  27318. if (this.effectLayers[i].shouldRender()) {
  27319. this.effectLayers[i].render();
  27320. }
  27321. }
  27322. engine.setDepthBuffer(true);
  27323. }
  27324. // Foregrounds
  27325. if (this.layers.length) {
  27326. engine.setDepthBuffer(false);
  27327. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27328. layer = this.layers[layerIndex];
  27329. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27330. layer.render();
  27331. }
  27332. }
  27333. engine.setDepthBuffer(true);
  27334. }
  27335. // Finalize frame
  27336. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27337. // Reset some special arrays
  27338. this._renderTargets.reset();
  27339. this._alternateRendering = false;
  27340. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27341. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27342. };
  27343. Scene.prototype._processSubCameras = function (camera) {
  27344. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27345. this._renderForCamera(camera);
  27346. return;
  27347. }
  27348. // rig cameras
  27349. for (var index = 0; index < camera._rigCameras.length; index++) {
  27350. this._renderForCamera(camera._rigCameras[index], camera);
  27351. }
  27352. this.activeCamera = camera;
  27353. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27354. };
  27355. Scene.prototype._checkIntersections = function () {
  27356. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27357. var sourceMesh = this._meshesForIntersections.data[index];
  27358. if (!sourceMesh.actionManager) {
  27359. continue;
  27360. }
  27361. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27362. var action = sourceMesh.actionManager.actions[actionIndex];
  27363. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27364. var parameters = action.getTriggerParameter();
  27365. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27366. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27367. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27368. if (areIntersecting && currentIntersectionInProgress === -1) {
  27369. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27370. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27371. sourceMesh._intersectionsInProgress.push(otherMesh);
  27372. }
  27373. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27374. sourceMesh._intersectionsInProgress.push(otherMesh);
  27375. }
  27376. }
  27377. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27378. //They intersected, and now they don't.
  27379. //is this trigger an exit trigger? execute an event.
  27380. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27381. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27382. }
  27383. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27384. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27385. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27386. return otherMesh === parameterMesh;
  27387. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27388. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27389. }
  27390. }
  27391. }
  27392. }
  27393. }
  27394. };
  27395. /**
  27396. * Render the scene
  27397. */
  27398. Scene.prototype.render = function () {
  27399. if (this.isDisposed) {
  27400. return;
  27401. }
  27402. this._activeParticles.fetchNewFrame();
  27403. this._totalVertices.fetchNewFrame();
  27404. this._activeIndices.fetchNewFrame();
  27405. this._activeBones.fetchNewFrame();
  27406. this._meshesForIntersections.reset();
  27407. this.resetCachedMaterial();
  27408. this.onBeforeAnimationsObservable.notifyObservers(this);
  27409. // Actions
  27410. if (this.actionManager) {
  27411. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27412. }
  27413. //Simplification Queue
  27414. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27415. this.simplificationQueue.executeNext();
  27416. }
  27417. if (this._engine.isDeterministicLockStep()) {
  27418. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27419. var defaultFPS = (60.0 / 1000.0);
  27420. var defaultFrameTime = 1000 / 60; // frame time in MS
  27421. if (this._physicsEngine) {
  27422. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27423. }
  27424. var stepsTaken = 0;
  27425. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27426. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27427. internalSteps = Math.min(internalSteps, maxSubSteps);
  27428. do {
  27429. this.onBeforeStepObservable.notifyObservers(this);
  27430. // Animations
  27431. this._animationRatio = defaultFrameTime * defaultFPS;
  27432. this._animate();
  27433. this.onAfterAnimationsObservable.notifyObservers(this);
  27434. // Physics
  27435. if (this._physicsEngine) {
  27436. this.onBeforePhysicsObservable.notifyObservers(this);
  27437. this._physicsEngine._step(defaultFrameTime / 1000);
  27438. this.onAfterPhysicsObservable.notifyObservers(this);
  27439. }
  27440. this.onAfterStepObservable.notifyObservers(this);
  27441. this._currentStepId++;
  27442. stepsTaken++;
  27443. deltaTime -= defaultFrameTime;
  27444. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27445. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27446. }
  27447. else {
  27448. // Animations
  27449. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27450. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27451. this._animate();
  27452. this.onAfterAnimationsObservable.notifyObservers(this);
  27453. // Physics
  27454. if (this._physicsEngine) {
  27455. this.onBeforePhysicsObservable.notifyObservers(this);
  27456. this._physicsEngine._step(deltaTime / 1000.0);
  27457. this.onAfterPhysicsObservable.notifyObservers(this);
  27458. }
  27459. }
  27460. // update gamepad manager
  27461. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27462. this._gamepadManager._checkGamepadsStatus();
  27463. }
  27464. // Update Cameras
  27465. if (this.activeCameras.length > 0) {
  27466. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27467. var camera = this.activeCameras[cameraIndex];
  27468. camera.update();
  27469. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27470. // rig cameras
  27471. for (var index = 0; index < camera._rigCameras.length; index++) {
  27472. camera._rigCameras[index].update();
  27473. }
  27474. }
  27475. }
  27476. }
  27477. else if (this.activeCamera) {
  27478. this.activeCamera.update();
  27479. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27480. // rig cameras
  27481. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27482. this.activeCamera._rigCameras[index].update();
  27483. }
  27484. }
  27485. }
  27486. // Before render
  27487. this.onBeforeRenderObservable.notifyObservers(this);
  27488. // Customs render targets
  27489. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27490. var engine = this.getEngine();
  27491. var currentActiveCamera = this.activeCamera;
  27492. if (this.renderTargetsEnabled) {
  27493. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27494. this._intermediateRendering = true;
  27495. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27496. var renderTarget = this.customRenderTargets[customIndex];
  27497. if (renderTarget._shouldRender()) {
  27498. this._renderId++;
  27499. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27500. if (!this.activeCamera)
  27501. throw new Error("Active camera not set");
  27502. // Viewport
  27503. engine.setViewport(this.activeCamera.viewport);
  27504. // Camera
  27505. this.updateTransformMatrix();
  27506. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27507. }
  27508. }
  27509. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27510. this._intermediateRendering = false;
  27511. this._renderId++;
  27512. }
  27513. // Restore back buffer
  27514. if (this.customRenderTargets.length > 0) {
  27515. engine.restoreDefaultFramebuffer();
  27516. }
  27517. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27518. this.activeCamera = currentActiveCamera;
  27519. // Procedural textures
  27520. if (this.proceduralTexturesEnabled) {
  27521. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27522. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27523. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27524. if (proceduralTexture._shouldRender()) {
  27525. proceduralTexture.render();
  27526. }
  27527. }
  27528. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27529. }
  27530. // Clear
  27531. if (this.autoClearDepthAndStencil || this.autoClear) {
  27532. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27533. }
  27534. // Shadows
  27535. if (this.shadowsEnabled) {
  27536. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27537. var light = this.lights[lightIndex];
  27538. var shadowGenerator = light.getShadowGenerator();
  27539. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27540. var shadowMap = (shadowGenerator.getShadowMap());
  27541. if (this.textures.indexOf(shadowMap) !== -1) {
  27542. this._renderTargets.push(shadowMap);
  27543. }
  27544. }
  27545. }
  27546. }
  27547. // Depth renderer
  27548. for (var key in this._depthRenderer) {
  27549. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27550. }
  27551. // Geometry renderer
  27552. if (this._geometryBufferRenderer) {
  27553. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27554. }
  27555. // RenderPipeline
  27556. if (this._postProcessRenderPipelineManager) {
  27557. this._postProcessRenderPipelineManager.update();
  27558. }
  27559. // Multi-cameras?
  27560. if (this.activeCameras.length > 0) {
  27561. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27562. if (cameraIndex > 0) {
  27563. this._engine.clear(null, false, true, true);
  27564. }
  27565. this._processSubCameras(this.activeCameras[cameraIndex]);
  27566. }
  27567. }
  27568. else {
  27569. if (!this.activeCamera) {
  27570. throw new Error("No camera defined");
  27571. }
  27572. this._processSubCameras(this.activeCamera);
  27573. }
  27574. // Intersection checks
  27575. this._checkIntersections();
  27576. // Update the audio listener attached to the camera
  27577. if (BABYLON.AudioEngine) {
  27578. this._updateAudioParameters();
  27579. }
  27580. // After render
  27581. if (this.afterRender) {
  27582. this.afterRender();
  27583. }
  27584. this.onAfterRenderObservable.notifyObservers(this);
  27585. // Cleaning
  27586. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27587. var data = this._toBeDisposed.data[index];
  27588. if (data) {
  27589. data.dispose();
  27590. }
  27591. this._toBeDisposed[index] = null;
  27592. }
  27593. this._toBeDisposed.reset();
  27594. if (this.dumpNextRenderTargets) {
  27595. this.dumpNextRenderTargets = false;
  27596. }
  27597. this._activeBones.addCount(0, true);
  27598. this._activeIndices.addCount(0, true);
  27599. this._activeParticles.addCount(0, true);
  27600. };
  27601. Scene.prototype._updateAudioParameters = function () {
  27602. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27603. return;
  27604. }
  27605. var listeningCamera;
  27606. var audioEngine = BABYLON.Engine.audioEngine;
  27607. if (this.activeCameras.length > 0) {
  27608. listeningCamera = this.activeCameras[0];
  27609. }
  27610. else {
  27611. listeningCamera = this.activeCamera;
  27612. }
  27613. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27614. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27615. // for VR cameras
  27616. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27617. listeningCamera = listeningCamera.rigCameras[0];
  27618. }
  27619. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27620. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27621. cameraDirection.normalize();
  27622. // To avoid some errors on GearVR
  27623. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27624. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27625. }
  27626. var i;
  27627. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27628. var sound = this.mainSoundTrack.soundCollection[i];
  27629. if (sound.useCustomAttenuation) {
  27630. sound.updateDistanceFromListener();
  27631. }
  27632. }
  27633. for (i = 0; i < this.soundTracks.length; i++) {
  27634. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27635. sound = this.soundTracks[i].soundCollection[j];
  27636. if (sound.useCustomAttenuation) {
  27637. sound.updateDistanceFromListener();
  27638. }
  27639. }
  27640. }
  27641. }
  27642. };
  27643. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27644. // Audio
  27645. /**
  27646. * Gets or sets if audio support is enabled
  27647. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27648. */
  27649. get: function () {
  27650. return this._audioEnabled;
  27651. },
  27652. set: function (value) {
  27653. this._audioEnabled = value;
  27654. if (BABYLON.AudioEngine) {
  27655. if (this._audioEnabled) {
  27656. this._enableAudio();
  27657. }
  27658. else {
  27659. this._disableAudio();
  27660. }
  27661. }
  27662. },
  27663. enumerable: true,
  27664. configurable: true
  27665. });
  27666. Scene.prototype._disableAudio = function () {
  27667. var i;
  27668. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27669. this.mainSoundTrack.soundCollection[i].pause();
  27670. }
  27671. for (i = 0; i < this.soundTracks.length; i++) {
  27672. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27673. this.soundTracks[i].soundCollection[j].pause();
  27674. }
  27675. }
  27676. };
  27677. Scene.prototype._enableAudio = function () {
  27678. var i;
  27679. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27680. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27681. this.mainSoundTrack.soundCollection[i].play();
  27682. }
  27683. }
  27684. for (i = 0; i < this.soundTracks.length; i++) {
  27685. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27686. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27687. this.soundTracks[i].soundCollection[j].play();
  27688. }
  27689. }
  27690. }
  27691. };
  27692. Object.defineProperty(Scene.prototype, "headphone", {
  27693. /**
  27694. * Gets or sets if audio will be output to headphones
  27695. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27696. */
  27697. get: function () {
  27698. return this._headphone;
  27699. },
  27700. set: function (value) {
  27701. this._headphone = value;
  27702. if (BABYLON.AudioEngine) {
  27703. if (this._headphone) {
  27704. this._switchAudioModeForHeadphones();
  27705. }
  27706. else {
  27707. this._switchAudioModeForNormalSpeakers();
  27708. }
  27709. }
  27710. },
  27711. enumerable: true,
  27712. configurable: true
  27713. });
  27714. Scene.prototype._switchAudioModeForHeadphones = function () {
  27715. this.mainSoundTrack.switchPanningModelToHRTF();
  27716. for (var i = 0; i < this.soundTracks.length; i++) {
  27717. this.soundTracks[i].switchPanningModelToHRTF();
  27718. }
  27719. };
  27720. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27721. this.mainSoundTrack.switchPanningModelToEqualPower();
  27722. for (var i = 0; i < this.soundTracks.length; i++) {
  27723. this.soundTracks[i].switchPanningModelToEqualPower();
  27724. }
  27725. };
  27726. /**
  27727. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27728. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27729. * @returns the created depth renderer
  27730. */
  27731. Scene.prototype.enableDepthRenderer = function (camera) {
  27732. camera = camera || this.activeCamera;
  27733. if (!camera) {
  27734. throw "No camera available to enable depth renderer";
  27735. }
  27736. if (!this._depthRenderer[camera.id]) {
  27737. var textureType = 0;
  27738. if (this._engine.getCaps().textureHalfFloatRender) {
  27739. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27740. }
  27741. else if (this._engine.getCaps().textureFloatRender) {
  27742. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27743. }
  27744. else {
  27745. throw "Depth renderer does not support int texture type";
  27746. }
  27747. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27748. }
  27749. return this._depthRenderer[camera.id];
  27750. };
  27751. /**
  27752. * Disables a depth renderer for a given camera
  27753. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27754. */
  27755. Scene.prototype.disableDepthRenderer = function (camera) {
  27756. camera = camera || this.activeCamera;
  27757. if (!camera || !this._depthRenderer[camera.id]) {
  27758. return;
  27759. }
  27760. this._depthRenderer[camera.id].dispose();
  27761. delete this._depthRenderer[camera.id];
  27762. };
  27763. /**
  27764. * Enables a GeometryBufferRender and associates it with the scene
  27765. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27766. * @returns the GeometryBufferRenderer
  27767. */
  27768. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27769. if (ratio === void 0) { ratio = 1; }
  27770. if (this._geometryBufferRenderer) {
  27771. return this._geometryBufferRenderer;
  27772. }
  27773. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27774. if (!this._geometryBufferRenderer.isSupported) {
  27775. this._geometryBufferRenderer = null;
  27776. }
  27777. return this._geometryBufferRenderer;
  27778. };
  27779. /**
  27780. * Disables the GeometryBufferRender associated with the scene
  27781. */
  27782. Scene.prototype.disableGeometryBufferRenderer = function () {
  27783. if (!this._geometryBufferRenderer) {
  27784. return;
  27785. }
  27786. this._geometryBufferRenderer.dispose();
  27787. this._geometryBufferRenderer = null;
  27788. };
  27789. /**
  27790. * Freeze all materials
  27791. * A frozen material will not be updatable but should be faster to render
  27792. */
  27793. Scene.prototype.freezeMaterials = function () {
  27794. for (var i = 0; i < this.materials.length; i++) {
  27795. this.materials[i].freeze();
  27796. }
  27797. };
  27798. /**
  27799. * Unfreeze all materials
  27800. * A frozen material will not be updatable but should be faster to render
  27801. */
  27802. Scene.prototype.unfreezeMaterials = function () {
  27803. for (var i = 0; i < this.materials.length; i++) {
  27804. this.materials[i].unfreeze();
  27805. }
  27806. };
  27807. /**
  27808. * Releases all held ressources
  27809. */
  27810. Scene.prototype.dispose = function () {
  27811. this.beforeRender = null;
  27812. this.afterRender = null;
  27813. this.skeletons = [];
  27814. this.morphTargetManagers = [];
  27815. this.importedMeshesFiles = new Array();
  27816. this.stopAllAnimations();
  27817. this.resetCachedMaterial();
  27818. for (var key in this._depthRenderer) {
  27819. this._depthRenderer[key].dispose();
  27820. }
  27821. if (this._gamepadManager) {
  27822. this._gamepadManager.dispose();
  27823. this._gamepadManager = null;
  27824. }
  27825. // Smart arrays
  27826. if (this.activeCamera) {
  27827. this.activeCamera._activeMeshes.dispose();
  27828. this.activeCamera = null;
  27829. }
  27830. this._activeMeshes.dispose();
  27831. this._renderingManager.dispose();
  27832. this._processedMaterials.dispose();
  27833. this._activeParticleSystems.dispose();
  27834. this._activeSkeletons.dispose();
  27835. this._softwareSkinnedMeshes.dispose();
  27836. this._renderTargets.dispose();
  27837. this._registeredForLateAnimationBindings.dispose();
  27838. if (this._boundingBoxRenderer) {
  27839. this._boundingBoxRenderer.dispose();
  27840. }
  27841. this._meshesForIntersections.dispose();
  27842. this._toBeDisposed.dispose();
  27843. // Abort active requests
  27844. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27845. var request = _a[_i];
  27846. request.abort();
  27847. }
  27848. // Debug layer
  27849. if (this._debugLayer) {
  27850. this._debugLayer.hide();
  27851. }
  27852. // Events
  27853. this.onDisposeObservable.notifyObservers(this);
  27854. this.onDisposeObservable.clear();
  27855. this.onBeforeRenderObservable.clear();
  27856. this.onAfterRenderObservable.clear();
  27857. this.onBeforeRenderTargetsRenderObservable.clear();
  27858. this.onAfterRenderTargetsRenderObservable.clear();
  27859. this.onAfterStepObservable.clear();
  27860. this.onBeforeStepObservable.clear();
  27861. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27862. this.onAfterActiveMeshesEvaluationObservable.clear();
  27863. this.onBeforeParticlesRenderingObservable.clear();
  27864. this.onAfterParticlesRenderingObservable.clear();
  27865. this.onBeforeSpritesRenderingObservable.clear();
  27866. this.onAfterSpritesRenderingObservable.clear();
  27867. this.onBeforeDrawPhaseObservable.clear();
  27868. this.onAfterDrawPhaseObservable.clear();
  27869. this.onBeforePhysicsObservable.clear();
  27870. this.onAfterPhysicsObservable.clear();
  27871. this.onBeforeAnimationsObservable.clear();
  27872. this.onAfterAnimationsObservable.clear();
  27873. this.onDataLoadedObservable.clear();
  27874. this.detachControl();
  27875. // Release sounds & sounds tracks
  27876. if (BABYLON.AudioEngine) {
  27877. this.disposeSounds();
  27878. }
  27879. // VR Helper
  27880. if (this.VRHelper) {
  27881. this.VRHelper.dispose();
  27882. }
  27883. // Detach cameras
  27884. var canvas = this._engine.getRenderingCanvas();
  27885. if (canvas) {
  27886. var index;
  27887. for (index = 0; index < this.cameras.length; index++) {
  27888. this.cameras[index].detachControl(canvas);
  27889. }
  27890. }
  27891. // Release animation groups
  27892. while (this.animationGroups.length) {
  27893. this.animationGroups[0].dispose();
  27894. }
  27895. // Release lights
  27896. while (this.lights.length) {
  27897. this.lights[0].dispose();
  27898. }
  27899. // Release meshes
  27900. while (this.meshes.length) {
  27901. this.meshes[0].dispose(true);
  27902. }
  27903. while (this.transformNodes.length) {
  27904. this.removeTransformNode(this.transformNodes[0]);
  27905. }
  27906. // Release cameras
  27907. while (this.cameras.length) {
  27908. this.cameras[0].dispose();
  27909. }
  27910. // Release materials
  27911. if (this.defaultMaterial) {
  27912. this.defaultMaterial.dispose();
  27913. }
  27914. while (this.multiMaterials.length) {
  27915. this.multiMaterials[0].dispose();
  27916. }
  27917. while (this.materials.length) {
  27918. this.materials[0].dispose();
  27919. }
  27920. // Release particles
  27921. while (this.particleSystems.length) {
  27922. this.particleSystems[0].dispose();
  27923. }
  27924. // Release sprites
  27925. while (this.spriteManagers.length) {
  27926. this.spriteManagers[0].dispose();
  27927. }
  27928. // Release postProcesses
  27929. while (this.postProcesses.length) {
  27930. this.postProcesses[0].dispose();
  27931. }
  27932. // Release layers
  27933. while (this.layers.length) {
  27934. this.layers[0].dispose();
  27935. }
  27936. while (this.effectLayers.length) {
  27937. this.effectLayers[0].dispose();
  27938. }
  27939. // Release textures
  27940. while (this.textures.length) {
  27941. this.textures[0].dispose();
  27942. }
  27943. // Release UBO
  27944. this._sceneUbo.dispose();
  27945. if (this._alternateSceneUbo) {
  27946. this._alternateSceneUbo.dispose();
  27947. }
  27948. // Post-processes
  27949. this.postProcessManager.dispose();
  27950. if (this._postProcessRenderPipelineManager) {
  27951. this._postProcessRenderPipelineManager.dispose();
  27952. }
  27953. // Physics
  27954. if (this._physicsEngine) {
  27955. this.disablePhysicsEngine();
  27956. }
  27957. // Remove from engine
  27958. index = this._engine.scenes.indexOf(this);
  27959. if (index > -1) {
  27960. this._engine.scenes.splice(index, 1);
  27961. }
  27962. this._engine.wipeCaches(true);
  27963. this._isDisposed = true;
  27964. };
  27965. Object.defineProperty(Scene.prototype, "isDisposed", {
  27966. /**
  27967. * Gets if the scene is already disposed
  27968. */
  27969. get: function () {
  27970. return this._isDisposed;
  27971. },
  27972. enumerable: true,
  27973. configurable: true
  27974. });
  27975. /**
  27976. * Releases sounds & soundtracks
  27977. */
  27978. Scene.prototype.disposeSounds = function () {
  27979. if (!this._mainSoundTrack) {
  27980. return;
  27981. }
  27982. this.mainSoundTrack.dispose();
  27983. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27984. this.soundTracks[scIndex].dispose();
  27985. }
  27986. };
  27987. // Octrees
  27988. /**
  27989. * Get the world extend vectors with an optional filter
  27990. *
  27991. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27992. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27993. */
  27994. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27995. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27996. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27997. filterPredicate = filterPredicate || (function () { return true; });
  27998. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27999. mesh.computeWorldMatrix(true);
  28000. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28001. return;
  28002. }
  28003. var boundingInfo = mesh.getBoundingInfo();
  28004. var minBox = boundingInfo.boundingBox.minimumWorld;
  28005. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28006. BABYLON.Tools.CheckExtends(minBox, min, max);
  28007. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28008. });
  28009. return {
  28010. min: min,
  28011. max: max
  28012. };
  28013. };
  28014. /**
  28015. * Creates or updates the octree used to boost selection (picking)
  28016. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28017. * @param maxCapacity defines the maximum capacity per leaf
  28018. * @param maxDepth defines the maximum depth of the octree
  28019. * @returns an octree of AbstractMesh
  28020. */
  28021. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28022. if (maxCapacity === void 0) { maxCapacity = 64; }
  28023. if (maxDepth === void 0) { maxDepth = 2; }
  28024. if (!this._selectionOctree) {
  28025. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28026. }
  28027. var worldExtends = this.getWorldExtends();
  28028. // Update octree
  28029. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28030. return this._selectionOctree;
  28031. };
  28032. // Picking
  28033. /**
  28034. * Creates a ray that can be used to pick in the scene
  28035. * @param x defines the x coordinate of the origin (on-screen)
  28036. * @param y defines the y coordinate of the origin (on-screen)
  28037. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28038. * @param camera defines the camera to use for the picking
  28039. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28040. * @returns a Ray
  28041. */
  28042. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28043. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28044. var result = BABYLON.Ray.Zero();
  28045. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28046. return result;
  28047. };
  28048. /**
  28049. * Creates a ray that can be used to pick in the scene
  28050. * @param x defines the x coordinate of the origin (on-screen)
  28051. * @param y defines the y coordinate of the origin (on-screen)
  28052. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28053. * @param result defines the ray where to store the picking ray
  28054. * @param camera defines the camera to use for the picking
  28055. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28056. * @returns the current scene
  28057. */
  28058. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28059. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28060. var engine = this._engine;
  28061. if (!camera) {
  28062. if (!this.activeCamera)
  28063. throw new Error("Active camera not set");
  28064. camera = this.activeCamera;
  28065. }
  28066. var cameraViewport = camera.viewport;
  28067. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28068. // Moving coordinates to local viewport world
  28069. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28070. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28071. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28072. return this;
  28073. };
  28074. /**
  28075. * Creates a ray that can be used to pick in the scene
  28076. * @param x defines the x coordinate of the origin (on-screen)
  28077. * @param y defines the y coordinate of the origin (on-screen)
  28078. * @param camera defines the camera to use for the picking
  28079. * @returns a Ray
  28080. */
  28081. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28082. var result = BABYLON.Ray.Zero();
  28083. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28084. return result;
  28085. };
  28086. /**
  28087. * Creates a ray that can be used to pick in the scene
  28088. * @param x defines the x coordinate of the origin (on-screen)
  28089. * @param y defines the y coordinate of the origin (on-screen)
  28090. * @param result defines the ray where to store the picking ray
  28091. * @param camera defines the camera to use for the picking
  28092. * @returns the current scene
  28093. */
  28094. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28095. if (!BABYLON.PickingInfo) {
  28096. return this;
  28097. }
  28098. var engine = this._engine;
  28099. if (!camera) {
  28100. if (!this.activeCamera)
  28101. throw new Error("Active camera not set");
  28102. camera = this.activeCamera;
  28103. }
  28104. var cameraViewport = camera.viewport;
  28105. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28106. var identity = BABYLON.Matrix.Identity();
  28107. // Moving coordinates to local viewport world
  28108. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28109. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28110. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28111. return this;
  28112. };
  28113. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28114. if (!BABYLON.PickingInfo) {
  28115. return null;
  28116. }
  28117. var pickingInfo = null;
  28118. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28119. var mesh = this.meshes[meshIndex];
  28120. if (predicate) {
  28121. if (!predicate(mesh)) {
  28122. continue;
  28123. }
  28124. }
  28125. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28126. continue;
  28127. }
  28128. var world = mesh.getWorldMatrix();
  28129. var ray = rayFunction(world);
  28130. var result = mesh.intersects(ray, fastCheck);
  28131. if (!result || !result.hit)
  28132. continue;
  28133. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28134. continue;
  28135. pickingInfo = result;
  28136. if (fastCheck) {
  28137. break;
  28138. }
  28139. }
  28140. return pickingInfo || new BABYLON.PickingInfo();
  28141. };
  28142. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28143. if (!BABYLON.PickingInfo) {
  28144. return null;
  28145. }
  28146. var pickingInfos = new Array();
  28147. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28148. var mesh = this.meshes[meshIndex];
  28149. if (predicate) {
  28150. if (!predicate(mesh)) {
  28151. continue;
  28152. }
  28153. }
  28154. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28155. continue;
  28156. }
  28157. var world = mesh.getWorldMatrix();
  28158. var ray = rayFunction(world);
  28159. var result = mesh.intersects(ray, false);
  28160. if (!result || !result.hit)
  28161. continue;
  28162. pickingInfos.push(result);
  28163. }
  28164. return pickingInfos;
  28165. };
  28166. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28167. if (!BABYLON.PickingInfo) {
  28168. return null;
  28169. }
  28170. var pickingInfo = null;
  28171. if (!camera) {
  28172. if (!this.activeCamera) {
  28173. return null;
  28174. }
  28175. camera = this.activeCamera;
  28176. }
  28177. if (this.spriteManagers.length > 0) {
  28178. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28179. var spriteManager = this.spriteManagers[spriteIndex];
  28180. if (!spriteManager.isPickable) {
  28181. continue;
  28182. }
  28183. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28184. if (!result || !result.hit)
  28185. continue;
  28186. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28187. continue;
  28188. pickingInfo = result;
  28189. if (fastCheck) {
  28190. break;
  28191. }
  28192. }
  28193. }
  28194. return pickingInfo || new BABYLON.PickingInfo();
  28195. };
  28196. /** Launch a ray to try to pick a mesh in the scene
  28197. * @param x position on screen
  28198. * @param y position on screen
  28199. * @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
  28200. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28201. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28202. * @returns a PickingInfo
  28203. */
  28204. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28205. var _this = this;
  28206. if (!BABYLON.PickingInfo) {
  28207. return null;
  28208. }
  28209. return this._internalPick(function (world) {
  28210. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28211. return _this._tempPickingRay;
  28212. }, predicate, fastCheck);
  28213. };
  28214. /** Launch a ray to try to pick a sprite in the scene
  28215. * @param x position on screen
  28216. * @param y position on screen
  28217. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28218. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28219. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28220. * @returns a PickingInfo
  28221. */
  28222. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28223. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28224. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28225. };
  28226. /** Use the given ray to pick a mesh in the scene
  28227. * @param ray The ray to use to pick meshes
  28228. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28229. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28230. * @returns a PickingInfo
  28231. */
  28232. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28233. var _this = this;
  28234. return this._internalPick(function (world) {
  28235. if (!_this._pickWithRayInverseMatrix) {
  28236. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28237. }
  28238. world.invertToRef(_this._pickWithRayInverseMatrix);
  28239. if (!_this._cachedRayForTransform) {
  28240. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28241. }
  28242. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28243. return _this._cachedRayForTransform;
  28244. }, predicate, fastCheck);
  28245. };
  28246. /**
  28247. * Launch a ray to try to pick a mesh in the scene
  28248. * @param x X position on screen
  28249. * @param y Y position on screen
  28250. * @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
  28251. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28252. * @returns an array of PickingInfo
  28253. */
  28254. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28255. var _this = this;
  28256. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28257. };
  28258. /**
  28259. * Launch a ray to try to pick a mesh in the scene
  28260. * @param ray Ray to use
  28261. * @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
  28262. * @returns an array of PickingInfo
  28263. */
  28264. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28265. var _this = this;
  28266. return this._internalMultiPick(function (world) {
  28267. if (!_this._pickWithRayInverseMatrix) {
  28268. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28269. }
  28270. world.invertToRef(_this._pickWithRayInverseMatrix);
  28271. if (!_this._cachedRayForTransform) {
  28272. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28273. }
  28274. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28275. return _this._cachedRayForTransform;
  28276. }, predicate);
  28277. };
  28278. /**
  28279. * Force the value of meshUnderPointer
  28280. * @param mesh defines the mesh to use
  28281. */
  28282. Scene.prototype.setPointerOverMesh = function (mesh) {
  28283. if (this._pointerOverMesh === mesh) {
  28284. return;
  28285. }
  28286. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28287. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28288. }
  28289. this._pointerOverMesh = mesh;
  28290. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28291. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28292. }
  28293. };
  28294. /**
  28295. * Gets the mesh under the pointer
  28296. * @returns a Mesh or null if no mesh is under the pointer
  28297. */
  28298. Scene.prototype.getPointerOverMesh = function () {
  28299. return this._pointerOverMesh;
  28300. };
  28301. /**
  28302. * Force the sprite under the pointer
  28303. * @param sprite defines the sprite to use
  28304. */
  28305. Scene.prototype.setPointerOverSprite = function (sprite) {
  28306. if (this._pointerOverSprite === sprite) {
  28307. return;
  28308. }
  28309. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28310. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28311. }
  28312. this._pointerOverSprite = sprite;
  28313. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28314. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28315. }
  28316. };
  28317. /**
  28318. * Gets the sprite under the pointer
  28319. * @returns a Sprite or null if no sprite is under the pointer
  28320. */
  28321. Scene.prototype.getPointerOverSprite = function () {
  28322. return this._pointerOverSprite;
  28323. };
  28324. // Physics
  28325. /**
  28326. * Gets the current physics engine
  28327. * @returns a PhysicsEngine or null if none attached
  28328. */
  28329. Scene.prototype.getPhysicsEngine = function () {
  28330. return this._physicsEngine;
  28331. };
  28332. /**
  28333. * Enables physics to the current scene
  28334. * @param gravity defines the scene's gravity for the physics engine
  28335. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28336. * @return a boolean indicating if the physics engine was initialized
  28337. */
  28338. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28339. if (gravity === void 0) { gravity = null; }
  28340. if (this._physicsEngine) {
  28341. return true;
  28342. }
  28343. try {
  28344. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28345. return true;
  28346. }
  28347. catch (e) {
  28348. BABYLON.Tools.Error(e.message);
  28349. return false;
  28350. }
  28351. };
  28352. /**
  28353. * Disables and disposes the physics engine associated with the scene
  28354. */
  28355. Scene.prototype.disablePhysicsEngine = function () {
  28356. if (!this._physicsEngine) {
  28357. return;
  28358. }
  28359. this._physicsEngine.dispose();
  28360. this._physicsEngine = null;
  28361. };
  28362. /**
  28363. * Gets a boolean indicating if there is an active physics engine
  28364. * @returns a boolean indicating if there is an active physics engine
  28365. */
  28366. Scene.prototype.isPhysicsEnabled = function () {
  28367. return this._physicsEngine !== undefined;
  28368. };
  28369. /**
  28370. * Deletes a physics compound impostor
  28371. * @param compound defines the compound to delete
  28372. */
  28373. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28374. var mesh = compound.parts[0].mesh;
  28375. if (mesh.physicsImpostor) {
  28376. mesh.physicsImpostor.dispose( /*true*/);
  28377. mesh.physicsImpostor = null;
  28378. }
  28379. };
  28380. // Misc.
  28381. /** @hidden */
  28382. Scene.prototype._rebuildGeometries = function () {
  28383. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28384. var geometry = _a[_i];
  28385. geometry._rebuild();
  28386. }
  28387. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28388. var mesh = _c[_b];
  28389. mesh._rebuild();
  28390. }
  28391. if (this.postProcessManager) {
  28392. this.postProcessManager._rebuild();
  28393. }
  28394. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28395. var layer = _e[_d];
  28396. layer._rebuild();
  28397. }
  28398. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28399. var effectLayer = _g[_f];
  28400. effectLayer._rebuild();
  28401. }
  28402. if (this._boundingBoxRenderer) {
  28403. this._boundingBoxRenderer._rebuild();
  28404. }
  28405. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28406. var system = _j[_h];
  28407. system.rebuild();
  28408. }
  28409. if (this._postProcessRenderPipelineManager) {
  28410. this._postProcessRenderPipelineManager._rebuild();
  28411. }
  28412. };
  28413. /** @hidden */
  28414. Scene.prototype._rebuildTextures = function () {
  28415. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28416. var texture = _a[_i];
  28417. texture._rebuild();
  28418. }
  28419. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28420. };
  28421. /**
  28422. * Creates a default light for the scene.
  28423. * @param replace Whether to replace the existing lights in the scene.
  28424. */
  28425. Scene.prototype.createDefaultLight = function (replace) {
  28426. if (replace === void 0) { replace = false; }
  28427. // Dispose existing light in replace mode.
  28428. if (replace) {
  28429. if (this.lights) {
  28430. for (var i = 0; i < this.lights.length; i++) {
  28431. this.lights[i].dispose();
  28432. }
  28433. }
  28434. }
  28435. // Light
  28436. if (this.lights.length === 0) {
  28437. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28438. }
  28439. };
  28440. /**
  28441. * Creates a default camera for the scene.
  28442. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28443. * @param replace Whether to replace the existing active camera in the scene.
  28444. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28445. */
  28446. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28447. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28448. if (replace === void 0) { replace = false; }
  28449. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28450. // Dispose existing camera in replace mode.
  28451. if (replace) {
  28452. if (this.activeCamera) {
  28453. this.activeCamera.dispose();
  28454. this.activeCamera = null;
  28455. }
  28456. }
  28457. // Camera
  28458. if (!this.activeCamera) {
  28459. var worldExtends = this.getWorldExtends();
  28460. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28461. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28462. var camera;
  28463. var radius = worldSize.length() * 1.5;
  28464. // empty scene scenario!
  28465. if (!isFinite(radius)) {
  28466. radius = 1;
  28467. worldCenter.copyFromFloats(0, 0, 0);
  28468. }
  28469. if (createArcRotateCamera) {
  28470. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28471. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28472. arcRotateCamera.wheelPrecision = 100 / radius;
  28473. camera = arcRotateCamera;
  28474. }
  28475. else {
  28476. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28477. freeCamera.setTarget(worldCenter);
  28478. camera = freeCamera;
  28479. }
  28480. camera.minZ = radius * 0.01;
  28481. camera.maxZ = radius * 1000;
  28482. camera.speed = radius * 0.2;
  28483. this.activeCamera = camera;
  28484. var canvas = this.getEngine().getRenderingCanvas();
  28485. if (attachCameraControls && canvas) {
  28486. camera.attachControl(canvas);
  28487. }
  28488. }
  28489. };
  28490. /**
  28491. * Creates a default camera and a default light
  28492. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28493. * @param replace defines if the camera and/or light will replace the existing ones
  28494. * @param attachCameraControls defines if attachControl will be called on the new camera
  28495. */
  28496. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28497. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28498. if (replace === void 0) { replace = false; }
  28499. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28500. this.createDefaultLight(replace);
  28501. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28502. };
  28503. /**
  28504. * Creates a new sky box
  28505. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28506. * @param environmentTexture defines the texture to use as environment texture
  28507. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28508. * @param scale defines the overall scale of the skybox
  28509. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28510. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28511. * @returns a new mesh holding the sky box
  28512. */
  28513. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28514. if (pbr === void 0) { pbr = false; }
  28515. if (scale === void 0) { scale = 1000; }
  28516. if (blur === void 0) { blur = 0; }
  28517. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28518. if (!environmentTexture) {
  28519. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28520. return null;
  28521. }
  28522. if (setGlobalEnvTexture) {
  28523. if (environmentTexture) {
  28524. this.environmentTexture = environmentTexture;
  28525. }
  28526. }
  28527. // Skybox
  28528. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28529. if (pbr) {
  28530. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28531. hdrSkyboxMaterial.backFaceCulling = false;
  28532. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28533. if (hdrSkyboxMaterial.reflectionTexture) {
  28534. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28535. }
  28536. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28537. hdrSkyboxMaterial.disableLighting = true;
  28538. hdrSkyboxMaterial.twoSidedLighting = true;
  28539. hdrSkybox.infiniteDistance = true;
  28540. hdrSkybox.material = hdrSkyboxMaterial;
  28541. }
  28542. else {
  28543. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28544. skyboxMaterial.backFaceCulling = false;
  28545. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28546. if (skyboxMaterial.reflectionTexture) {
  28547. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28548. }
  28549. skyboxMaterial.disableLighting = true;
  28550. hdrSkybox.infiniteDistance = true;
  28551. hdrSkybox.material = skyboxMaterial;
  28552. }
  28553. return hdrSkybox;
  28554. };
  28555. /**
  28556. * Creates a new environment
  28557. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28558. * @param options defines the options you can use to configure the environment
  28559. * @returns the new EnvironmentHelper
  28560. */
  28561. Scene.prototype.createDefaultEnvironment = function (options) {
  28562. if (BABYLON.EnvironmentHelper) {
  28563. return new BABYLON.EnvironmentHelper(options, this);
  28564. }
  28565. return null;
  28566. };
  28567. /**
  28568. * Creates a new VREXperienceHelper
  28569. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28570. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28571. * @returns a new VREXperienceHelper
  28572. */
  28573. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28574. if (webVROptions === void 0) { webVROptions = {}; }
  28575. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28576. };
  28577. // Tags
  28578. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28579. if (tagsQuery === undefined) {
  28580. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28581. return list;
  28582. }
  28583. var listByTags = [];
  28584. forEach = forEach || (function (item) { return; });
  28585. for (var i in list) {
  28586. var item = list[i];
  28587. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28588. listByTags.push(item);
  28589. forEach(item);
  28590. }
  28591. }
  28592. return listByTags;
  28593. };
  28594. /**
  28595. * Get a list of meshes 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 Mesh
  28599. */
  28600. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28601. return this._getByTags(this.meshes, tagsQuery, forEach);
  28602. };
  28603. /**
  28604. * Get a list of cameras by tags
  28605. * @param tagsQuery defines the tags query to use
  28606. * @param forEach defines a predicate used to filter results
  28607. * @returns an array of Camera
  28608. */
  28609. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28610. return this._getByTags(this.cameras, tagsQuery, forEach);
  28611. };
  28612. /**
  28613. * Get a list of lights by tags
  28614. * @param tagsQuery defines the tags query to use
  28615. * @param forEach defines a predicate used to filter results
  28616. * @returns an array of Light
  28617. */
  28618. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28619. return this._getByTags(this.lights, tagsQuery, forEach);
  28620. };
  28621. /**
  28622. * Get a list of materials by tags
  28623. * @param tagsQuery defines the tags query to use
  28624. * @param forEach defines a predicate used to filter results
  28625. * @returns an array of Material
  28626. */
  28627. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28628. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28629. };
  28630. /**
  28631. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28632. * This allowed control for front to back rendering or reversly depending of the special needs.
  28633. *
  28634. * @param renderingGroupId The rendering group id corresponding to its index
  28635. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28636. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28637. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28638. */
  28639. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28640. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28641. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28642. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28643. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28644. };
  28645. /**
  28646. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28647. *
  28648. * @param renderingGroupId The rendering group id corresponding to its index
  28649. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28650. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28651. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28652. */
  28653. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28654. if (depth === void 0) { depth = true; }
  28655. if (stencil === void 0) { stencil = true; }
  28656. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28657. };
  28658. /**
  28659. * Will flag all materials as dirty to trigger new shader compilation
  28660. * @param flag defines the flag used to specify which material part must be marked as dirty
  28661. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28662. */
  28663. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28664. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28665. var material = _a[_i];
  28666. if (predicate && !predicate(material)) {
  28667. continue;
  28668. }
  28669. material.markAsDirty(flag);
  28670. }
  28671. };
  28672. /** @hidden */
  28673. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28674. var _this = this;
  28675. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28676. this._activeRequests.push(request);
  28677. request.onCompleteObservable.add(function (request) {
  28678. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28679. });
  28680. return request;
  28681. };
  28682. /** @hidden */
  28683. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28684. var _this = this;
  28685. return new Promise(function (resolve, reject) {
  28686. _this._loadFile(url, function (data) {
  28687. resolve(data);
  28688. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28689. reject(exception);
  28690. });
  28691. });
  28692. };
  28693. // Statics
  28694. Scene._FOGMODE_NONE = 0;
  28695. Scene._FOGMODE_EXP = 1;
  28696. Scene._FOGMODE_EXP2 = 2;
  28697. Scene._FOGMODE_LINEAR = 3;
  28698. Scene._uniqueIdCounter = 0;
  28699. /**
  28700. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28701. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28702. */
  28703. Scene.MinDeltaTime = 1.0;
  28704. /**
  28705. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28706. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28707. */
  28708. Scene.MaxDeltaTime = 1000.0;
  28709. /** The distance in pixel that you have to move to prevent some events */
  28710. Scene.DragMovementThreshold = 10; // in pixels
  28711. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28712. Scene.LongPressDelay = 500; // in milliseconds
  28713. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28714. Scene.DoubleClickDelay = 300; // in milliseconds
  28715. /** If you need to check double click without raising a single click at first click, enable this flag */
  28716. Scene.ExclusiveDoubleClickMode = false;
  28717. return Scene;
  28718. }());
  28719. BABYLON.Scene = Scene;
  28720. })(BABYLON || (BABYLON = {}));
  28721. //# sourceMappingURL=babylon.scene.js.map
  28722. var BABYLON;
  28723. (function (BABYLON) {
  28724. /**
  28725. * Set of assets to keep when moving a scene into an asset container.
  28726. */
  28727. var KeepAssets = /** @class */ (function () {
  28728. function KeepAssets() {
  28729. /**
  28730. * Cameras to keep.
  28731. */
  28732. this.cameras = new Array();
  28733. /**
  28734. * Lights to keep.
  28735. */
  28736. this.lights = new Array();
  28737. /**
  28738. * Meshes to keep.
  28739. */
  28740. this.meshes = new Array();
  28741. /**
  28742. * Skeletons to keep.
  28743. */
  28744. this.skeletons = new Array();
  28745. /**
  28746. * ParticleSystems to keep.
  28747. */
  28748. this.particleSystems = new Array();
  28749. /**
  28750. * Animations to keep.
  28751. */
  28752. this.animations = new Array();
  28753. /**
  28754. * AnimationGroups to keep.
  28755. */
  28756. this.animationGroups = new Array();
  28757. /**
  28758. * MultiMaterials to keep.
  28759. */
  28760. this.multiMaterials = new Array();
  28761. /**
  28762. * Materials to keep.
  28763. */
  28764. this.materials = new Array();
  28765. /**
  28766. * MorphTargetManagers to keep.
  28767. */
  28768. this.morphTargetManagers = new Array();
  28769. /**
  28770. * Geometries to keep.
  28771. */
  28772. this.geometries = new Array();
  28773. /**
  28774. * TransformNodes to keep.
  28775. */
  28776. this.transformNodes = new Array();
  28777. /**
  28778. * LensFlareSystems to keep.
  28779. */
  28780. this.lensFlareSystems = new Array();
  28781. /**
  28782. * ShadowGenerators to keep.
  28783. */
  28784. this.shadowGenerators = new Array();
  28785. /**
  28786. * ActionManagers to keep.
  28787. */
  28788. this.actionManagers = new Array();
  28789. /**
  28790. * Sounds to keep.
  28791. */
  28792. this.sounds = new Array();
  28793. /**
  28794. * Textures to keep.
  28795. */
  28796. this.textures = new Array();
  28797. /**
  28798. * Effect layers to keep.
  28799. */
  28800. this.effectLayers = new Array();
  28801. }
  28802. return KeepAssets;
  28803. }());
  28804. BABYLON.KeepAssets = KeepAssets;
  28805. /**
  28806. * Container with a set of assets that can be added or removed from a scene.
  28807. */
  28808. var AssetContainer = /** @class */ (function () {
  28809. /**
  28810. * Instantiates an AssetContainer.
  28811. * @param scene The scene the AssetContainer belongs to.
  28812. */
  28813. function AssetContainer(scene) {
  28814. // Objects
  28815. /**
  28816. * Cameras populated in the container.
  28817. */
  28818. this.cameras = new Array();
  28819. /**
  28820. * Lights populated in the container.
  28821. */
  28822. this.lights = new Array();
  28823. /**
  28824. * Meshes populated in the container.
  28825. */
  28826. this.meshes = new Array();
  28827. /**
  28828. * Skeletons populated in the container.
  28829. */
  28830. this.skeletons = new Array();
  28831. /**
  28832. * ParticleSystems populated in the container.
  28833. */
  28834. this.particleSystems = new Array();
  28835. /**
  28836. * Animations populated in the container.
  28837. */
  28838. this.animations = new Array();
  28839. /**
  28840. * AnimationGroups populated in the container.
  28841. */
  28842. this.animationGroups = new Array();
  28843. /**
  28844. * MultiMaterials populated in the container.
  28845. */
  28846. this.multiMaterials = new Array();
  28847. /**
  28848. * Materials populated in the container.
  28849. */
  28850. this.materials = new Array();
  28851. /**
  28852. * MorphTargetManagers populated in the container.
  28853. */
  28854. this.morphTargetManagers = new Array();
  28855. /**
  28856. * Geometries populated in the container.
  28857. */
  28858. this.geometries = new Array();
  28859. /**
  28860. * TransformNodes populated in the container.
  28861. */
  28862. this.transformNodes = new Array();
  28863. /**
  28864. * LensFlareSystems populated in the container.
  28865. */
  28866. this.lensFlareSystems = new Array();
  28867. /**
  28868. * ShadowGenerators populated in the container.
  28869. */
  28870. this.shadowGenerators = new Array();
  28871. /**
  28872. * ActionManagers populated in the container.
  28873. */
  28874. this.actionManagers = new Array();
  28875. /**
  28876. * Sounds populated in the container.
  28877. */
  28878. this.sounds = new Array();
  28879. /**
  28880. * Textures populated in the container.
  28881. */
  28882. this.textures = new Array();
  28883. /**
  28884. * Effect layers populated in the container.
  28885. */
  28886. this.effectLayers = new Array();
  28887. this.scene = scene;
  28888. }
  28889. /**
  28890. * Adds all the assets from the container to the scene.
  28891. */
  28892. AssetContainer.prototype.addAllToScene = function () {
  28893. var _this = this;
  28894. this.cameras.forEach(function (o) {
  28895. _this.scene.addCamera(o);
  28896. });
  28897. this.lights.forEach(function (o) {
  28898. _this.scene.addLight(o);
  28899. });
  28900. this.meshes.forEach(function (o) {
  28901. _this.scene.addMesh(o);
  28902. });
  28903. this.skeletons.forEach(function (o) {
  28904. _this.scene.addSkeleton(o);
  28905. });
  28906. this.particleSystems.forEach(function (o) {
  28907. _this.scene.addParticleSystem(o);
  28908. });
  28909. this.animations.forEach(function (o) {
  28910. _this.scene.addAnimation(o);
  28911. });
  28912. this.animationGroups.forEach(function (o) {
  28913. _this.scene.addAnimationGroup(o);
  28914. });
  28915. this.multiMaterials.forEach(function (o) {
  28916. _this.scene.addMultiMaterial(o);
  28917. });
  28918. this.materials.forEach(function (o) {
  28919. _this.scene.addMaterial(o);
  28920. });
  28921. this.morphTargetManagers.forEach(function (o) {
  28922. _this.scene.addMorphTargetManager(o);
  28923. });
  28924. this.geometries.forEach(function (o) {
  28925. _this.scene.addGeometry(o);
  28926. });
  28927. this.transformNodes.forEach(function (o) {
  28928. _this.scene.addTransformNode(o);
  28929. });
  28930. this.lensFlareSystems.forEach(function (o) {
  28931. _this.scene.addLensFlareSystem(o);
  28932. });
  28933. this.actionManagers.forEach(function (o) {
  28934. _this.scene.addActionManager(o);
  28935. });
  28936. this.sounds.forEach(function (o) {
  28937. o.play();
  28938. o.autoplay = true;
  28939. _this.scene.mainSoundTrack.AddSound(o);
  28940. });
  28941. this.textures.forEach(function (o) {
  28942. _this.scene.addTexture(o);
  28943. });
  28944. this.effectLayers.forEach(function (o) {
  28945. _this.scene.addEffectLayer(o);
  28946. });
  28947. };
  28948. /**
  28949. * Removes all the assets in the container from the scene
  28950. */
  28951. AssetContainer.prototype.removeAllFromScene = function () {
  28952. var _this = this;
  28953. this.cameras.forEach(function (o) {
  28954. _this.scene.removeCamera(o);
  28955. });
  28956. this.lights.forEach(function (o) {
  28957. _this.scene.removeLight(o);
  28958. });
  28959. this.meshes.forEach(function (o) {
  28960. _this.scene.removeMesh(o);
  28961. });
  28962. this.skeletons.forEach(function (o) {
  28963. _this.scene.removeSkeleton(o);
  28964. });
  28965. this.particleSystems.forEach(function (o) {
  28966. _this.scene.removeParticleSystem(o);
  28967. });
  28968. this.animations.forEach(function (o) {
  28969. _this.scene.removeAnimation(o);
  28970. });
  28971. this.animationGroups.forEach(function (o) {
  28972. _this.scene.removeAnimationGroup(o);
  28973. });
  28974. this.multiMaterials.forEach(function (o) {
  28975. _this.scene.removeMultiMaterial(o);
  28976. });
  28977. this.materials.forEach(function (o) {
  28978. _this.scene.removeMaterial(o);
  28979. });
  28980. this.morphTargetManagers.forEach(function (o) {
  28981. _this.scene.removeMorphTargetManager(o);
  28982. });
  28983. this.geometries.forEach(function (o) {
  28984. _this.scene.removeGeometry(o);
  28985. });
  28986. this.transformNodes.forEach(function (o) {
  28987. _this.scene.removeTransformNode(o);
  28988. });
  28989. this.lensFlareSystems.forEach(function (o) {
  28990. _this.scene.removeLensFlareSystem(o);
  28991. });
  28992. this.actionManagers.forEach(function (o) {
  28993. _this.scene.removeActionManager(o);
  28994. });
  28995. this.sounds.forEach(function (o) {
  28996. o.stop();
  28997. o.autoplay = false;
  28998. _this.scene.mainSoundTrack.RemoveSound(o);
  28999. });
  29000. this.textures.forEach(function (o) {
  29001. _this.scene.removeTexture(o);
  29002. });
  29003. this.effectLayers.forEach(function (o) {
  29004. _this.scene.removeEffectLayer(o);
  29005. });
  29006. };
  29007. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29008. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29009. var asset = sourceAssets_1[_i];
  29010. var move = true;
  29011. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29012. var keepAsset = keepAssets_1[_a];
  29013. if (asset === keepAsset) {
  29014. move = false;
  29015. break;
  29016. }
  29017. }
  29018. if (move) {
  29019. targetAssets.push(asset);
  29020. }
  29021. }
  29022. };
  29023. /**
  29024. * Removes all the assets contained in the scene and adds them to the container.
  29025. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29026. */
  29027. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29028. if (keepAssets === undefined) {
  29029. keepAssets = new KeepAssets();
  29030. }
  29031. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29032. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29033. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29034. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29035. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29036. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29037. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29038. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29039. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29040. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29041. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29042. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29043. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29044. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29045. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29046. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29047. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29048. this.removeAllFromScene();
  29049. };
  29050. return AssetContainer;
  29051. }());
  29052. BABYLON.AssetContainer = AssetContainer;
  29053. })(BABYLON || (BABYLON = {}));
  29054. //# sourceMappingURL=babylon.assetContainer.js.map
  29055. var BABYLON;
  29056. (function (BABYLON) {
  29057. var Buffer = /** @class */ (function () {
  29058. /**
  29059. * Constructor
  29060. * @param engine the engine
  29061. * @param data the data to use for this buffer
  29062. * @param updatable whether the data is updatable
  29063. * @param stride the stride (optional)
  29064. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29065. * @param instanced whether the buffer is instanced (optional)
  29066. * @param useBytes set to true if the stride in in bytes (optional)
  29067. */
  29068. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29069. if (stride === void 0) { stride = 0; }
  29070. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29071. if (instanced === void 0) { instanced = false; }
  29072. if (useBytes === void 0) { useBytes = false; }
  29073. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29074. this._engine = engine.getScene().getEngine();
  29075. }
  29076. else {
  29077. this._engine = engine;
  29078. }
  29079. this._updatable = updatable;
  29080. this._instanced = instanced;
  29081. this._data = data;
  29082. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29083. if (!postponeInternalCreation) { // by default
  29084. this.create();
  29085. }
  29086. }
  29087. /**
  29088. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29089. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29090. * @param offset defines offset in the buffer (0 by default)
  29091. * @param size defines the size in floats of attributes (position is 3 for instance)
  29092. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29093. * @param instanced defines if the vertex buffer contains indexed data
  29094. * @param useBytes defines if the offset and stride are in bytes
  29095. * @returns the new vertex buffer
  29096. */
  29097. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29098. if (useBytes === void 0) { useBytes = false; }
  29099. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29100. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29101. // a lot of these parameters are ignored as they are overriden by the buffer
  29102. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29103. };
  29104. // Properties
  29105. Buffer.prototype.isUpdatable = function () {
  29106. return this._updatable;
  29107. };
  29108. Buffer.prototype.getData = function () {
  29109. return this._data;
  29110. };
  29111. Buffer.prototype.getBuffer = function () {
  29112. return this._buffer;
  29113. };
  29114. /**
  29115. * Gets the stride in float32 units (i.e. byte stride / 4).
  29116. * May not be an integer if the byte stride is not divisible by 4.
  29117. * DEPRECATED. Use byteStride instead.
  29118. * @returns the stride in float32 units
  29119. */
  29120. Buffer.prototype.getStrideSize = function () {
  29121. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29122. };
  29123. // Methods
  29124. Buffer.prototype.create = function (data) {
  29125. if (data === void 0) { data = null; }
  29126. if (!data && this._buffer) {
  29127. return; // nothing to do
  29128. }
  29129. data = data || this._data;
  29130. if (!data) {
  29131. return;
  29132. }
  29133. if (!this._buffer) { // create buffer
  29134. if (this._updatable) {
  29135. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29136. this._data = data;
  29137. }
  29138. else {
  29139. this._buffer = this._engine.createVertexBuffer(data);
  29140. }
  29141. }
  29142. else if (this._updatable) { // update buffer
  29143. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29144. this._data = data;
  29145. }
  29146. };
  29147. Buffer.prototype._rebuild = function () {
  29148. this._buffer = null;
  29149. this.create(this._data);
  29150. };
  29151. Buffer.prototype.update = function (data) {
  29152. this.create(data);
  29153. };
  29154. /**
  29155. * Updates the data directly.
  29156. * @param data the new data
  29157. * @param offset the new offset
  29158. * @param vertexCount the vertex count (optional)
  29159. * @param useBytes set to true if the offset is in bytes
  29160. */
  29161. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29162. if (useBytes === void 0) { useBytes = false; }
  29163. if (!this._buffer) {
  29164. return;
  29165. }
  29166. if (this._updatable) { // update buffer
  29167. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29168. this._data = null;
  29169. }
  29170. };
  29171. Buffer.prototype.dispose = function () {
  29172. if (!this._buffer) {
  29173. return;
  29174. }
  29175. if (this._engine._releaseBuffer(this._buffer)) {
  29176. this._buffer = null;
  29177. }
  29178. };
  29179. return Buffer;
  29180. }());
  29181. BABYLON.Buffer = Buffer;
  29182. })(BABYLON || (BABYLON = {}));
  29183. //# sourceMappingURL=babylon.buffer.js.map
  29184. var BABYLON;
  29185. (function (BABYLON) {
  29186. var VertexBuffer = /** @class */ (function () {
  29187. /**
  29188. * Constructor
  29189. * @param engine the engine
  29190. * @param data the data to use for this vertex buffer
  29191. * @param kind the vertex buffer kind
  29192. * @param updatable whether the data is updatable
  29193. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29194. * @param stride the stride (optional)
  29195. * @param instanced whether the buffer is instanced (optional)
  29196. * @param offset the offset of the data (optional)
  29197. * @param size the number of components (optional)
  29198. * @param type the type of the component (optional)
  29199. * @param normalized whether the data contains normalized data (optional)
  29200. * @param useBytes set to true if stride and offset are in bytes (optional)
  29201. */
  29202. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29203. if (normalized === void 0) { normalized = false; }
  29204. if (useBytes === void 0) { useBytes = false; }
  29205. if (data instanceof BABYLON.Buffer) {
  29206. this._buffer = data;
  29207. this._ownsBuffer = false;
  29208. }
  29209. else {
  29210. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29211. this._ownsBuffer = true;
  29212. }
  29213. this._kind = kind;
  29214. if (type == undefined) {
  29215. var data_1 = this.getData();
  29216. this.type = VertexBuffer.FLOAT;
  29217. if (data_1 instanceof Int8Array)
  29218. this.type = VertexBuffer.BYTE;
  29219. else if (data_1 instanceof Uint8Array)
  29220. this.type = VertexBuffer.UNSIGNED_BYTE;
  29221. else if (data_1 instanceof Int16Array)
  29222. this.type = VertexBuffer.SHORT;
  29223. else if (data_1 instanceof Uint16Array)
  29224. this.type = VertexBuffer.UNSIGNED_SHORT;
  29225. else if (data_1 instanceof Int32Array)
  29226. this.type = VertexBuffer.INT;
  29227. else if (data_1 instanceof Uint32Array)
  29228. this.type = VertexBuffer.UNSIGNED_INT;
  29229. }
  29230. else {
  29231. this.type = type;
  29232. }
  29233. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29234. if (useBytes) {
  29235. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29236. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29237. this.byteOffset = offset || 0;
  29238. }
  29239. else {
  29240. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29241. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29242. this.byteOffset = (offset || 0) * typeByteLength;
  29243. }
  29244. this.normalized = normalized;
  29245. this._instanced = instanced !== undefined ? instanced : false;
  29246. this._instanceDivisor = instanced ? 1 : 0;
  29247. }
  29248. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29249. /**
  29250. * Gets or sets the instance divisor when in instanced mode
  29251. */
  29252. get: function () {
  29253. return this._instanceDivisor;
  29254. },
  29255. set: function (value) {
  29256. this._instanceDivisor = value;
  29257. if (value == 0) {
  29258. this._instanced = false;
  29259. }
  29260. else {
  29261. this._instanced = true;
  29262. }
  29263. },
  29264. enumerable: true,
  29265. configurable: true
  29266. });
  29267. VertexBuffer.prototype._rebuild = function () {
  29268. if (!this._buffer) {
  29269. return;
  29270. }
  29271. this._buffer._rebuild();
  29272. };
  29273. /**
  29274. * Returns the kind of the VertexBuffer (string).
  29275. */
  29276. VertexBuffer.prototype.getKind = function () {
  29277. return this._kind;
  29278. };
  29279. // Properties
  29280. /**
  29281. * Boolean : is the VertexBuffer updatable ?
  29282. */
  29283. VertexBuffer.prototype.isUpdatable = function () {
  29284. return this._buffer.isUpdatable();
  29285. };
  29286. /**
  29287. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29288. */
  29289. VertexBuffer.prototype.getData = function () {
  29290. return this._buffer.getData();
  29291. };
  29292. /**
  29293. * Returns the WebGLBuffer associated to the VertexBuffer.
  29294. */
  29295. VertexBuffer.prototype.getBuffer = function () {
  29296. return this._buffer.getBuffer();
  29297. };
  29298. /**
  29299. * Returns the stride as a multiple of the type byte length.
  29300. * DEPRECATED. Use byteStride instead.
  29301. */
  29302. VertexBuffer.prototype.getStrideSize = function () {
  29303. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29304. };
  29305. /**
  29306. * Returns the offset as a multiple of the type byte length.
  29307. * DEPRECATED. Use byteOffset instead.
  29308. */
  29309. VertexBuffer.prototype.getOffset = function () {
  29310. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29311. };
  29312. /**
  29313. * Returns the number of components per vertex attribute (integer).
  29314. */
  29315. VertexBuffer.prototype.getSize = function () {
  29316. return this._size;
  29317. };
  29318. /**
  29319. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29320. */
  29321. VertexBuffer.prototype.getIsInstanced = function () {
  29322. return this._instanced;
  29323. };
  29324. /**
  29325. * Returns the instancing divisor, zero for non-instanced (integer).
  29326. */
  29327. VertexBuffer.prototype.getInstanceDivisor = function () {
  29328. return this._instanceDivisor;
  29329. };
  29330. // Methods
  29331. /**
  29332. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29333. * Returns the created WebGLBuffer.
  29334. */
  29335. VertexBuffer.prototype.create = function (data) {
  29336. return this._buffer.create(data);
  29337. };
  29338. /**
  29339. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29340. * This function will create a new buffer if the current one is not updatable
  29341. * Returns the updated WebGLBuffer.
  29342. */
  29343. VertexBuffer.prototype.update = function (data) {
  29344. return this._buffer.update(data);
  29345. };
  29346. /**
  29347. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29348. * Returns the directly updated WebGLBuffer.
  29349. * @param data the new data
  29350. * @param offset the new offset
  29351. * @param useBytes set to true if the offset is in bytes
  29352. */
  29353. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29354. if (useBytes === void 0) { useBytes = false; }
  29355. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29356. };
  29357. /**
  29358. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29359. */
  29360. VertexBuffer.prototype.dispose = function () {
  29361. if (this._ownsBuffer) {
  29362. this._buffer.dispose();
  29363. }
  29364. };
  29365. /**
  29366. * Enumerates each value of this vertex buffer as numbers.
  29367. * @param count the number of values to enumerate
  29368. * @param callback the callback function called for each value
  29369. */
  29370. VertexBuffer.prototype.forEach = function (count, callback) {
  29371. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29372. };
  29373. Object.defineProperty(VertexBuffer, "PositionKind", {
  29374. get: function () {
  29375. return VertexBuffer._PositionKind;
  29376. },
  29377. enumerable: true,
  29378. configurable: true
  29379. });
  29380. Object.defineProperty(VertexBuffer, "NormalKind", {
  29381. get: function () {
  29382. return VertexBuffer._NormalKind;
  29383. },
  29384. enumerable: true,
  29385. configurable: true
  29386. });
  29387. Object.defineProperty(VertexBuffer, "TangentKind", {
  29388. get: function () {
  29389. return VertexBuffer._TangentKind;
  29390. },
  29391. enumerable: true,
  29392. configurable: true
  29393. });
  29394. Object.defineProperty(VertexBuffer, "UVKind", {
  29395. get: function () {
  29396. return VertexBuffer._UVKind;
  29397. },
  29398. enumerable: true,
  29399. configurable: true
  29400. });
  29401. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29402. get: function () {
  29403. return VertexBuffer._UV2Kind;
  29404. },
  29405. enumerable: true,
  29406. configurable: true
  29407. });
  29408. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29409. get: function () {
  29410. return VertexBuffer._UV3Kind;
  29411. },
  29412. enumerable: true,
  29413. configurable: true
  29414. });
  29415. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29416. get: function () {
  29417. return VertexBuffer._UV4Kind;
  29418. },
  29419. enumerable: true,
  29420. configurable: true
  29421. });
  29422. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29423. get: function () {
  29424. return VertexBuffer._UV5Kind;
  29425. },
  29426. enumerable: true,
  29427. configurable: true
  29428. });
  29429. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29430. get: function () {
  29431. return VertexBuffer._UV6Kind;
  29432. },
  29433. enumerable: true,
  29434. configurable: true
  29435. });
  29436. Object.defineProperty(VertexBuffer, "ColorKind", {
  29437. get: function () {
  29438. return VertexBuffer._ColorKind;
  29439. },
  29440. enumerable: true,
  29441. configurable: true
  29442. });
  29443. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29444. get: function () {
  29445. return VertexBuffer._MatricesIndicesKind;
  29446. },
  29447. enumerable: true,
  29448. configurable: true
  29449. });
  29450. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29451. get: function () {
  29452. return VertexBuffer._MatricesWeightsKind;
  29453. },
  29454. enumerable: true,
  29455. configurable: true
  29456. });
  29457. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29458. get: function () {
  29459. return VertexBuffer._MatricesIndicesExtraKind;
  29460. },
  29461. enumerable: true,
  29462. configurable: true
  29463. });
  29464. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29465. get: function () {
  29466. return VertexBuffer._MatricesWeightsExtraKind;
  29467. },
  29468. enumerable: true,
  29469. configurable: true
  29470. });
  29471. /**
  29472. * Deduces the stride given a kind.
  29473. * @param kind The kind string to deduce
  29474. * @returns The deduced stride
  29475. */
  29476. VertexBuffer.DeduceStride = function (kind) {
  29477. switch (kind) {
  29478. case VertexBuffer.UVKind:
  29479. case VertexBuffer.UV2Kind:
  29480. case VertexBuffer.UV3Kind:
  29481. case VertexBuffer.UV4Kind:
  29482. case VertexBuffer.UV5Kind:
  29483. case VertexBuffer.UV6Kind:
  29484. return 2;
  29485. case VertexBuffer.NormalKind:
  29486. case VertexBuffer.PositionKind:
  29487. return 3;
  29488. case VertexBuffer.ColorKind:
  29489. case VertexBuffer.MatricesIndicesKind:
  29490. case VertexBuffer.MatricesIndicesExtraKind:
  29491. case VertexBuffer.MatricesWeightsKind:
  29492. case VertexBuffer.MatricesWeightsExtraKind:
  29493. case VertexBuffer.TangentKind:
  29494. return 4;
  29495. default:
  29496. throw new Error("Invalid kind '" + kind + "'");
  29497. }
  29498. };
  29499. /**
  29500. * Gets the byte length of the given type.
  29501. * @param type the type
  29502. * @returns the number of bytes
  29503. */
  29504. VertexBuffer.GetTypeByteLength = function (type) {
  29505. switch (type) {
  29506. case VertexBuffer.BYTE:
  29507. case VertexBuffer.UNSIGNED_BYTE:
  29508. return 1;
  29509. case VertexBuffer.SHORT:
  29510. case VertexBuffer.UNSIGNED_SHORT:
  29511. return 2;
  29512. case VertexBuffer.INT:
  29513. case VertexBuffer.FLOAT:
  29514. return 4;
  29515. default:
  29516. throw new Error("Invalid type '" + type + "'");
  29517. }
  29518. };
  29519. /**
  29520. * Enumerates each value of the given parameters as numbers.
  29521. * @param data the data to enumerate
  29522. * @param byteOffset the byte offset of the data
  29523. * @param byteStride the byte stride of the data
  29524. * @param componentCount the number of components per element
  29525. * @param componentType the type of the component
  29526. * @param count the total number of components
  29527. * @param normalized whether the data is normalized
  29528. * @param callback the callback function called for each value
  29529. */
  29530. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29531. if (data instanceof Array) {
  29532. var offset = byteOffset / 4;
  29533. var stride = byteStride / 4;
  29534. for (var index = 0; index < count; index += componentCount) {
  29535. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29536. callback(data[offset + componentIndex], index + componentIndex);
  29537. }
  29538. offset += stride;
  29539. }
  29540. }
  29541. else {
  29542. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29543. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29544. for (var index = 0; index < count; index += componentCount) {
  29545. var componentByteOffset = byteOffset;
  29546. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29547. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29548. callback(value, index + componentIndex);
  29549. componentByteOffset += componentByteLength;
  29550. }
  29551. byteOffset += byteStride;
  29552. }
  29553. }
  29554. };
  29555. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29556. switch (type) {
  29557. case VertexBuffer.BYTE: {
  29558. var value = dataView.getInt8(byteOffset);
  29559. if (normalized) {
  29560. value = (value + 0.5) / 127.5;
  29561. }
  29562. return value;
  29563. }
  29564. case VertexBuffer.UNSIGNED_BYTE: {
  29565. var value = dataView.getUint8(byteOffset);
  29566. if (normalized) {
  29567. value = value / 255;
  29568. }
  29569. return value;
  29570. }
  29571. case VertexBuffer.SHORT: {
  29572. var value = dataView.getInt16(byteOffset, true);
  29573. if (normalized) {
  29574. value = (value + 0.5) / 16383.5;
  29575. }
  29576. return value;
  29577. }
  29578. case VertexBuffer.UNSIGNED_SHORT: {
  29579. var value = dataView.getUint16(byteOffset, true);
  29580. if (normalized) {
  29581. value = value / 65535;
  29582. }
  29583. return value;
  29584. }
  29585. case VertexBuffer.FLOAT: {
  29586. return dataView.getFloat32(byteOffset, true);
  29587. }
  29588. default: {
  29589. throw new Error("Invalid component type " + type);
  29590. }
  29591. }
  29592. };
  29593. /**
  29594. * The byte type.
  29595. */
  29596. VertexBuffer.BYTE = 5120;
  29597. /**
  29598. * The unsigned byte type.
  29599. */
  29600. VertexBuffer.UNSIGNED_BYTE = 5121;
  29601. /**
  29602. * The short type.
  29603. */
  29604. VertexBuffer.SHORT = 5122;
  29605. /**
  29606. * The unsigned short type.
  29607. */
  29608. VertexBuffer.UNSIGNED_SHORT = 5123;
  29609. /**
  29610. * The integer type.
  29611. */
  29612. VertexBuffer.INT = 5124;
  29613. /**
  29614. * The unsigned integer type.
  29615. */
  29616. VertexBuffer.UNSIGNED_INT = 5125;
  29617. /**
  29618. * The float type.
  29619. */
  29620. VertexBuffer.FLOAT = 5126;
  29621. // Enums
  29622. VertexBuffer._PositionKind = "position";
  29623. VertexBuffer._NormalKind = "normal";
  29624. VertexBuffer._TangentKind = "tangent";
  29625. VertexBuffer._UVKind = "uv";
  29626. VertexBuffer._UV2Kind = "uv2";
  29627. VertexBuffer._UV3Kind = "uv3";
  29628. VertexBuffer._UV4Kind = "uv4";
  29629. VertexBuffer._UV5Kind = "uv5";
  29630. VertexBuffer._UV6Kind = "uv6";
  29631. VertexBuffer._ColorKind = "color";
  29632. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29633. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29634. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29635. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29636. return VertexBuffer;
  29637. }());
  29638. BABYLON.VertexBuffer = VertexBuffer;
  29639. })(BABYLON || (BABYLON = {}));
  29640. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29641. var BABYLON;
  29642. (function (BABYLON) {
  29643. /**
  29644. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29645. */
  29646. var DummyInternalTextureTracker = /** @class */ (function () {
  29647. function DummyInternalTextureTracker() {
  29648. /**
  29649. * Gets or set the previous tracker in the list
  29650. */
  29651. this.previous = null;
  29652. /**
  29653. * Gets or set the next tracker in the list
  29654. */
  29655. this.next = null;
  29656. }
  29657. return DummyInternalTextureTracker;
  29658. }());
  29659. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29660. })(BABYLON || (BABYLON = {}));
  29661. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29662. var BABYLON;
  29663. (function (BABYLON) {
  29664. /**
  29665. * Class used to store data associated with WebGL texture data for the engine
  29666. * This class should not be used directly
  29667. */
  29668. var InternalTexture = /** @class */ (function () {
  29669. /**
  29670. * Creates a new InternalTexture
  29671. * @param engine defines the engine to use
  29672. * @param dataSource defines the type of data that will be used
  29673. */
  29674. function InternalTexture(engine, dataSource) {
  29675. /**
  29676. * Observable called when the texture is loaded
  29677. */
  29678. this.onLoadedObservable = new BABYLON.Observable();
  29679. /**
  29680. * Gets or set the previous tracker in the list
  29681. */
  29682. this.previous = null;
  29683. /**
  29684. * Gets or set the next tracker in the list
  29685. */
  29686. this.next = null;
  29687. // Private
  29688. /** @hidden */
  29689. this._initialSlot = -1;
  29690. /** @hidden */
  29691. this._designatedSlot = -1;
  29692. /** @hidden */
  29693. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29694. /** @hidden */
  29695. this._comparisonFunction = 0;
  29696. /** @hidden */
  29697. this._references = 1;
  29698. this._engine = engine;
  29699. this._dataSource = dataSource;
  29700. this._webGLTexture = engine._createTexture();
  29701. }
  29702. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29703. /**
  29704. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29705. */
  29706. get: function () {
  29707. return this._dataSource;
  29708. },
  29709. enumerable: true,
  29710. configurable: true
  29711. });
  29712. /**
  29713. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29714. */
  29715. InternalTexture.prototype.incrementReferences = function () {
  29716. this._references++;
  29717. };
  29718. /**
  29719. * Change the size of the texture (not the size of the content)
  29720. * @param width defines the new width
  29721. * @param height defines the new height
  29722. * @param depth defines the new depth (1 by default)
  29723. */
  29724. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29725. if (depth === void 0) { depth = 1; }
  29726. this.width = width;
  29727. this.height = height;
  29728. this.depth = depth;
  29729. this.baseWidth = width;
  29730. this.baseHeight = height;
  29731. this.baseDepth = depth;
  29732. this._size = width * height * depth;
  29733. };
  29734. /** @hidden */
  29735. InternalTexture.prototype._rebuild = function () {
  29736. var _this = this;
  29737. var proxy;
  29738. this.isReady = false;
  29739. this._cachedCoordinatesMode = null;
  29740. this._cachedWrapU = null;
  29741. this._cachedWrapV = null;
  29742. this._cachedAnisotropicFilteringLevel = null;
  29743. switch (this._dataSource) {
  29744. case InternalTexture.DATASOURCE_TEMP:
  29745. return;
  29746. case InternalTexture.DATASOURCE_URL:
  29747. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29748. _this.isReady = true;
  29749. }, null, this._buffer, undefined, this.format);
  29750. proxy._swapAndDie(this);
  29751. return;
  29752. case InternalTexture.DATASOURCE_RAW:
  29753. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29754. proxy._swapAndDie(this);
  29755. this.isReady = true;
  29756. return;
  29757. case InternalTexture.DATASOURCE_RAW3D:
  29758. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29759. proxy._swapAndDie(this);
  29760. this.isReady = true;
  29761. return;
  29762. case InternalTexture.DATASOURCE_DYNAMIC:
  29763. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29764. proxy._swapAndDie(this);
  29765. // The engine will make sure to update content so no need to flag it as isReady = true
  29766. return;
  29767. case InternalTexture.DATASOURCE_RENDERTARGET:
  29768. var options = new BABYLON.RenderTargetCreationOptions();
  29769. options.generateDepthBuffer = this._generateDepthBuffer;
  29770. options.generateMipMaps = this.generateMipMaps;
  29771. options.generateStencilBuffer = this._generateStencilBuffer;
  29772. options.samplingMode = this.samplingMode;
  29773. options.type = this.type;
  29774. if (this.isCube) {
  29775. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29776. }
  29777. else {
  29778. var size = {
  29779. width: this.width,
  29780. height: this.height
  29781. };
  29782. proxy = this._engine.createRenderTargetTexture(size, options);
  29783. }
  29784. proxy._swapAndDie(this);
  29785. this.isReady = true;
  29786. return;
  29787. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29788. var depthTextureOptions = {
  29789. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29790. comparisonFunction: this._comparisonFunction,
  29791. generateStencil: this._generateStencilBuffer,
  29792. isCube: this.isCube
  29793. };
  29794. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29795. proxy._swapAndDie(this);
  29796. this.isReady = true;
  29797. return;
  29798. case InternalTexture.DATASOURCE_CUBE:
  29799. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29800. _this.isReady = true;
  29801. }, null, this.format, this._extension);
  29802. proxy._swapAndDie(this);
  29803. return;
  29804. case InternalTexture.DATASOURCE_CUBERAW:
  29805. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29806. proxy._swapAndDie(this);
  29807. this.isReady = true;
  29808. return;
  29809. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29810. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29811. if (proxy) {
  29812. proxy._swapAndDie(_this);
  29813. }
  29814. _this.isReady = true;
  29815. }, null, this.format, this._extension);
  29816. return;
  29817. }
  29818. };
  29819. InternalTexture.prototype._swapAndDie = function (target) {
  29820. target._webGLTexture = this._webGLTexture;
  29821. if (this._framebuffer) {
  29822. target._framebuffer = this._framebuffer;
  29823. }
  29824. if (this._depthStencilBuffer) {
  29825. target._depthStencilBuffer = this._depthStencilBuffer;
  29826. }
  29827. if (this._lodTextureHigh) {
  29828. if (target._lodTextureHigh) {
  29829. target._lodTextureHigh.dispose();
  29830. }
  29831. target._lodTextureHigh = this._lodTextureHigh;
  29832. }
  29833. if (this._lodTextureMid) {
  29834. if (target._lodTextureMid) {
  29835. target._lodTextureMid.dispose();
  29836. }
  29837. target._lodTextureMid = this._lodTextureMid;
  29838. }
  29839. if (this._lodTextureLow) {
  29840. if (target._lodTextureLow) {
  29841. target._lodTextureLow.dispose();
  29842. }
  29843. target._lodTextureLow = this._lodTextureLow;
  29844. }
  29845. var cache = this._engine.getLoadedTexturesCache();
  29846. var index = cache.indexOf(this);
  29847. if (index !== -1) {
  29848. cache.splice(index, 1);
  29849. }
  29850. };
  29851. /**
  29852. * Dispose the current allocated resources
  29853. */
  29854. InternalTexture.prototype.dispose = function () {
  29855. if (!this._webGLTexture) {
  29856. return;
  29857. }
  29858. this._references--;
  29859. if (this._references === 0) {
  29860. this._engine._releaseTexture(this);
  29861. this._webGLTexture = null;
  29862. this.previous = null;
  29863. this.next = null;
  29864. }
  29865. };
  29866. /**
  29867. * The source of the texture data is unknown
  29868. */
  29869. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29870. /**
  29871. * Texture data comes from an URL
  29872. */
  29873. InternalTexture.DATASOURCE_URL = 1;
  29874. /**
  29875. * Texture data is only used for temporary storage
  29876. */
  29877. InternalTexture.DATASOURCE_TEMP = 2;
  29878. /**
  29879. * Texture data comes from raw data (ArrayBuffer)
  29880. */
  29881. InternalTexture.DATASOURCE_RAW = 3;
  29882. /**
  29883. * Texture content is dynamic (video or dynamic texture)
  29884. */
  29885. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29886. /**
  29887. * Texture content is generated by rendering to it
  29888. */
  29889. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29890. /**
  29891. * Texture content is part of a multi render target process
  29892. */
  29893. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29894. /**
  29895. * Texture data comes from a cube data file
  29896. */
  29897. InternalTexture.DATASOURCE_CUBE = 7;
  29898. /**
  29899. * Texture data comes from a raw cube data
  29900. */
  29901. InternalTexture.DATASOURCE_CUBERAW = 8;
  29902. /**
  29903. * Texture data come from a prefiltered cube data file
  29904. */
  29905. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29906. /**
  29907. * Texture content is raw 3D data
  29908. */
  29909. InternalTexture.DATASOURCE_RAW3D = 10;
  29910. /**
  29911. * Texture content is a depth texture
  29912. */
  29913. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29914. return InternalTexture;
  29915. }());
  29916. BABYLON.InternalTexture = InternalTexture;
  29917. })(BABYLON || (BABYLON = {}));
  29918. //# sourceMappingURL=babylon.internalTexture.js.map
  29919. var BABYLON;
  29920. (function (BABYLON) {
  29921. var BaseTexture = /** @class */ (function () {
  29922. function BaseTexture(scene) {
  29923. this._hasAlpha = false;
  29924. this.getAlphaFromRGB = false;
  29925. this.level = 1;
  29926. this.coordinatesIndex = 0;
  29927. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29928. /**
  29929. * | Value | Type | Description |
  29930. * | ----- | ------------------ | ----------- |
  29931. * | 0 | CLAMP_ADDRESSMODE | |
  29932. * | 1 | WRAP_ADDRESSMODE | |
  29933. * | 2 | MIRROR_ADDRESSMODE | |
  29934. */
  29935. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29936. /**
  29937. * | Value | Type | Description |
  29938. * | ----- | ------------------ | ----------- |
  29939. * | 0 | CLAMP_ADDRESSMODE | |
  29940. * | 1 | WRAP_ADDRESSMODE | |
  29941. * | 2 | MIRROR_ADDRESSMODE | |
  29942. */
  29943. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29944. /**
  29945. * | Value | Type | Description |
  29946. * | ----- | ------------------ | ----------- |
  29947. * | 0 | CLAMP_ADDRESSMODE | |
  29948. * | 1 | WRAP_ADDRESSMODE | |
  29949. * | 2 | MIRROR_ADDRESSMODE | |
  29950. */
  29951. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29952. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29953. this.isCube = false;
  29954. this.is3D = false;
  29955. this.gammaSpace = true;
  29956. this.invertZ = false;
  29957. this.lodLevelInAlpha = false;
  29958. this.lodGenerationOffset = 0.0;
  29959. this.lodGenerationScale = 0.8;
  29960. this.isRenderTarget = false;
  29961. this.animations = new Array();
  29962. /**
  29963. * An event triggered when the texture is disposed.
  29964. */
  29965. this.onDisposeObservable = new BABYLON.Observable();
  29966. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29967. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29968. if (this._scene) {
  29969. this._scene.textures.push(this);
  29970. }
  29971. this._uid = null;
  29972. }
  29973. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29974. get: function () {
  29975. return this._hasAlpha;
  29976. },
  29977. set: function (value) {
  29978. if (this._hasAlpha === value) {
  29979. return;
  29980. }
  29981. this._hasAlpha = value;
  29982. if (this._scene) {
  29983. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29984. }
  29985. },
  29986. enumerable: true,
  29987. configurable: true
  29988. });
  29989. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29990. get: function () {
  29991. return this._coordinatesMode;
  29992. },
  29993. /**
  29994. * How a texture is mapped.
  29995. *
  29996. * | Value | Type | Description |
  29997. * | ----- | ----------------------------------- | ----------- |
  29998. * | 0 | EXPLICIT_MODE | |
  29999. * | 1 | SPHERICAL_MODE | |
  30000. * | 2 | PLANAR_MODE | |
  30001. * | 3 | CUBIC_MODE | |
  30002. * | 4 | PROJECTION_MODE | |
  30003. * | 5 | SKYBOX_MODE | |
  30004. * | 6 | INVCUBIC_MODE | |
  30005. * | 7 | EQUIRECTANGULAR_MODE | |
  30006. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30007. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30008. */
  30009. set: function (value) {
  30010. if (this._coordinatesMode === value) {
  30011. return;
  30012. }
  30013. this._coordinatesMode = value;
  30014. if (this._scene) {
  30015. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30016. }
  30017. },
  30018. enumerable: true,
  30019. configurable: true
  30020. });
  30021. Object.defineProperty(BaseTexture.prototype, "uid", {
  30022. get: function () {
  30023. if (!this._uid) {
  30024. this._uid = BABYLON.Tools.RandomId();
  30025. }
  30026. return this._uid;
  30027. },
  30028. enumerable: true,
  30029. configurable: true
  30030. });
  30031. BaseTexture.prototype.toString = function () {
  30032. return this.name;
  30033. };
  30034. BaseTexture.prototype.getClassName = function () {
  30035. return "BaseTexture";
  30036. };
  30037. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30038. set: function (callback) {
  30039. if (this._onDisposeObserver) {
  30040. this.onDisposeObservable.remove(this._onDisposeObserver);
  30041. }
  30042. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30043. },
  30044. enumerable: true,
  30045. configurable: true
  30046. });
  30047. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30048. get: function () {
  30049. return true;
  30050. },
  30051. enumerable: true,
  30052. configurable: true
  30053. });
  30054. BaseTexture.prototype.getScene = function () {
  30055. return this._scene;
  30056. };
  30057. BaseTexture.prototype.getTextureMatrix = function () {
  30058. return BABYLON.Matrix.IdentityReadOnly;
  30059. };
  30060. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30061. return BABYLON.Matrix.IdentityReadOnly;
  30062. };
  30063. BaseTexture.prototype.getInternalTexture = function () {
  30064. return this._texture;
  30065. };
  30066. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30067. return !this.isBlocking || this.isReady();
  30068. };
  30069. BaseTexture.prototype.isReady = function () {
  30070. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30071. this.delayLoad();
  30072. return false;
  30073. }
  30074. if (this._texture) {
  30075. return this._texture.isReady;
  30076. }
  30077. return false;
  30078. };
  30079. BaseTexture.prototype.getSize = function () {
  30080. if (this._texture && this._texture.width) {
  30081. return new BABYLON.Size(this._texture.width, this._texture.height);
  30082. }
  30083. if (this._texture && this._texture._size) {
  30084. return new BABYLON.Size(this._texture._size, this._texture._size);
  30085. }
  30086. return BABYLON.Size.Zero();
  30087. };
  30088. BaseTexture.prototype.getBaseSize = function () {
  30089. if (!this.isReady() || !this._texture)
  30090. return BABYLON.Size.Zero();
  30091. if (this._texture._size) {
  30092. return new BABYLON.Size(this._texture._size, this._texture._size);
  30093. }
  30094. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30095. };
  30096. BaseTexture.prototype.scale = function (ratio) {
  30097. };
  30098. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30099. get: function () {
  30100. return false;
  30101. },
  30102. enumerable: true,
  30103. configurable: true
  30104. });
  30105. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30106. if (!this._scene) {
  30107. return null;
  30108. }
  30109. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30110. for (var index = 0; index < texturesCache.length; index++) {
  30111. var texturesCacheEntry = texturesCache[index];
  30112. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30113. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30114. texturesCacheEntry.incrementReferences();
  30115. return texturesCacheEntry;
  30116. }
  30117. }
  30118. }
  30119. return null;
  30120. };
  30121. BaseTexture.prototype._rebuild = function () {
  30122. };
  30123. BaseTexture.prototype.delayLoad = function () {
  30124. };
  30125. BaseTexture.prototype.clone = function () {
  30126. return null;
  30127. };
  30128. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30129. get: function () {
  30130. if (!this._texture) {
  30131. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30132. }
  30133. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30134. },
  30135. enumerable: true,
  30136. configurable: true
  30137. });
  30138. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30139. get: function () {
  30140. if (!this._texture) {
  30141. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30142. }
  30143. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30144. },
  30145. enumerable: true,
  30146. configurable: true
  30147. });
  30148. BaseTexture.prototype.readPixels = function (faceIndex) {
  30149. if (faceIndex === void 0) { faceIndex = 0; }
  30150. if (!this._texture) {
  30151. return null;
  30152. }
  30153. var size = this.getSize();
  30154. var scene = this.getScene();
  30155. if (!scene) {
  30156. return null;
  30157. }
  30158. var engine = scene.getEngine();
  30159. if (this._texture.isCube) {
  30160. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30161. }
  30162. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30163. };
  30164. BaseTexture.prototype.releaseInternalTexture = function () {
  30165. if (this._texture) {
  30166. this._texture.dispose();
  30167. this._texture = null;
  30168. }
  30169. };
  30170. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30171. get: function () {
  30172. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30173. return null;
  30174. }
  30175. if (!this._texture._sphericalPolynomial) {
  30176. this._texture._sphericalPolynomial =
  30177. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30178. }
  30179. return this._texture._sphericalPolynomial;
  30180. },
  30181. set: function (value) {
  30182. if (this._texture) {
  30183. this._texture._sphericalPolynomial = value;
  30184. }
  30185. },
  30186. enumerable: true,
  30187. configurable: true
  30188. });
  30189. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30190. get: function () {
  30191. if (this._texture) {
  30192. return this._texture._lodTextureHigh;
  30193. }
  30194. return null;
  30195. },
  30196. enumerable: true,
  30197. configurable: true
  30198. });
  30199. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30200. get: function () {
  30201. if (this._texture) {
  30202. return this._texture._lodTextureMid;
  30203. }
  30204. return null;
  30205. },
  30206. enumerable: true,
  30207. configurable: true
  30208. });
  30209. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30210. get: function () {
  30211. if (this._texture) {
  30212. return this._texture._lodTextureLow;
  30213. }
  30214. return null;
  30215. },
  30216. enumerable: true,
  30217. configurable: true
  30218. });
  30219. BaseTexture.prototype.dispose = function () {
  30220. if (!this._scene) {
  30221. return;
  30222. }
  30223. // Animations
  30224. this._scene.stopAnimation(this);
  30225. // Remove from scene
  30226. this._scene._removePendingData(this);
  30227. var index = this._scene.textures.indexOf(this);
  30228. if (index >= 0) {
  30229. this._scene.textures.splice(index, 1);
  30230. }
  30231. if (this._texture === undefined) {
  30232. return;
  30233. }
  30234. // Release
  30235. this.releaseInternalTexture();
  30236. // Callback
  30237. this.onDisposeObservable.notifyObservers(this);
  30238. this.onDisposeObservable.clear();
  30239. };
  30240. BaseTexture.prototype.serialize = function () {
  30241. if (!this.name) {
  30242. return null;
  30243. }
  30244. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30245. // Animations
  30246. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30247. return serializationObject;
  30248. };
  30249. BaseTexture.WhenAllReady = function (textures, callback) {
  30250. var numRemaining = textures.length;
  30251. if (numRemaining === 0) {
  30252. callback();
  30253. return;
  30254. }
  30255. var _loop_1 = function () {
  30256. texture = textures[i];
  30257. if (texture.isReady()) {
  30258. if (--numRemaining === 0) {
  30259. callback();
  30260. }
  30261. }
  30262. else {
  30263. onLoadObservable = texture.onLoadObservable;
  30264. var onLoadCallback_1 = function () {
  30265. onLoadObservable.removeCallback(onLoadCallback_1);
  30266. if (--numRemaining === 0) {
  30267. callback();
  30268. }
  30269. };
  30270. onLoadObservable.add(onLoadCallback_1);
  30271. }
  30272. };
  30273. var texture, onLoadObservable;
  30274. for (var i = 0; i < textures.length; i++) {
  30275. _loop_1();
  30276. }
  30277. };
  30278. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30279. __decorate([
  30280. BABYLON.serialize()
  30281. ], BaseTexture.prototype, "name", void 0);
  30282. __decorate([
  30283. BABYLON.serialize("hasAlpha")
  30284. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30285. __decorate([
  30286. BABYLON.serialize()
  30287. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30288. __decorate([
  30289. BABYLON.serialize()
  30290. ], BaseTexture.prototype, "level", void 0);
  30291. __decorate([
  30292. BABYLON.serialize()
  30293. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30294. __decorate([
  30295. BABYLON.serialize("coordinatesMode")
  30296. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30297. __decorate([
  30298. BABYLON.serialize()
  30299. ], BaseTexture.prototype, "wrapU", void 0);
  30300. __decorate([
  30301. BABYLON.serialize()
  30302. ], BaseTexture.prototype, "wrapV", void 0);
  30303. __decorate([
  30304. BABYLON.serialize()
  30305. ], BaseTexture.prototype, "wrapR", void 0);
  30306. __decorate([
  30307. BABYLON.serialize()
  30308. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30309. __decorate([
  30310. BABYLON.serialize()
  30311. ], BaseTexture.prototype, "isCube", void 0);
  30312. __decorate([
  30313. BABYLON.serialize()
  30314. ], BaseTexture.prototype, "is3D", void 0);
  30315. __decorate([
  30316. BABYLON.serialize()
  30317. ], BaseTexture.prototype, "gammaSpace", void 0);
  30318. __decorate([
  30319. BABYLON.serialize()
  30320. ], BaseTexture.prototype, "invertZ", void 0);
  30321. __decorate([
  30322. BABYLON.serialize()
  30323. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30324. __decorate([
  30325. BABYLON.serialize()
  30326. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30327. __decorate([
  30328. BABYLON.serialize()
  30329. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30330. __decorate([
  30331. BABYLON.serialize()
  30332. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30333. return BaseTexture;
  30334. }());
  30335. BABYLON.BaseTexture = BaseTexture;
  30336. })(BABYLON || (BABYLON = {}));
  30337. //# sourceMappingURL=babylon.baseTexture.js.map
  30338. var BABYLON;
  30339. (function (BABYLON) {
  30340. var Texture = /** @class */ (function (_super) {
  30341. __extends(Texture, _super);
  30342. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30343. if (noMipmap === void 0) { noMipmap = false; }
  30344. if (invertY === void 0) { invertY = true; }
  30345. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30346. if (onLoad === void 0) { onLoad = null; }
  30347. if (onError === void 0) { onError = null; }
  30348. if (buffer === void 0) { buffer = null; }
  30349. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30350. var _this = _super.call(this, scene) || this;
  30351. _this.uOffset = 0;
  30352. _this.vOffset = 0;
  30353. _this.uScale = 1.0;
  30354. _this.vScale = 1.0;
  30355. _this.uAng = 0;
  30356. _this.vAng = 0;
  30357. _this.wAng = 0;
  30358. _this._isBlocking = true;
  30359. _this.name = url || "";
  30360. _this.url = url;
  30361. _this._noMipmap = noMipmap;
  30362. _this._invertY = invertY;
  30363. _this._samplingMode = samplingMode;
  30364. _this._buffer = buffer;
  30365. _this._deleteBuffer = deleteBuffer;
  30366. if (format) {
  30367. _this._format = format;
  30368. }
  30369. scene = _this.getScene();
  30370. if (!scene) {
  30371. return _this;
  30372. }
  30373. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30374. var load = function () {
  30375. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30376. _this.onLoadObservable.notifyObservers(_this);
  30377. }
  30378. if (onLoad) {
  30379. onLoad();
  30380. }
  30381. if (!_this.isBlocking && scene) {
  30382. scene.resetCachedMaterial();
  30383. }
  30384. };
  30385. if (!_this.url) {
  30386. _this._delayedOnLoad = load;
  30387. _this._delayedOnError = onError;
  30388. return _this;
  30389. }
  30390. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30391. if (!_this._texture) {
  30392. if (!scene.useDelayedTextureLoading) {
  30393. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30394. if (deleteBuffer) {
  30395. delete _this._buffer;
  30396. }
  30397. }
  30398. else {
  30399. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30400. _this._delayedOnLoad = load;
  30401. _this._delayedOnError = onError;
  30402. }
  30403. }
  30404. else {
  30405. if (_this._texture.isReady) {
  30406. BABYLON.Tools.SetImmediate(function () { return load(); });
  30407. }
  30408. else {
  30409. _this._texture.onLoadedObservable.add(load);
  30410. }
  30411. }
  30412. return _this;
  30413. }
  30414. Object.defineProperty(Texture.prototype, "noMipmap", {
  30415. get: function () {
  30416. return this._noMipmap;
  30417. },
  30418. enumerable: true,
  30419. configurable: true
  30420. });
  30421. Object.defineProperty(Texture.prototype, "isBlocking", {
  30422. get: function () {
  30423. return this._isBlocking;
  30424. },
  30425. set: function (value) {
  30426. this._isBlocking = value;
  30427. },
  30428. enumerable: true,
  30429. configurable: true
  30430. });
  30431. Object.defineProperty(Texture.prototype, "samplingMode", {
  30432. get: function () {
  30433. return this._samplingMode;
  30434. },
  30435. enumerable: true,
  30436. configurable: true
  30437. });
  30438. Texture.prototype.updateURL = function (url) {
  30439. this.url = url;
  30440. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30441. this.delayLoad();
  30442. };
  30443. Texture.prototype.delayLoad = function () {
  30444. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30445. return;
  30446. }
  30447. var scene = this.getScene();
  30448. if (!scene) {
  30449. return;
  30450. }
  30451. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30452. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30453. if (!this._texture) {
  30454. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30455. if (this._deleteBuffer) {
  30456. delete this._buffer;
  30457. }
  30458. }
  30459. else {
  30460. if (this._delayedOnLoad) {
  30461. if (this._texture.isReady) {
  30462. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30463. }
  30464. else {
  30465. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30466. }
  30467. }
  30468. }
  30469. this._delayedOnLoad = null;
  30470. this._delayedOnError = null;
  30471. };
  30472. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30473. if (!this._texture) {
  30474. return;
  30475. }
  30476. var scene = this.getScene();
  30477. if (!scene) {
  30478. return;
  30479. }
  30480. this._samplingMode = samplingMode;
  30481. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30482. };
  30483. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30484. x *= this.uScale;
  30485. y *= this.vScale;
  30486. x -= 0.5 * this.uScale;
  30487. y -= 0.5 * this.vScale;
  30488. z -= 0.5;
  30489. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30490. t.x += 0.5 * this.uScale + this.uOffset;
  30491. t.y += 0.5 * this.vScale + this.vOffset;
  30492. t.z += 0.5;
  30493. };
  30494. Texture.prototype.getTextureMatrix = function () {
  30495. var _this = this;
  30496. if (this.uOffset === this._cachedUOffset &&
  30497. this.vOffset === this._cachedVOffset &&
  30498. this.uScale === this._cachedUScale &&
  30499. this.vScale === this._cachedVScale &&
  30500. this.uAng === this._cachedUAng &&
  30501. this.vAng === this._cachedVAng &&
  30502. this.wAng === this._cachedWAng) {
  30503. return this._cachedTextureMatrix;
  30504. }
  30505. this._cachedUOffset = this.uOffset;
  30506. this._cachedVOffset = this.vOffset;
  30507. this._cachedUScale = this.uScale;
  30508. this._cachedVScale = this.vScale;
  30509. this._cachedUAng = this.uAng;
  30510. this._cachedVAng = this.vAng;
  30511. this._cachedWAng = this.wAng;
  30512. if (!this._cachedTextureMatrix) {
  30513. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30514. this._rowGenerationMatrix = new BABYLON.Matrix();
  30515. this._t0 = BABYLON.Vector3.Zero();
  30516. this._t1 = BABYLON.Vector3.Zero();
  30517. this._t2 = BABYLON.Vector3.Zero();
  30518. }
  30519. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30520. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30521. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30522. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30523. this._t1.subtractInPlace(this._t0);
  30524. this._t2.subtractInPlace(this._t0);
  30525. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30526. this._cachedTextureMatrix.m[0] = this._t1.x;
  30527. this._cachedTextureMatrix.m[1] = this._t1.y;
  30528. this._cachedTextureMatrix.m[2] = this._t1.z;
  30529. this._cachedTextureMatrix.m[4] = this._t2.x;
  30530. this._cachedTextureMatrix.m[5] = this._t2.y;
  30531. this._cachedTextureMatrix.m[6] = this._t2.z;
  30532. this._cachedTextureMatrix.m[8] = this._t0.x;
  30533. this._cachedTextureMatrix.m[9] = this._t0.y;
  30534. this._cachedTextureMatrix.m[10] = this._t0.z;
  30535. var scene = this.getScene();
  30536. if (!scene) {
  30537. return this._cachedTextureMatrix;
  30538. }
  30539. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30540. return mat.hasTexture(_this);
  30541. });
  30542. return this._cachedTextureMatrix;
  30543. };
  30544. Texture.prototype.getReflectionTextureMatrix = function () {
  30545. var _this = this;
  30546. var scene = this.getScene();
  30547. if (!scene) {
  30548. return this._cachedTextureMatrix;
  30549. }
  30550. if (this.uOffset === this._cachedUOffset &&
  30551. this.vOffset === this._cachedVOffset &&
  30552. this.uScale === this._cachedUScale &&
  30553. this.vScale === this._cachedVScale &&
  30554. this.coordinatesMode === this._cachedCoordinatesMode) {
  30555. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30556. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30557. return this._cachedTextureMatrix;
  30558. }
  30559. }
  30560. else {
  30561. return this._cachedTextureMatrix;
  30562. }
  30563. }
  30564. if (!this._cachedTextureMatrix) {
  30565. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30566. }
  30567. if (!this._projectionModeMatrix) {
  30568. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30569. }
  30570. this._cachedUOffset = this.uOffset;
  30571. this._cachedVOffset = this.vOffset;
  30572. this._cachedUScale = this.uScale;
  30573. this._cachedVScale = this.vScale;
  30574. this._cachedCoordinatesMode = this.coordinatesMode;
  30575. switch (this.coordinatesMode) {
  30576. case Texture.PLANAR_MODE:
  30577. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30578. this._cachedTextureMatrix[0] = this.uScale;
  30579. this._cachedTextureMatrix[5] = this.vScale;
  30580. this._cachedTextureMatrix[12] = this.uOffset;
  30581. this._cachedTextureMatrix[13] = this.vOffset;
  30582. break;
  30583. case Texture.PROJECTION_MODE:
  30584. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30585. this._projectionModeMatrix.m[0] = 0.5;
  30586. this._projectionModeMatrix.m[5] = -0.5;
  30587. this._projectionModeMatrix.m[10] = 0.0;
  30588. this._projectionModeMatrix.m[12] = 0.5;
  30589. this._projectionModeMatrix.m[13] = 0.5;
  30590. this._projectionModeMatrix.m[14] = 1.0;
  30591. this._projectionModeMatrix.m[15] = 1.0;
  30592. var projectionMatrix = scene.getProjectionMatrix();
  30593. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30594. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30595. break;
  30596. default:
  30597. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30598. break;
  30599. }
  30600. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30601. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30602. });
  30603. return this._cachedTextureMatrix;
  30604. };
  30605. Texture.prototype.clone = function () {
  30606. var _this = this;
  30607. return BABYLON.SerializationHelper.Clone(function () {
  30608. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30609. }, this);
  30610. };
  30611. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30612. get: function () {
  30613. if (!this._onLoadObservable) {
  30614. this._onLoadObservable = new BABYLON.Observable();
  30615. }
  30616. return this._onLoadObservable;
  30617. },
  30618. enumerable: true,
  30619. configurable: true
  30620. });
  30621. Texture.prototype.serialize = function () {
  30622. var serializationObject = _super.prototype.serialize.call(this);
  30623. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30624. serializationObject.base64String = this._buffer;
  30625. serializationObject.name = serializationObject.name.replace("data:", "");
  30626. }
  30627. serializationObject.invertY = this._invertY;
  30628. serializationObject.samplingMode = this.samplingMode;
  30629. return serializationObject;
  30630. };
  30631. Texture.prototype.getClassName = function () {
  30632. return "Texture";
  30633. };
  30634. Texture.prototype.dispose = function () {
  30635. _super.prototype.dispose.call(this);
  30636. if (this.onLoadObservable) {
  30637. this.onLoadObservable.clear();
  30638. this._onLoadObservable = null;
  30639. }
  30640. this._delayedOnLoad = null;
  30641. this._delayedOnError = null;
  30642. };
  30643. // Statics
  30644. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30645. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30646. if (onLoad === void 0) { onLoad = null; }
  30647. if (onError === void 0) { onError = null; }
  30648. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30649. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30650. };
  30651. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30652. if (parsedTexture.customType) {
  30653. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30654. // Update Sampling Mode
  30655. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30656. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30657. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30658. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30659. }
  30660. }
  30661. return parsedCustomTexture;
  30662. }
  30663. if (parsedTexture.isCube) {
  30664. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30665. }
  30666. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30667. return null;
  30668. }
  30669. var texture = BABYLON.SerializationHelper.Parse(function () {
  30670. var generateMipMaps = true;
  30671. if (parsedTexture.noMipmap) {
  30672. generateMipMaps = false;
  30673. }
  30674. if (parsedTexture.mirrorPlane) {
  30675. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30676. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30677. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30678. return mirrorTexture;
  30679. }
  30680. else if (parsedTexture.isRenderTarget) {
  30681. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30682. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30683. return renderTargetTexture;
  30684. }
  30685. else {
  30686. var texture;
  30687. if (parsedTexture.base64String) {
  30688. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30689. }
  30690. else {
  30691. var url = rootUrl + parsedTexture.name;
  30692. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30693. url = parsedTexture.url;
  30694. }
  30695. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30696. }
  30697. return texture;
  30698. }
  30699. }, parsedTexture, scene);
  30700. // Update Sampling Mode
  30701. if (parsedTexture.samplingMode) {
  30702. var sampling = parsedTexture.samplingMode;
  30703. if (texture._samplingMode !== sampling) {
  30704. texture.updateSamplingMode(sampling);
  30705. }
  30706. }
  30707. // Animations
  30708. if (parsedTexture.animations) {
  30709. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30710. var parsedAnimation = parsedTexture.animations[animationIndex];
  30711. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30712. }
  30713. }
  30714. return texture;
  30715. };
  30716. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30717. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30718. if (noMipmap === void 0) { noMipmap = false; }
  30719. if (invertY === void 0) { invertY = true; }
  30720. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30721. if (onLoad === void 0) { onLoad = null; }
  30722. if (onError === void 0) { onError = null; }
  30723. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30724. if (name.substr(0, 5) !== "data:") {
  30725. name = "data:" + name;
  30726. }
  30727. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30728. };
  30729. // Constants
  30730. Texture.NEAREST_SAMPLINGMODE = 1;
  30731. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30732. Texture.BILINEAR_SAMPLINGMODE = 2;
  30733. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30734. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30735. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30736. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30737. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30738. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30739. Texture.NEAREST_LINEAR = 7;
  30740. Texture.NEAREST_NEAREST = 8;
  30741. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30742. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30743. Texture.LINEAR_LINEAR = 11;
  30744. Texture.LINEAR_NEAREST = 12;
  30745. Texture.EXPLICIT_MODE = 0;
  30746. Texture.SPHERICAL_MODE = 1;
  30747. Texture.PLANAR_MODE = 2;
  30748. Texture.CUBIC_MODE = 3;
  30749. Texture.PROJECTION_MODE = 4;
  30750. Texture.SKYBOX_MODE = 5;
  30751. Texture.INVCUBIC_MODE = 6;
  30752. Texture.EQUIRECTANGULAR_MODE = 7;
  30753. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30754. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30755. Texture.CLAMP_ADDRESSMODE = 0;
  30756. Texture.WRAP_ADDRESSMODE = 1;
  30757. Texture.MIRROR_ADDRESSMODE = 2;
  30758. /**
  30759. * 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
  30760. */
  30761. Texture.UseSerializedUrlIfAny = false;
  30762. __decorate([
  30763. BABYLON.serialize()
  30764. ], Texture.prototype, "url", void 0);
  30765. __decorate([
  30766. BABYLON.serialize()
  30767. ], Texture.prototype, "uOffset", void 0);
  30768. __decorate([
  30769. BABYLON.serialize()
  30770. ], Texture.prototype, "vOffset", void 0);
  30771. __decorate([
  30772. BABYLON.serialize()
  30773. ], Texture.prototype, "uScale", void 0);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], Texture.prototype, "vScale", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], Texture.prototype, "uAng", void 0);
  30780. __decorate([
  30781. BABYLON.serialize()
  30782. ], Texture.prototype, "vAng", void 0);
  30783. __decorate([
  30784. BABYLON.serialize()
  30785. ], Texture.prototype, "wAng", void 0);
  30786. __decorate([
  30787. BABYLON.serialize()
  30788. ], Texture.prototype, "isBlocking", null);
  30789. return Texture;
  30790. }(BABYLON.BaseTexture));
  30791. BABYLON.Texture = Texture;
  30792. })(BABYLON || (BABYLON = {}));
  30793. //# sourceMappingURL=babylon.texture.js.map
  30794. var BABYLON;
  30795. (function (BABYLON) {
  30796. /**
  30797. * @hidden
  30798. **/
  30799. var _InstancesBatch = /** @class */ (function () {
  30800. function _InstancesBatch() {
  30801. this.mustReturn = false;
  30802. this.visibleInstances = new Array();
  30803. this.renderSelf = new Array();
  30804. }
  30805. return _InstancesBatch;
  30806. }());
  30807. BABYLON._InstancesBatch = _InstancesBatch;
  30808. var Mesh = /** @class */ (function (_super) {
  30809. __extends(Mesh, _super);
  30810. /**
  30811. * @constructor
  30812. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30813. * @param {Scene} scene The scene to add this mesh to.
  30814. * @param {Node} parent The parent of this mesh, if it has one
  30815. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30816. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30817. * When false, achieved by calling a clone(), also passing False.
  30818. * This will make creation of children, recursive.
  30819. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30820. */
  30821. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30822. if (scene === void 0) { scene = null; }
  30823. if (parent === void 0) { parent = null; }
  30824. if (source === void 0) { source = null; }
  30825. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30826. var _this = _super.call(this, name, scene) || this;
  30827. // Events
  30828. /**
  30829. * An event triggered before rendering the mesh
  30830. */
  30831. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30832. /**
  30833. * An event triggered after rendering the mesh
  30834. */
  30835. _this.onAfterRenderObservable = new BABYLON.Observable();
  30836. /**
  30837. * An event triggered before drawing the mesh
  30838. */
  30839. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30840. // Members
  30841. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30842. _this.instances = new Array();
  30843. _this._LODLevels = new Array();
  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. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30850. _this.overrideMaterialSideOrientation = null;
  30851. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30852. // Will be used to save a source mesh reference, If any
  30853. _this._source = null;
  30854. scene = _this.getScene();
  30855. if (source) {
  30856. // Source mesh
  30857. _this._source = source;
  30858. // Geometry
  30859. if (source._geometry) {
  30860. source._geometry.applyToMesh(_this);
  30861. }
  30862. // Deep copy
  30863. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30864. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30865. // Metadata
  30866. if (source.metadata && source.metadata.clone) {
  30867. _this.metadata = source.metadata.clone();
  30868. }
  30869. else {
  30870. _this.metadata = source.metadata;
  30871. }
  30872. // Tags
  30873. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30874. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30875. }
  30876. // Parent
  30877. _this.parent = source.parent;
  30878. // Pivot
  30879. _this.setPivotMatrix(source.getPivotMatrix());
  30880. _this.id = name + "." + source.id;
  30881. // Material
  30882. _this.material = source.material;
  30883. var index;
  30884. if (!doNotCloneChildren) {
  30885. // Children
  30886. var directDescendants = source.getDescendants(true);
  30887. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30888. var child = directDescendants[index_1];
  30889. if (child.clone) {
  30890. child.clone(name + "." + child.name, _this);
  30891. }
  30892. }
  30893. }
  30894. // Physics clone
  30895. var physicsEngine = _this.getScene().getPhysicsEngine();
  30896. if (clonePhysicsImpostor && physicsEngine) {
  30897. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30898. if (impostor) {
  30899. _this.physicsImpostor = impostor.clone(_this);
  30900. }
  30901. }
  30902. // Particles
  30903. for (index = 0; index < scene.particleSystems.length; index++) {
  30904. var system = scene.particleSystems[index];
  30905. if (system.emitter === source) {
  30906. system.clone(system.name, _this);
  30907. }
  30908. }
  30909. _this.computeWorldMatrix(true);
  30910. }
  30911. // Parent
  30912. if (parent !== null) {
  30913. _this.parent = parent;
  30914. }
  30915. return _this;
  30916. }
  30917. Object.defineProperty(Mesh, "FRONTSIDE", {
  30918. /**
  30919. * Mesh side orientation : usually the external or front surface
  30920. */
  30921. get: function () {
  30922. return Mesh._FRONTSIDE;
  30923. },
  30924. enumerable: true,
  30925. configurable: true
  30926. });
  30927. Object.defineProperty(Mesh, "BACKSIDE", {
  30928. /**
  30929. * Mesh side orientation : usually the internal or back surface
  30930. */
  30931. get: function () {
  30932. return Mesh._BACKSIDE;
  30933. },
  30934. enumerable: true,
  30935. configurable: true
  30936. });
  30937. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30938. /**
  30939. * Mesh side orientation : both internal and external or front and back surfaces
  30940. */
  30941. get: function () {
  30942. return Mesh._DOUBLESIDE;
  30943. },
  30944. enumerable: true,
  30945. configurable: true
  30946. });
  30947. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30948. /**
  30949. * Mesh side orientation : by default, `FRONTSIDE`
  30950. */
  30951. get: function () {
  30952. return Mesh._DEFAULTSIDE;
  30953. },
  30954. enumerable: true,
  30955. configurable: true
  30956. });
  30957. Object.defineProperty(Mesh, "NO_CAP", {
  30958. /**
  30959. * Mesh cap setting : no cap
  30960. */
  30961. get: function () {
  30962. return Mesh._NO_CAP;
  30963. },
  30964. enumerable: true,
  30965. configurable: true
  30966. });
  30967. Object.defineProperty(Mesh, "CAP_START", {
  30968. /**
  30969. * Mesh cap setting : one cap at the beginning of the mesh
  30970. */
  30971. get: function () {
  30972. return Mesh._CAP_START;
  30973. },
  30974. enumerable: true,
  30975. configurable: true
  30976. });
  30977. Object.defineProperty(Mesh, "CAP_END", {
  30978. /**
  30979. * Mesh cap setting : one cap at the end of the mesh
  30980. */
  30981. get: function () {
  30982. return Mesh._CAP_END;
  30983. },
  30984. enumerable: true,
  30985. configurable: true
  30986. });
  30987. Object.defineProperty(Mesh, "CAP_ALL", {
  30988. /**
  30989. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30990. */
  30991. get: function () {
  30992. return Mesh._CAP_ALL;
  30993. },
  30994. enumerable: true,
  30995. configurable: true
  30996. });
  30997. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30998. set: function (callback) {
  30999. if (this._onBeforeDrawObserver) {
  31000. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31001. }
  31002. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31003. },
  31004. enumerable: true,
  31005. configurable: true
  31006. });
  31007. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31008. get: function () {
  31009. return this._morphTargetManager;
  31010. },
  31011. set: function (value) {
  31012. if (this._morphTargetManager === value) {
  31013. return;
  31014. }
  31015. this._morphTargetManager = value;
  31016. this._syncGeometryWithMorphTargetManager();
  31017. },
  31018. enumerable: true,
  31019. configurable: true
  31020. });
  31021. Object.defineProperty(Mesh.prototype, "source", {
  31022. get: function () {
  31023. return this._source;
  31024. },
  31025. enumerable: true,
  31026. configurable: true
  31027. });
  31028. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31029. get: function () {
  31030. return this._unIndexed;
  31031. },
  31032. set: function (value) {
  31033. if (this._unIndexed !== value) {
  31034. this._unIndexed = value;
  31035. this._markSubMeshesAsAttributesDirty();
  31036. }
  31037. },
  31038. enumerable: true,
  31039. configurable: true
  31040. });
  31041. // Methods
  31042. /**
  31043. * Returns the string "Mesh".
  31044. */
  31045. Mesh.prototype.getClassName = function () {
  31046. return "Mesh";
  31047. };
  31048. /**
  31049. * Returns a string.
  31050. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31051. */
  31052. Mesh.prototype.toString = function (fullDetails) {
  31053. var ret = _super.prototype.toString.call(this, fullDetails);
  31054. ret += ", n vertices: " + this.getTotalVertices();
  31055. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31056. if (this.animations) {
  31057. for (var i = 0; i < this.animations.length; i++) {
  31058. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31059. }
  31060. }
  31061. if (fullDetails) {
  31062. if (this._geometry) {
  31063. var ib = this.getIndices();
  31064. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31065. if (vb && ib) {
  31066. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31067. }
  31068. }
  31069. else {
  31070. ret += ", flat shading: UNKNOWN";
  31071. }
  31072. }
  31073. return ret;
  31074. };
  31075. Mesh.prototype._unBindEffect = function () {
  31076. _super.prototype._unBindEffect.call(this);
  31077. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31078. var instance = _a[_i];
  31079. instance._unBindEffect();
  31080. }
  31081. };
  31082. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31083. /**
  31084. * True if the mesh has some Levels Of Details (LOD).
  31085. * Returns a boolean.
  31086. */
  31087. get: function () {
  31088. return this._LODLevels.length > 0;
  31089. },
  31090. enumerable: true,
  31091. configurable: true
  31092. });
  31093. /**
  31094. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31095. * @returns an array of {BABYLON.MeshLODLevel}
  31096. */
  31097. Mesh.prototype.getLODLevels = function () {
  31098. return this._LODLevels;
  31099. };
  31100. Mesh.prototype._sortLODLevels = function () {
  31101. this._LODLevels.sort(function (a, b) {
  31102. if (a.distance < b.distance) {
  31103. return 1;
  31104. }
  31105. if (a.distance > b.distance) {
  31106. return -1;
  31107. }
  31108. return 0;
  31109. });
  31110. };
  31111. /**
  31112. * Add a mesh as LOD level triggered at the given distance.
  31113. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31114. * @param {number} distance The distance from the center of the object to show this level
  31115. * @param {Mesh} mesh The mesh to be added as LOD level
  31116. * @return {Mesh} This mesh (for chaining)
  31117. */
  31118. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31119. if (mesh && mesh._masterMesh) {
  31120. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31121. return this;
  31122. }
  31123. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31124. this._LODLevels.push(level);
  31125. if (mesh) {
  31126. mesh._masterMesh = this;
  31127. }
  31128. this._sortLODLevels();
  31129. return this;
  31130. };
  31131. /**
  31132. * Returns the LOD level mesh at the passed distance or null if not found.
  31133. * It is related to the method `addLODLevel(distance, mesh)`.
  31134. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31135. * Returns an object Mesh or `null`.
  31136. */
  31137. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31138. for (var index = 0; index < this._LODLevels.length; index++) {
  31139. var level = this._LODLevels[index];
  31140. if (level.distance === distance) {
  31141. return level.mesh;
  31142. }
  31143. }
  31144. return null;
  31145. };
  31146. /**
  31147. * Remove a mesh from the LOD array
  31148. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31149. * @param {Mesh} mesh The mesh to be removed.
  31150. * @return {Mesh} This mesh (for chaining)
  31151. */
  31152. Mesh.prototype.removeLODLevel = function (mesh) {
  31153. for (var index = 0; index < this._LODLevels.length; index++) {
  31154. if (this._LODLevels[index].mesh === mesh) {
  31155. this._LODLevels.splice(index, 1);
  31156. if (mesh) {
  31157. mesh._masterMesh = null;
  31158. }
  31159. }
  31160. }
  31161. this._sortLODLevels();
  31162. return this;
  31163. };
  31164. /**
  31165. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31166. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31167. */
  31168. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31169. if (!this._LODLevels || this._LODLevels.length === 0) {
  31170. return this;
  31171. }
  31172. var bSphere;
  31173. if (boundingSphere) {
  31174. bSphere = boundingSphere;
  31175. }
  31176. else {
  31177. var boundingInfo = this.getBoundingInfo();
  31178. bSphere = boundingInfo.boundingSphere;
  31179. }
  31180. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31181. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31182. if (this.onLODLevelSelection) {
  31183. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31184. }
  31185. return this;
  31186. }
  31187. for (var index = 0; index < this._LODLevels.length; index++) {
  31188. var level = this._LODLevels[index];
  31189. if (level.distance < distanceToCamera) {
  31190. if (level.mesh) {
  31191. level.mesh._preActivate();
  31192. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31193. }
  31194. if (this.onLODLevelSelection) {
  31195. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31196. }
  31197. return level.mesh;
  31198. }
  31199. }
  31200. if (this.onLODLevelSelection) {
  31201. this.onLODLevelSelection(distanceToCamera, this, this);
  31202. }
  31203. return this;
  31204. };
  31205. Object.defineProperty(Mesh.prototype, "geometry", {
  31206. /**
  31207. * Returns the mesh internal Geometry object.
  31208. */
  31209. get: function () {
  31210. return this._geometry;
  31211. },
  31212. enumerable: true,
  31213. configurable: true
  31214. });
  31215. /**
  31216. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31217. */
  31218. Mesh.prototype.getTotalVertices = function () {
  31219. if (this._geometry === null || this._geometry === undefined) {
  31220. return 0;
  31221. }
  31222. return this._geometry.getTotalVertices();
  31223. };
  31224. /**
  31225. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31226. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31227. * You can force the copy with forceCopy === true
  31228. * Returns null if the mesh has no geometry or no vertex buffer.
  31229. * Possible `kind` values :
  31230. * - BABYLON.VertexBuffer.PositionKind
  31231. * - BABYLON.VertexBuffer.UVKind
  31232. * - BABYLON.VertexBuffer.UV2Kind
  31233. * - BABYLON.VertexBuffer.UV3Kind
  31234. * - BABYLON.VertexBuffer.UV4Kind
  31235. * - BABYLON.VertexBuffer.UV5Kind
  31236. * - BABYLON.VertexBuffer.UV6Kind
  31237. * - BABYLON.VertexBuffer.ColorKind
  31238. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31239. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31240. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31241. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31242. */
  31243. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31244. if (!this._geometry) {
  31245. return null;
  31246. }
  31247. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31248. };
  31249. /**
  31250. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31251. * Returns `null` if the mesh has no geometry.
  31252. * Possible `kind` values :
  31253. * - BABYLON.VertexBuffer.PositionKind
  31254. * - BABYLON.VertexBuffer.UVKind
  31255. * - BABYLON.VertexBuffer.UV2Kind
  31256. * - BABYLON.VertexBuffer.UV3Kind
  31257. * - BABYLON.VertexBuffer.UV4Kind
  31258. * - BABYLON.VertexBuffer.UV5Kind
  31259. * - BABYLON.VertexBuffer.UV6Kind
  31260. * - BABYLON.VertexBuffer.ColorKind
  31261. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31262. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31263. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31264. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31265. */
  31266. Mesh.prototype.getVertexBuffer = function (kind) {
  31267. if (!this._geometry) {
  31268. return null;
  31269. }
  31270. return this._geometry.getVertexBuffer(kind);
  31271. };
  31272. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31273. if (!this._geometry) {
  31274. if (this._delayInfo) {
  31275. return this._delayInfo.indexOf(kind) !== -1;
  31276. }
  31277. return false;
  31278. }
  31279. return this._geometry.isVerticesDataPresent(kind);
  31280. };
  31281. /**
  31282. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31283. * Possible `kind` values :
  31284. * - BABYLON.VertexBuffer.PositionKind
  31285. * - BABYLON.VertexBuffer.UVKind
  31286. * - BABYLON.VertexBuffer.UV2Kind
  31287. * - BABYLON.VertexBuffer.UV3Kind
  31288. * - BABYLON.VertexBuffer.UV4Kind
  31289. * - BABYLON.VertexBuffer.UV5Kind
  31290. * - BABYLON.VertexBuffer.UV6Kind
  31291. * - BABYLON.VertexBuffer.ColorKind
  31292. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31293. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31294. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31295. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31296. */
  31297. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31298. if (!this._geometry) {
  31299. if (this._delayInfo) {
  31300. return this._delayInfo.indexOf(kind) !== -1;
  31301. }
  31302. return false;
  31303. }
  31304. return this._geometry.isVertexBufferUpdatable(kind);
  31305. };
  31306. /**
  31307. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31308. * Possible `kind` values :
  31309. * - BABYLON.VertexBuffer.PositionKind
  31310. * - BABYLON.VertexBuffer.UVKind
  31311. * - BABYLON.VertexBuffer.UV2Kind
  31312. * - BABYLON.VertexBuffer.UV3Kind
  31313. * - BABYLON.VertexBuffer.UV4Kind
  31314. * - BABYLON.VertexBuffer.UV5Kind
  31315. * - BABYLON.VertexBuffer.UV6Kind
  31316. * - BABYLON.VertexBuffer.ColorKind
  31317. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31318. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31319. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31320. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31321. */
  31322. Mesh.prototype.getVerticesDataKinds = function () {
  31323. if (!this._geometry) {
  31324. var result = new Array();
  31325. if (this._delayInfo) {
  31326. this._delayInfo.forEach(function (kind, index, array) {
  31327. result.push(kind);
  31328. });
  31329. }
  31330. return result;
  31331. }
  31332. return this._geometry.getVerticesDataKinds();
  31333. };
  31334. /**
  31335. * Returns a positive integer : the total number of indices in this mesh geometry.
  31336. * Returns zero if the mesh has no geometry.
  31337. */
  31338. Mesh.prototype.getTotalIndices = function () {
  31339. if (!this._geometry) {
  31340. return 0;
  31341. }
  31342. return this._geometry.getTotalIndices();
  31343. };
  31344. /**
  31345. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31346. * If the parameter `copyWhenShared` is 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.
  31347. * Returns an empty array if the mesh has no geometry.
  31348. */
  31349. Mesh.prototype.getIndices = function (copyWhenShared) {
  31350. if (!this._geometry) {
  31351. return [];
  31352. }
  31353. return this._geometry.getIndices(copyWhenShared);
  31354. };
  31355. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31356. get: function () {
  31357. return this._masterMesh !== null && this._masterMesh !== undefined;
  31358. },
  31359. enumerable: true,
  31360. configurable: true
  31361. });
  31362. /**
  31363. * Determine if the current mesh is ready to be rendered
  31364. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31365. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31366. * @returns true if all associated assets are ready (material, textures, shaders)
  31367. */
  31368. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31369. if (completeCheck === void 0) { completeCheck = false; }
  31370. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31371. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31372. return false;
  31373. }
  31374. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31375. return false;
  31376. }
  31377. if (!this.subMeshes || this.subMeshes.length === 0) {
  31378. return true;
  31379. }
  31380. if (!completeCheck) {
  31381. return true;
  31382. }
  31383. var engine = this.getEngine();
  31384. var scene = this.getScene();
  31385. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31386. this.computeWorldMatrix();
  31387. var mat = this.material || scene.defaultMaterial;
  31388. if (mat) {
  31389. if (mat.storeEffectOnSubMeshes) {
  31390. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31391. var subMesh = _a[_i];
  31392. var effectiveMaterial = subMesh.getMaterial();
  31393. if (effectiveMaterial) {
  31394. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31395. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31396. return false;
  31397. }
  31398. }
  31399. else {
  31400. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31401. return false;
  31402. }
  31403. }
  31404. }
  31405. }
  31406. }
  31407. else {
  31408. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31409. return false;
  31410. }
  31411. }
  31412. }
  31413. // Shadows
  31414. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31415. var light = _c[_b];
  31416. var generator = light.getShadowGenerator();
  31417. if (generator) {
  31418. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31419. var subMesh = _e[_d];
  31420. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31421. return false;
  31422. }
  31423. }
  31424. }
  31425. }
  31426. // LOD
  31427. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31428. var lod = _g[_f];
  31429. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31430. return false;
  31431. }
  31432. }
  31433. return true;
  31434. };
  31435. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31436. /**
  31437. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31438. * This property is pertinent only for updatable parametric shapes.
  31439. */
  31440. get: function () {
  31441. return this._areNormalsFrozen;
  31442. },
  31443. enumerable: true,
  31444. configurable: true
  31445. });
  31446. /**
  31447. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31448. * It has no effect at all on other shapes.
  31449. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31450. * Returns the Mesh.
  31451. */
  31452. Mesh.prototype.freezeNormals = function () {
  31453. this._areNormalsFrozen = true;
  31454. return this;
  31455. };
  31456. /**
  31457. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31458. * It has no effect at all on other shapes.
  31459. * It reactivates the mesh normals computation if it was previously frozen.
  31460. * Returns the Mesh.
  31461. */
  31462. Mesh.prototype.unfreezeNormals = function () {
  31463. this._areNormalsFrozen = false;
  31464. return this;
  31465. };
  31466. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31467. /**
  31468. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31469. */
  31470. set: function (count) {
  31471. this._overridenInstanceCount = count;
  31472. },
  31473. enumerable: true,
  31474. configurable: true
  31475. });
  31476. // Methods
  31477. Mesh.prototype._preActivate = function () {
  31478. var sceneRenderId = this.getScene().getRenderId();
  31479. if (this._preActivateId === sceneRenderId) {
  31480. return this;
  31481. }
  31482. this._preActivateId = sceneRenderId;
  31483. this._visibleInstances = null;
  31484. return this;
  31485. };
  31486. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31487. if (this._visibleInstances) {
  31488. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31489. }
  31490. return this;
  31491. };
  31492. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31493. if (!this._visibleInstances) {
  31494. this._visibleInstances = {};
  31495. this._visibleInstances.defaultRenderId = renderId;
  31496. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31497. }
  31498. if (!this._visibleInstances[renderId]) {
  31499. this._visibleInstances[renderId] = new Array();
  31500. }
  31501. this._visibleInstances[renderId].push(instance);
  31502. return this;
  31503. };
  31504. /**
  31505. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31506. * This means the mesh underlying bounding box and sphere are recomputed.
  31507. * Returns the Mesh.
  31508. */
  31509. Mesh.prototype.refreshBoundingInfo = function () {
  31510. return this._refreshBoundingInfo(false);
  31511. };
  31512. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31513. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31514. return this;
  31515. }
  31516. var data = this._getPositionData(applySkeleton);
  31517. if (data) {
  31518. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31519. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31520. }
  31521. if (this.subMeshes) {
  31522. for (var index = 0; index < this.subMeshes.length; index++) {
  31523. this.subMeshes[index].refreshBoundingInfo();
  31524. }
  31525. }
  31526. this._updateBoundingInfo();
  31527. return this;
  31528. };
  31529. Mesh.prototype._getPositionData = function (applySkeleton) {
  31530. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31531. if (data && applySkeleton && this.skeleton) {
  31532. data = BABYLON.Tools.Slice(data);
  31533. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31534. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31535. if (matricesWeightsData && matricesIndicesData) {
  31536. var needExtras = this.numBoneInfluencers > 4;
  31537. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31538. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31539. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31540. var tempVector = BABYLON.Tmp.Vector3[0];
  31541. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31542. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31543. var matWeightIdx = 0;
  31544. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31545. finalMatrix.reset();
  31546. var inf;
  31547. var weight;
  31548. for (inf = 0; inf < 4; inf++) {
  31549. weight = matricesWeightsData[matWeightIdx + inf];
  31550. if (weight <= 0)
  31551. break;
  31552. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31553. finalMatrix.addToSelf(tempMatrix);
  31554. }
  31555. if (needExtras) {
  31556. for (inf = 0; inf < 4; inf++) {
  31557. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31558. if (weight <= 0)
  31559. break;
  31560. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31561. finalMatrix.addToSelf(tempMatrix);
  31562. }
  31563. }
  31564. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31565. tempVector.toArray(data, index);
  31566. }
  31567. }
  31568. }
  31569. return data;
  31570. };
  31571. Mesh.prototype._createGlobalSubMesh = function (force) {
  31572. var totalVertices = this.getTotalVertices();
  31573. if (!totalVertices || !this.getIndices()) {
  31574. return null;
  31575. }
  31576. // Check if we need to recreate the submeshes
  31577. if (this.subMeshes && this.subMeshes.length > 0) {
  31578. var ib = this.getIndices();
  31579. if (!ib) {
  31580. return null;
  31581. }
  31582. var totalIndices = ib.length;
  31583. var needToRecreate = false;
  31584. if (force) {
  31585. needToRecreate = true;
  31586. }
  31587. else {
  31588. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31589. var submesh = _a[_i];
  31590. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31591. needToRecreate = true;
  31592. break;
  31593. }
  31594. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31595. needToRecreate = true;
  31596. break;
  31597. }
  31598. }
  31599. }
  31600. if (!needToRecreate) {
  31601. return this.subMeshes[0];
  31602. }
  31603. }
  31604. this.releaseSubMeshes();
  31605. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31606. };
  31607. Mesh.prototype.subdivide = function (count) {
  31608. if (count < 1) {
  31609. return;
  31610. }
  31611. var totalIndices = this.getTotalIndices();
  31612. var subdivisionSize = (totalIndices / count) | 0;
  31613. var offset = 0;
  31614. // Ensure that subdivisionSize is a multiple of 3
  31615. while (subdivisionSize % 3 !== 0) {
  31616. subdivisionSize++;
  31617. }
  31618. this.releaseSubMeshes();
  31619. for (var index = 0; index < count; index++) {
  31620. if (offset >= totalIndices) {
  31621. break;
  31622. }
  31623. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31624. offset += subdivisionSize;
  31625. }
  31626. this.synchronizeInstances();
  31627. };
  31628. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31629. if (updatable === void 0) { updatable = false; }
  31630. if (!this._geometry) {
  31631. var vertexData = new BABYLON.VertexData();
  31632. vertexData.set(data, kind);
  31633. var scene = this.getScene();
  31634. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31635. }
  31636. else {
  31637. this._geometry.setVerticesData(kind, data, updatable, stride);
  31638. }
  31639. return this;
  31640. };
  31641. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31642. if (updatable === void 0) { updatable = true; }
  31643. var vb = this.getVertexBuffer(kind);
  31644. if (!vb || vb.isUpdatable() === updatable) {
  31645. return;
  31646. }
  31647. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31648. };
  31649. /**
  31650. * Sets the mesh VertexBuffer.
  31651. * Returns the Mesh.
  31652. */
  31653. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31654. if (!this._geometry) {
  31655. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31656. }
  31657. this._geometry.setVerticesBuffer(buffer);
  31658. return this;
  31659. };
  31660. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31661. if (!this._geometry) {
  31662. return this;
  31663. }
  31664. if (!makeItUnique) {
  31665. this._geometry.updateVerticesData(kind, data, updateExtends);
  31666. }
  31667. else {
  31668. this.makeGeometryUnique();
  31669. this.updateVerticesData(kind, data, updateExtends, false);
  31670. }
  31671. return this;
  31672. };
  31673. /**
  31674. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31675. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31676. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31677. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31678. * Returns the Mesh.
  31679. */
  31680. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31681. if (computeNormals === void 0) { computeNormals = true; }
  31682. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31683. if (!positions) {
  31684. return this;
  31685. }
  31686. positionFunction(positions);
  31687. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31688. if (computeNormals) {
  31689. var indices = this.getIndices();
  31690. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31691. if (!normals) {
  31692. return this;
  31693. }
  31694. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31695. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31696. }
  31697. return this;
  31698. };
  31699. /**
  31700. * Creates a un-shared specific occurence of the geometry for the mesh.
  31701. * Returns the Mesh.
  31702. */
  31703. Mesh.prototype.makeGeometryUnique = function () {
  31704. if (!this._geometry) {
  31705. return this;
  31706. }
  31707. var oldGeometry = this._geometry;
  31708. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31709. oldGeometry.releaseForMesh(this, true);
  31710. geometry.applyToMesh(this);
  31711. return this;
  31712. };
  31713. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31714. if (totalVertices === void 0) { totalVertices = null; }
  31715. if (updatable === void 0) { updatable = false; }
  31716. if (!this._geometry) {
  31717. var vertexData = new BABYLON.VertexData();
  31718. vertexData.indices = indices;
  31719. var scene = this.getScene();
  31720. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31721. }
  31722. else {
  31723. this._geometry.setIndices(indices, totalVertices, updatable);
  31724. }
  31725. return this;
  31726. };
  31727. /**
  31728. * Update the current index buffer
  31729. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31730. * Returns the Mesh.
  31731. */
  31732. Mesh.prototype.updateIndices = function (indices, offset) {
  31733. if (!this._geometry) {
  31734. return this;
  31735. }
  31736. this._geometry.updateIndices(indices, offset);
  31737. return this;
  31738. };
  31739. /**
  31740. * Invert the geometry to move from a right handed system to a left handed one.
  31741. * Returns the Mesh.
  31742. */
  31743. Mesh.prototype.toLeftHanded = function () {
  31744. if (!this._geometry) {
  31745. return this;
  31746. }
  31747. this._geometry.toLeftHanded();
  31748. return this;
  31749. };
  31750. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31751. if (!this._geometry) {
  31752. return this;
  31753. }
  31754. var engine = this.getScene().getEngine();
  31755. // Wireframe
  31756. var indexToBind;
  31757. if (this._unIndexed) {
  31758. indexToBind = null;
  31759. }
  31760. else {
  31761. switch (fillMode) {
  31762. case BABYLON.Material.PointFillMode:
  31763. indexToBind = null;
  31764. break;
  31765. case BABYLON.Material.WireFrameFillMode:
  31766. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31767. break;
  31768. default:
  31769. case BABYLON.Material.TriangleFillMode:
  31770. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31771. break;
  31772. }
  31773. }
  31774. // VBOs
  31775. this._geometry._bind(effect, indexToBind);
  31776. return this;
  31777. };
  31778. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31779. if (alternate === void 0) { alternate = false; }
  31780. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31781. return this;
  31782. }
  31783. this.onBeforeDrawObservable.notifyObservers(this);
  31784. var scene = this.getScene();
  31785. var engine = scene.getEngine();
  31786. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31787. // or triangles as points
  31788. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31789. }
  31790. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31791. // Triangles as wireframe
  31792. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31793. }
  31794. else {
  31795. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31796. }
  31797. if (scene._isAlternateRenderingEnabled && !alternate) {
  31798. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31799. if (!effect || !scene.activeCamera) {
  31800. return this;
  31801. }
  31802. scene._switchToAlternateCameraConfiguration(true);
  31803. this._effectiveMaterial.bindView(effect);
  31804. this._effectiveMaterial.bindViewProjection(effect);
  31805. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31806. this._draw(subMesh, fillMode, instancesCount, true);
  31807. engine.setViewport(scene.activeCamera.viewport);
  31808. scene._switchToAlternateCameraConfiguration(false);
  31809. this._effectiveMaterial.bindView(effect);
  31810. this._effectiveMaterial.bindViewProjection(effect);
  31811. }
  31812. return this;
  31813. };
  31814. /**
  31815. * Registers for this mesh a javascript function called just before the rendering process.
  31816. * This function is passed the current mesh.
  31817. * Return the Mesh.
  31818. */
  31819. Mesh.prototype.registerBeforeRender = function (func) {
  31820. this.onBeforeRenderObservable.add(func);
  31821. return this;
  31822. };
  31823. /**
  31824. * Disposes a previously registered javascript function called before the rendering.
  31825. * This function is passed the current mesh.
  31826. * Returns the Mesh.
  31827. */
  31828. Mesh.prototype.unregisterBeforeRender = function (func) {
  31829. this.onBeforeRenderObservable.removeCallback(func);
  31830. return this;
  31831. };
  31832. /**
  31833. * Registers for this mesh a javascript function called just after the rendering is complete.
  31834. * This function is passed the current mesh.
  31835. * Returns the Mesh.
  31836. */
  31837. Mesh.prototype.registerAfterRender = function (func) {
  31838. this.onAfterRenderObservable.add(func);
  31839. return this;
  31840. };
  31841. /**
  31842. * Disposes a previously registered javascript function called after the rendering.
  31843. * This function is passed the current mesh.
  31844. * Return the Mesh.
  31845. */
  31846. Mesh.prototype.unregisterAfterRender = function (func) {
  31847. this.onAfterRenderObservable.removeCallback(func);
  31848. return this;
  31849. };
  31850. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31851. var scene = this.getScene();
  31852. this._batchCache.mustReturn = false;
  31853. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31854. this._batchCache.visibleInstances[subMeshId] = null;
  31855. if (this._visibleInstances) {
  31856. var currentRenderId = scene.getRenderId();
  31857. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31858. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31859. var selfRenderId = this._renderId;
  31860. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31861. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31862. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31863. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31864. }
  31865. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31866. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31867. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31868. this._batchCache.mustReturn = true;
  31869. return this._batchCache;
  31870. }
  31871. if (currentRenderId !== selfRenderId) {
  31872. this._batchCache.renderSelf[subMeshId] = false;
  31873. }
  31874. }
  31875. this._renderIdForInstances[subMeshId] = currentRenderId;
  31876. }
  31877. return this._batchCache;
  31878. };
  31879. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31880. var visibleInstances = batch.visibleInstances[subMesh._id];
  31881. if (!visibleInstances) {
  31882. return this;
  31883. }
  31884. var matricesCount = visibleInstances.length + 1;
  31885. var bufferSize = matricesCount * 16 * 4;
  31886. var currentInstancesBufferSize = this._instancesBufferSize;
  31887. var instancesBuffer = this._instancesBuffer;
  31888. while (this._instancesBufferSize < bufferSize) {
  31889. this._instancesBufferSize *= 2;
  31890. }
  31891. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31892. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31893. }
  31894. var offset = 0;
  31895. var instancesCount = 0;
  31896. var world = this.getWorldMatrix();
  31897. if (batch.renderSelf[subMesh._id]) {
  31898. world.copyToArray(this._instancesData, offset);
  31899. offset += 16;
  31900. instancesCount++;
  31901. }
  31902. if (visibleInstances) {
  31903. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31904. var instance = visibleInstances[instanceIndex];
  31905. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31906. offset += 16;
  31907. instancesCount++;
  31908. }
  31909. }
  31910. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31911. if (instancesBuffer) {
  31912. instancesBuffer.dispose();
  31913. }
  31914. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31915. this._instancesBuffer = instancesBuffer;
  31916. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31917. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31918. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31919. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31920. }
  31921. else {
  31922. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31923. }
  31924. this._bind(subMesh, effect, fillMode);
  31925. this._draw(subMesh, fillMode, instancesCount);
  31926. engine.unbindInstanceAttributes();
  31927. return this;
  31928. };
  31929. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31930. var scene = this.getScene();
  31931. var engine = scene.getEngine();
  31932. if (hardwareInstancedRendering) {
  31933. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31934. }
  31935. else {
  31936. if (batch.renderSelf[subMesh._id]) {
  31937. // Draw
  31938. if (onBeforeDraw) {
  31939. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31940. }
  31941. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31942. }
  31943. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31944. if (visibleInstancesForSubMesh) {
  31945. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31946. var instance = visibleInstancesForSubMesh[instanceIndex];
  31947. // World
  31948. var world = instance.getWorldMatrix();
  31949. if (onBeforeDraw) {
  31950. onBeforeDraw(true, world, effectiveMaterial);
  31951. }
  31952. // Draw
  31953. this._draw(subMesh, fillMode);
  31954. }
  31955. }
  31956. }
  31957. return this;
  31958. };
  31959. /**
  31960. * Triggers the draw call for the mesh.
  31961. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31962. * Returns the Mesh.
  31963. */
  31964. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31965. this._checkOcclusionQuery();
  31966. if (this._isOccluded) {
  31967. return this;
  31968. }
  31969. var scene = this.getScene();
  31970. // Managing instances
  31971. var batch = this._getInstancesRenderList(subMesh._id);
  31972. if (batch.mustReturn) {
  31973. return this;
  31974. }
  31975. // Checking geometry state
  31976. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31977. return this;
  31978. }
  31979. this.onBeforeRenderObservable.notifyObservers(this);
  31980. var engine = scene.getEngine();
  31981. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31982. // Material
  31983. var material = subMesh.getMaterial();
  31984. if (!material) {
  31985. return this;
  31986. }
  31987. this._effectiveMaterial = material;
  31988. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31989. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31990. return this;
  31991. }
  31992. }
  31993. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31994. return this;
  31995. }
  31996. // Alpha mode
  31997. if (enableAlphaMode) {
  31998. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31999. }
  32000. // Outline - step 1
  32001. var savedDepthWrite = engine.getDepthWrite();
  32002. if (this.renderOutline) {
  32003. engine.setDepthWrite(false);
  32004. scene.getOutlineRenderer().render(subMesh, batch);
  32005. engine.setDepthWrite(savedDepthWrite);
  32006. }
  32007. var effect;
  32008. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32009. effect = subMesh.effect;
  32010. }
  32011. else {
  32012. effect = this._effectiveMaterial.getEffect();
  32013. }
  32014. if (!effect) {
  32015. return this;
  32016. }
  32017. var sideOrientation = this.overrideMaterialSideOrientation;
  32018. if (sideOrientation == null) {
  32019. sideOrientation = this._effectiveMaterial.sideOrientation;
  32020. if (this._getWorldMatrixDeterminant() < 0) {
  32021. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32022. }
  32023. }
  32024. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32025. if (this._effectiveMaterial.forceDepthWrite) {
  32026. engine.setDepthWrite(true);
  32027. }
  32028. // Bind
  32029. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32030. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32031. this._bind(subMesh, effect, fillMode);
  32032. }
  32033. var world = this.getWorldMatrix();
  32034. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32035. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32036. }
  32037. else {
  32038. this._effectiveMaterial.bind(world, this);
  32039. }
  32040. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32041. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32042. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32043. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32044. }
  32045. // Draw
  32046. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32047. // Unbind
  32048. this._effectiveMaterial.unbind();
  32049. // Outline - step 2
  32050. if (this.renderOutline && savedDepthWrite) {
  32051. engine.setDepthWrite(true);
  32052. engine.setColorWrite(false);
  32053. scene.getOutlineRenderer().render(subMesh, batch);
  32054. engine.setColorWrite(true);
  32055. }
  32056. // Overlay
  32057. if (this.renderOverlay) {
  32058. var currentMode = engine.getAlphaMode();
  32059. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32060. scene.getOutlineRenderer().render(subMesh, batch, true);
  32061. engine.setAlphaMode(currentMode);
  32062. }
  32063. this.onAfterRenderObservable.notifyObservers(this);
  32064. return this;
  32065. };
  32066. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32067. if (isInstance && effectiveMaterial) {
  32068. effectiveMaterial.bindOnlyWorldMatrix(world);
  32069. }
  32070. };
  32071. /**
  32072. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32073. */
  32074. Mesh.prototype.getEmittedParticleSystems = function () {
  32075. var results = new Array();
  32076. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32077. var particleSystem = this.getScene().particleSystems[index];
  32078. if (particleSystem.emitter === this) {
  32079. results.push(particleSystem);
  32080. }
  32081. }
  32082. return results;
  32083. };
  32084. /**
  32085. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32086. */
  32087. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32088. var results = new Array();
  32089. var descendants = this.getDescendants();
  32090. descendants.push(this);
  32091. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32092. var particleSystem = this.getScene().particleSystems[index];
  32093. var emitter = particleSystem.emitter;
  32094. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32095. results.push(particleSystem);
  32096. }
  32097. }
  32098. return results;
  32099. };
  32100. Mesh.prototype._checkDelayState = function () {
  32101. var scene = this.getScene();
  32102. if (this._geometry) {
  32103. this._geometry.load(scene);
  32104. }
  32105. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32107. this._queueLoad(scene);
  32108. }
  32109. return this;
  32110. };
  32111. Mesh.prototype._queueLoad = function (scene) {
  32112. var _this = this;
  32113. scene._addPendingData(this);
  32114. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32115. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32116. if (data instanceof ArrayBuffer) {
  32117. _this._delayLoadingFunction(data, _this);
  32118. }
  32119. else {
  32120. _this._delayLoadingFunction(JSON.parse(data), _this);
  32121. }
  32122. _this.instances.forEach(function (instance) {
  32123. instance._syncSubMeshes();
  32124. });
  32125. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32126. scene._removePendingData(_this);
  32127. }, function () { }, scene.database, getBinaryData);
  32128. return this;
  32129. };
  32130. /**
  32131. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32132. */
  32133. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32134. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32135. return false;
  32136. }
  32137. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32138. return false;
  32139. }
  32140. this._checkDelayState();
  32141. return true;
  32142. };
  32143. /**
  32144. * Sets the mesh material by the material or multiMaterial `id` property.
  32145. * The material `id` is a string identifying the material or the multiMaterial.
  32146. * This method returns the Mesh.
  32147. */
  32148. Mesh.prototype.setMaterialByID = function (id) {
  32149. var materials = this.getScene().materials;
  32150. var index;
  32151. for (index = materials.length - 1; index > -1; index--) {
  32152. if (materials[index].id === id) {
  32153. this.material = materials[index];
  32154. return this;
  32155. }
  32156. }
  32157. // Multi
  32158. var multiMaterials = this.getScene().multiMaterials;
  32159. for (index = multiMaterials.length - 1; index > -1; index--) {
  32160. if (multiMaterials[index].id === id) {
  32161. this.material = multiMaterials[index];
  32162. return this;
  32163. }
  32164. }
  32165. return this;
  32166. };
  32167. /**
  32168. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32169. */
  32170. Mesh.prototype.getAnimatables = function () {
  32171. var results = new Array();
  32172. if (this.material) {
  32173. results.push(this.material);
  32174. }
  32175. if (this.skeleton) {
  32176. results.push(this.skeleton);
  32177. }
  32178. return results;
  32179. };
  32180. /**
  32181. * Modifies the mesh geometry according to the passed transformation matrix.
  32182. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32183. * The mesh normals are modified accordingly the same transformation.
  32184. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32185. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32186. * Returns the Mesh.
  32187. */
  32188. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32189. // Position
  32190. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32191. return this;
  32192. }
  32193. var submeshes = this.subMeshes.splice(0);
  32194. this._resetPointsArrayCache();
  32195. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32196. var temp = new Array();
  32197. var index;
  32198. for (index = 0; index < data.length; index += 3) {
  32199. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32200. }
  32201. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32202. // Normals
  32203. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32204. return this;
  32205. }
  32206. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32207. temp = [];
  32208. for (index = 0; index < data.length; index += 3) {
  32209. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32210. }
  32211. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32212. // flip faces?
  32213. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32214. this.flipFaces();
  32215. }
  32216. // Restore submeshes
  32217. this.releaseSubMeshes();
  32218. this.subMeshes = submeshes;
  32219. return this;
  32220. };
  32221. /**
  32222. * Modifies the mesh geometry according to its own current World Matrix.
  32223. * The mesh World Matrix is then reset.
  32224. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32225. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32226. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32227. * Returns the Mesh.
  32228. */
  32229. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32230. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32231. this.scaling.copyFromFloats(1, 1, 1);
  32232. this.position.copyFromFloats(0, 0, 0);
  32233. this.rotation.copyFromFloats(0, 0, 0);
  32234. //only if quaternion is already set
  32235. if (this.rotationQuaternion) {
  32236. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32237. }
  32238. this._worldMatrix = BABYLON.Matrix.Identity();
  32239. return this;
  32240. };
  32241. Object.defineProperty(Mesh.prototype, "_positions", {
  32242. // Cache
  32243. get: function () {
  32244. if (this._geometry) {
  32245. return this._geometry._positions;
  32246. }
  32247. return null;
  32248. },
  32249. enumerable: true,
  32250. configurable: true
  32251. });
  32252. Mesh.prototype._resetPointsArrayCache = function () {
  32253. if (this._geometry) {
  32254. this._geometry._resetPointsArrayCache();
  32255. }
  32256. return this;
  32257. };
  32258. Mesh.prototype._generatePointsArray = function () {
  32259. if (this._geometry) {
  32260. return this._geometry._generatePointsArray();
  32261. }
  32262. return false;
  32263. };
  32264. /**
  32265. * Returns a new Mesh object generated from the current mesh properties.
  32266. * This method must not get confused with createInstance().
  32267. * The parameter `name` is a string, the name given to the new mesh.
  32268. * The optional parameter `newParent` can be any Node object (default `null`).
  32269. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32270. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32271. */
  32272. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32273. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32274. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32275. };
  32276. /**
  32277. * Releases resources associated with this mesh.
  32278. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32279. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32280. */
  32281. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32282. var _this = this;
  32283. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32284. this.morphTargetManager = null;
  32285. if (this._geometry) {
  32286. this._geometry.releaseForMesh(this, true);
  32287. }
  32288. // Sources
  32289. var meshes = this.getScene().meshes;
  32290. meshes.forEach(function (abstractMesh) {
  32291. var mesh = abstractMesh;
  32292. if (mesh._source && mesh._source === _this) {
  32293. mesh._source = null;
  32294. }
  32295. });
  32296. this._source = null;
  32297. // Instances
  32298. if (this._instancesBuffer) {
  32299. this._instancesBuffer.dispose();
  32300. this._instancesBuffer = null;
  32301. }
  32302. while (this.instances.length) {
  32303. this.instances[0].dispose();
  32304. }
  32305. // Effect layers.
  32306. var effectLayers = this.getScene().effectLayers;
  32307. for (var i = 0; i < effectLayers.length; i++) {
  32308. var effectLayer = effectLayers[i];
  32309. if (effectLayer) {
  32310. effectLayer._disposeMesh(this);
  32311. }
  32312. }
  32313. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32314. };
  32315. /**
  32316. * Modifies the mesh geometry according to a displacement map.
  32317. * 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.
  32318. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32319. * This method returns nothing.
  32320. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32321. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32322. * The parameter `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.
  32323. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32324. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32325. *
  32326. * Returns the Mesh.
  32327. */
  32328. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32329. var _this = this;
  32330. var scene = this.getScene();
  32331. var onload = function (img) {
  32332. // Getting height map data
  32333. var canvas = document.createElement("canvas");
  32334. var context = canvas.getContext("2d");
  32335. var heightMapWidth = img.width;
  32336. var heightMapHeight = img.height;
  32337. canvas.width = heightMapWidth;
  32338. canvas.height = heightMapHeight;
  32339. context.drawImage(img, 0, 0);
  32340. // Create VertexData from map data
  32341. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32342. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32343. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32344. //execute success callback, if set
  32345. if (onSuccess) {
  32346. onSuccess(_this);
  32347. }
  32348. };
  32349. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32350. return this;
  32351. };
  32352. /**
  32353. * Modifies the mesh geometry according to a displacementMap buffer.
  32354. * 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.
  32355. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32356. * This method returns nothing.
  32357. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32358. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32359. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32360. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32361. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32362. *
  32363. * Returns the Mesh.
  32364. */
  32365. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32366. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32367. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32368. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32369. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32370. return this;
  32371. }
  32372. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32373. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32374. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32375. var position = BABYLON.Vector3.Zero();
  32376. var normal = BABYLON.Vector3.Zero();
  32377. var uv = BABYLON.Vector2.Zero();
  32378. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32379. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32380. for (var index = 0; index < positions.length; index += 3) {
  32381. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32382. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32383. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32384. // Compute height
  32385. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32386. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32387. var pos = (u + v * heightMapWidth) * 4;
  32388. var r = buffer[pos] / 255.0;
  32389. var g = buffer[pos + 1] / 255.0;
  32390. var b = buffer[pos + 2] / 255.0;
  32391. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32392. normal.normalize();
  32393. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32394. position = position.add(normal);
  32395. position.toArray(positions, index);
  32396. }
  32397. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32398. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32399. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32400. return this;
  32401. };
  32402. /**
  32403. * Modify the mesh to get a flat shading rendering.
  32404. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32405. * This method returns the Mesh.
  32406. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32407. */
  32408. Mesh.prototype.convertToFlatShadedMesh = function () {
  32409. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32410. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32411. var kinds = this.getVerticesDataKinds();
  32412. var vbs = {};
  32413. var data = {};
  32414. var newdata = {};
  32415. var updatableNormals = false;
  32416. var kindIndex;
  32417. var kind;
  32418. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32419. kind = kinds[kindIndex];
  32420. var vertexBuffer = this.getVertexBuffer(kind);
  32421. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32422. updatableNormals = vertexBuffer.isUpdatable();
  32423. kinds.splice(kindIndex, 1);
  32424. kindIndex--;
  32425. continue;
  32426. }
  32427. vbs[kind] = vertexBuffer;
  32428. data[kind] = vbs[kind].getData();
  32429. newdata[kind] = [];
  32430. }
  32431. // Save previous submeshes
  32432. var previousSubmeshes = this.subMeshes.slice(0);
  32433. var indices = this.getIndices();
  32434. var totalIndices = this.getTotalIndices();
  32435. // Generating unique vertices per face
  32436. var index;
  32437. for (index = 0; index < totalIndices; index++) {
  32438. var vertexIndex = indices[index];
  32439. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32440. kind = kinds[kindIndex];
  32441. var stride = vbs[kind].getStrideSize();
  32442. for (var offset = 0; offset < stride; offset++) {
  32443. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32444. }
  32445. }
  32446. }
  32447. // Updating faces & normal
  32448. var normals = [];
  32449. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32450. for (index = 0; index < totalIndices; index += 3) {
  32451. indices[index] = index;
  32452. indices[index + 1] = index + 1;
  32453. indices[index + 2] = index + 2;
  32454. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32455. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32456. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32457. var p1p2 = p1.subtract(p2);
  32458. var p3p2 = p3.subtract(p2);
  32459. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32460. // Store same normals for every vertex
  32461. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32462. normals.push(normal.x);
  32463. normals.push(normal.y);
  32464. normals.push(normal.z);
  32465. }
  32466. }
  32467. this.setIndices(indices);
  32468. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32469. // Updating vertex buffers
  32470. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32471. kind = kinds[kindIndex];
  32472. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32473. }
  32474. // Updating submeshes
  32475. this.releaseSubMeshes();
  32476. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32477. var previousOne = previousSubmeshes[submeshIndex];
  32478. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32479. }
  32480. this.synchronizeInstances();
  32481. return this;
  32482. };
  32483. /**
  32484. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32485. * In other words, more vertices, no more indices and a single bigger VBO.
  32486. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32487. * Returns the Mesh.
  32488. */
  32489. Mesh.prototype.convertToUnIndexedMesh = function () {
  32490. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32491. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32492. var kinds = this.getVerticesDataKinds();
  32493. var vbs = {};
  32494. var data = {};
  32495. var newdata = {};
  32496. var kindIndex;
  32497. var kind;
  32498. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32499. kind = kinds[kindIndex];
  32500. var vertexBuffer = this.getVertexBuffer(kind);
  32501. vbs[kind] = vertexBuffer;
  32502. data[kind] = vbs[kind].getData();
  32503. newdata[kind] = [];
  32504. }
  32505. // Save previous submeshes
  32506. var previousSubmeshes = this.subMeshes.slice(0);
  32507. var indices = this.getIndices();
  32508. var totalIndices = this.getTotalIndices();
  32509. // Generating unique vertices per face
  32510. var index;
  32511. for (index = 0; index < totalIndices; index++) {
  32512. var vertexIndex = indices[index];
  32513. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32514. kind = kinds[kindIndex];
  32515. var stride = vbs[kind].getStrideSize();
  32516. for (var offset = 0; offset < stride; offset++) {
  32517. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32518. }
  32519. }
  32520. }
  32521. // Updating indices
  32522. for (index = 0; index < totalIndices; index += 3) {
  32523. indices[index] = index;
  32524. indices[index + 1] = index + 1;
  32525. indices[index + 2] = index + 2;
  32526. }
  32527. this.setIndices(indices);
  32528. // Updating vertex buffers
  32529. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32530. kind = kinds[kindIndex];
  32531. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32532. }
  32533. // Updating submeshes
  32534. this.releaseSubMeshes();
  32535. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32536. var previousOne = previousSubmeshes[submeshIndex];
  32537. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32538. }
  32539. this._unIndexed = true;
  32540. this.synchronizeInstances();
  32541. return this;
  32542. };
  32543. /**
  32544. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32545. * This method returns the Mesh.
  32546. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32547. */
  32548. Mesh.prototype.flipFaces = function (flipNormals) {
  32549. if (flipNormals === void 0) { flipNormals = false; }
  32550. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32551. var i;
  32552. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32553. for (i = 0; i < vertex_data.normals.length; i++) {
  32554. vertex_data.normals[i] *= -1;
  32555. }
  32556. }
  32557. if (vertex_data.indices) {
  32558. var temp;
  32559. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32560. // reassign indices
  32561. temp = vertex_data.indices[i + 1];
  32562. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32563. vertex_data.indices[i + 2] = temp;
  32564. }
  32565. }
  32566. vertex_data.applyToMesh(this);
  32567. return this;
  32568. };
  32569. // Instances
  32570. /**
  32571. * Creates a new InstancedMesh object from the mesh model.
  32572. * An instance shares the same properties and the same material than its model.
  32573. * Only these properties of each instance can then be set individually :
  32574. * - position
  32575. * - rotation
  32576. * - rotationQuaternion
  32577. * - setPivotMatrix
  32578. * - scaling
  32579. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32580. * Warning : this method is not supported for Line mesh and LineSystem
  32581. */
  32582. Mesh.prototype.createInstance = function (name) {
  32583. return new BABYLON.InstancedMesh(name, this);
  32584. };
  32585. /**
  32586. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32587. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32588. * This method returns the Mesh.
  32589. */
  32590. Mesh.prototype.synchronizeInstances = function () {
  32591. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32592. var instance = this.instances[instanceIndex];
  32593. instance._syncSubMeshes();
  32594. }
  32595. return this;
  32596. };
  32597. /**
  32598. * Simplify the mesh according to the given array of settings.
  32599. * Function will return immediately and will simplify async. It returns the Mesh.
  32600. * @param settings a collection of simplification settings.
  32601. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32602. * @param type the type of simplification to run.
  32603. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32604. */
  32605. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32606. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32607. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32608. this.getScene().simplificationQueue.addTask({
  32609. settings: settings,
  32610. parallelProcessing: parallelProcessing,
  32611. mesh: this,
  32612. simplificationType: simplificationType,
  32613. successCallback: successCallback
  32614. });
  32615. return this;
  32616. };
  32617. /**
  32618. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32619. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32620. * This should be used together with the simplification to avoid disappearing triangles.
  32621. * Returns the Mesh.
  32622. * @param successCallback an optional success callback to be called after the optimization finished.
  32623. */
  32624. Mesh.prototype.optimizeIndices = function (successCallback) {
  32625. var _this = this;
  32626. var indices = this.getIndices();
  32627. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32628. if (!positions || !indices) {
  32629. return this;
  32630. }
  32631. var vectorPositions = new Array();
  32632. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32633. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32634. }
  32635. var dupes = new Array();
  32636. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32637. var realPos = vectorPositions.length - 1 - iteration;
  32638. var testedPosition = vectorPositions[realPos];
  32639. for (var j = 0; j < realPos; ++j) {
  32640. var againstPosition = vectorPositions[j];
  32641. if (testedPosition.equals(againstPosition)) {
  32642. dupes[realPos] = j;
  32643. break;
  32644. }
  32645. }
  32646. }, function () {
  32647. for (var i = 0; i < indices.length; ++i) {
  32648. indices[i] = dupes[indices[i]] || indices[i];
  32649. }
  32650. //indices are now reordered
  32651. var originalSubMeshes = _this.subMeshes.slice(0);
  32652. _this.setIndices(indices);
  32653. _this.subMeshes = originalSubMeshes;
  32654. if (successCallback) {
  32655. successCallback(_this);
  32656. }
  32657. });
  32658. return this;
  32659. };
  32660. Mesh.prototype.serialize = function (serializationObject) {
  32661. serializationObject.name = this.name;
  32662. serializationObject.id = this.id;
  32663. serializationObject.type = this.getClassName();
  32664. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32665. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32666. }
  32667. serializationObject.position = this.position.asArray();
  32668. if (this.rotationQuaternion) {
  32669. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32670. }
  32671. else if (this.rotation) {
  32672. serializationObject.rotation = this.rotation.asArray();
  32673. }
  32674. serializationObject.scaling = this.scaling.asArray();
  32675. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32676. serializationObject.isEnabled = this.isEnabled(false);
  32677. serializationObject.isVisible = this.isVisible;
  32678. serializationObject.infiniteDistance = this.infiniteDistance;
  32679. serializationObject.pickable = this.isPickable;
  32680. serializationObject.receiveShadows = this.receiveShadows;
  32681. serializationObject.billboardMode = this.billboardMode;
  32682. serializationObject.visibility = this.visibility;
  32683. serializationObject.checkCollisions = this.checkCollisions;
  32684. serializationObject.isBlocker = this.isBlocker;
  32685. // Parent
  32686. if (this.parent) {
  32687. serializationObject.parentId = this.parent.id;
  32688. }
  32689. // Geometry
  32690. serializationObject.isUnIndexed = this.isUnIndexed;
  32691. var geometry = this._geometry;
  32692. if (geometry) {
  32693. var geometryId = geometry.id;
  32694. serializationObject.geometryId = geometryId;
  32695. // SubMeshes
  32696. serializationObject.subMeshes = [];
  32697. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32698. var subMesh = this.subMeshes[subIndex];
  32699. serializationObject.subMeshes.push({
  32700. materialIndex: subMesh.materialIndex,
  32701. verticesStart: subMesh.verticesStart,
  32702. verticesCount: subMesh.verticesCount,
  32703. indexStart: subMesh.indexStart,
  32704. indexCount: subMesh.indexCount
  32705. });
  32706. }
  32707. }
  32708. // Material
  32709. if (this.material) {
  32710. serializationObject.materialId = this.material.id;
  32711. }
  32712. else {
  32713. this.material = null;
  32714. }
  32715. // Morph targets
  32716. if (this.morphTargetManager) {
  32717. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32718. }
  32719. // Skeleton
  32720. if (this.skeleton) {
  32721. serializationObject.skeletonId = this.skeleton.id;
  32722. }
  32723. // Physics
  32724. //TODO implement correct serialization for physics impostors.
  32725. var impostor = this.getPhysicsImpostor();
  32726. if (impostor) {
  32727. serializationObject.physicsMass = impostor.getParam("mass");
  32728. serializationObject.physicsFriction = impostor.getParam("friction");
  32729. serializationObject.physicsRestitution = impostor.getParam("mass");
  32730. serializationObject.physicsImpostor = impostor.type;
  32731. }
  32732. // Metadata
  32733. if (this.metadata) {
  32734. serializationObject.metadata = this.metadata;
  32735. }
  32736. // Instances
  32737. serializationObject.instances = [];
  32738. for (var index = 0; index < this.instances.length; index++) {
  32739. var instance = this.instances[index];
  32740. var serializationInstance = {
  32741. name: instance.name,
  32742. id: instance.id,
  32743. position: instance.position.asArray(),
  32744. scaling: instance.scaling.asArray()
  32745. };
  32746. if (instance.rotationQuaternion) {
  32747. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32748. }
  32749. else if (instance.rotation) {
  32750. serializationInstance.rotation = instance.rotation.asArray();
  32751. }
  32752. serializationObject.instances.push(serializationInstance);
  32753. // Animations
  32754. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32755. serializationInstance.ranges = instance.serializeAnimationRanges();
  32756. }
  32757. //
  32758. // Animations
  32759. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32760. serializationObject.ranges = this.serializeAnimationRanges();
  32761. // Layer mask
  32762. serializationObject.layerMask = this.layerMask;
  32763. // Alpha
  32764. serializationObject.alphaIndex = this.alphaIndex;
  32765. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32766. // Overlay
  32767. serializationObject.overlayAlpha = this.overlayAlpha;
  32768. serializationObject.overlayColor = this.overlayColor.asArray();
  32769. serializationObject.renderOverlay = this.renderOverlay;
  32770. // Fog
  32771. serializationObject.applyFog = this.applyFog;
  32772. // Action Manager
  32773. if (this.actionManager) {
  32774. serializationObject.actions = this.actionManager.serialize(this.name);
  32775. }
  32776. };
  32777. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32778. if (!this.geometry) {
  32779. return;
  32780. }
  32781. this._markSubMeshesAsAttributesDirty();
  32782. var morphTargetManager = this._morphTargetManager;
  32783. if (morphTargetManager && morphTargetManager.vertexCount) {
  32784. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32785. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32786. this.morphTargetManager = null;
  32787. return;
  32788. }
  32789. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32790. var morphTarget = morphTargetManager.getActiveTarget(index);
  32791. var positions = morphTarget.getPositions();
  32792. if (!positions) {
  32793. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32794. return;
  32795. }
  32796. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32797. var normals = morphTarget.getNormals();
  32798. if (normals) {
  32799. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32800. }
  32801. var tangents = morphTarget.getTangents();
  32802. if (tangents) {
  32803. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32804. }
  32805. }
  32806. }
  32807. else {
  32808. var index = 0;
  32809. // Positions
  32810. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32811. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32812. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32813. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32814. }
  32815. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32816. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32817. }
  32818. index++;
  32819. }
  32820. }
  32821. };
  32822. // Statics
  32823. /**
  32824. * Returns a new Mesh object parsed from the source provided.
  32825. * The parameter `parsedMesh` is the source.
  32826. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32827. */
  32828. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32829. var mesh;
  32830. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32831. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32832. }
  32833. else {
  32834. mesh = new Mesh(parsedMesh.name, scene);
  32835. }
  32836. mesh.id = parsedMesh.id;
  32837. if (BABYLON.Tags) {
  32838. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32839. }
  32840. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32841. if (parsedMesh.metadata !== undefined) {
  32842. mesh.metadata = parsedMesh.metadata;
  32843. }
  32844. if (parsedMesh.rotationQuaternion) {
  32845. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32846. }
  32847. else if (parsedMesh.rotation) {
  32848. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32849. }
  32850. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32851. if (parsedMesh.localMatrix) {
  32852. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32853. }
  32854. else if (parsedMesh.pivotMatrix) {
  32855. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32856. }
  32857. mesh.setEnabled(parsedMesh.isEnabled);
  32858. mesh.isVisible = parsedMesh.isVisible;
  32859. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32860. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32861. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32862. if (parsedMesh.applyFog !== undefined) {
  32863. mesh.applyFog = parsedMesh.applyFog;
  32864. }
  32865. if (parsedMesh.pickable !== undefined) {
  32866. mesh.isPickable = parsedMesh.pickable;
  32867. }
  32868. if (parsedMesh.alphaIndex !== undefined) {
  32869. mesh.alphaIndex = parsedMesh.alphaIndex;
  32870. }
  32871. mesh.receiveShadows = parsedMesh.receiveShadows;
  32872. mesh.billboardMode = parsedMesh.billboardMode;
  32873. if (parsedMesh.visibility !== undefined) {
  32874. mesh.visibility = parsedMesh.visibility;
  32875. }
  32876. mesh.checkCollisions = parsedMesh.checkCollisions;
  32877. if (parsedMesh.isBlocker !== undefined) {
  32878. mesh.isBlocker = parsedMesh.isBlocker;
  32879. }
  32880. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32881. // freezeWorldMatrix
  32882. if (parsedMesh.freezeWorldMatrix) {
  32883. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32884. }
  32885. // Parent
  32886. if (parsedMesh.parentId) {
  32887. mesh._waitingParentId = parsedMesh.parentId;
  32888. }
  32889. // Actions
  32890. if (parsedMesh.actions !== undefined) {
  32891. mesh._waitingActions = parsedMesh.actions;
  32892. }
  32893. // Overlay
  32894. if (parsedMesh.overlayAlpha !== undefined) {
  32895. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32896. }
  32897. if (parsedMesh.overlayColor !== undefined) {
  32898. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32899. }
  32900. if (parsedMesh.renderOverlay !== undefined) {
  32901. mesh.renderOverlay = parsedMesh.renderOverlay;
  32902. }
  32903. // Geometry
  32904. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32905. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32906. if (parsedMesh.delayLoadingFile) {
  32907. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32908. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32909. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32910. if (parsedMesh._binaryInfo) {
  32911. mesh._binaryInfo = parsedMesh._binaryInfo;
  32912. }
  32913. mesh._delayInfo = [];
  32914. if (parsedMesh.hasUVs) {
  32915. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32916. }
  32917. if (parsedMesh.hasUVs2) {
  32918. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32919. }
  32920. if (parsedMesh.hasUVs3) {
  32921. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32922. }
  32923. if (parsedMesh.hasUVs4) {
  32924. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32925. }
  32926. if (parsedMesh.hasUVs5) {
  32927. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32928. }
  32929. if (parsedMesh.hasUVs6) {
  32930. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32931. }
  32932. if (parsedMesh.hasColors) {
  32933. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32934. }
  32935. if (parsedMesh.hasMatricesIndices) {
  32936. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32937. }
  32938. if (parsedMesh.hasMatricesWeights) {
  32939. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32940. }
  32941. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32942. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32943. mesh._checkDelayState();
  32944. }
  32945. }
  32946. else {
  32947. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32948. }
  32949. // Material
  32950. if (parsedMesh.materialId) {
  32951. mesh.setMaterialByID(parsedMesh.materialId);
  32952. }
  32953. else {
  32954. mesh.material = null;
  32955. }
  32956. // Morph targets
  32957. if (parsedMesh.morphTargetManagerId > -1) {
  32958. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32959. }
  32960. // Skeleton
  32961. if (parsedMesh.skeletonId > -1) {
  32962. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32963. if (parsedMesh.numBoneInfluencers) {
  32964. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32965. }
  32966. }
  32967. // Animations
  32968. if (parsedMesh.animations) {
  32969. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32970. var parsedAnimation = parsedMesh.animations[animationIndex];
  32971. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32972. }
  32973. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32974. }
  32975. if (parsedMesh.autoAnimate) {
  32976. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32977. }
  32978. // Layer Mask
  32979. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32980. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32981. }
  32982. else {
  32983. mesh.layerMask = 0x0FFFFFFF;
  32984. }
  32985. // Physics
  32986. if (parsedMesh.physicsImpostor) {
  32987. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32988. mass: parsedMesh.physicsMass,
  32989. friction: parsedMesh.physicsFriction,
  32990. restitution: parsedMesh.physicsRestitution
  32991. }, scene);
  32992. }
  32993. // Instances
  32994. if (parsedMesh.instances) {
  32995. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32996. var parsedInstance = parsedMesh.instances[index];
  32997. var instance = mesh.createInstance(parsedInstance.name);
  32998. if (parsedInstance.id) {
  32999. instance.id = parsedInstance.id;
  33000. }
  33001. if (BABYLON.Tags) {
  33002. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33003. }
  33004. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33005. if (parsedInstance.parentId) {
  33006. instance._waitingParentId = parsedInstance.parentId;
  33007. }
  33008. if (parsedInstance.rotationQuaternion) {
  33009. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33010. }
  33011. else if (parsedInstance.rotation) {
  33012. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33013. }
  33014. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33015. instance.checkCollisions = mesh.checkCollisions;
  33016. if (parsedMesh.animations) {
  33017. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33018. parsedAnimation = parsedMesh.animations[animationIndex];
  33019. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33020. }
  33021. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33022. }
  33023. }
  33024. }
  33025. return mesh;
  33026. };
  33027. /**
  33028. * Creates a ribbon mesh.
  33029. * Please consider using the same method from the MeshBuilder class instead.
  33030. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33031. *
  33032. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33033. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33034. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33035. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33036. * 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.
  33037. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33038. * 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
  33039. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33040. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33041. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33042. */
  33043. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33044. if (closeArray === void 0) { closeArray = false; }
  33045. if (updatable === void 0) { updatable = false; }
  33046. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33047. pathArray: pathArray,
  33048. closeArray: closeArray,
  33049. closePath: closePath,
  33050. offset: offset,
  33051. updatable: updatable,
  33052. sideOrientation: sideOrientation,
  33053. instance: instance
  33054. }, scene);
  33055. };
  33056. /**
  33057. * Creates a plane polygonal mesh. By default, this is a disc.
  33058. * Please consider using the same method from the MeshBuilder class instead.
  33059. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33060. * 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.
  33061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33062. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33064. */
  33065. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33066. if (scene === void 0) { scene = null; }
  33067. var options = {
  33068. radius: radius,
  33069. tessellation: tessellation,
  33070. sideOrientation: sideOrientation,
  33071. updatable: updatable
  33072. };
  33073. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33074. };
  33075. /**
  33076. * Creates a box mesh.
  33077. * Please consider using the same method from the MeshBuilder class instead.
  33078. * The parameter `size` sets the size (float) of each box side (default 1).
  33079. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33080. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33082. */
  33083. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33084. if (scene === void 0) { scene = null; }
  33085. var options = {
  33086. size: size,
  33087. sideOrientation: sideOrientation,
  33088. updatable: updatable
  33089. };
  33090. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33091. };
  33092. /**
  33093. * Creates a sphere mesh.
  33094. * Please consider using the same method from the MeshBuilder class instead.
  33095. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33096. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33098. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33100. */
  33101. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33102. var options = {
  33103. segments: segments,
  33104. diameterX: diameter,
  33105. diameterY: diameter,
  33106. diameterZ: diameter,
  33107. sideOrientation: sideOrientation,
  33108. updatable: updatable
  33109. };
  33110. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33111. };
  33112. /**
  33113. * Creates a cylinder or a cone mesh.
  33114. * Please consider using the same method from the MeshBuilder class instead.
  33115. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33116. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33117. * 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.
  33118. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33119. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33121. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33123. */
  33124. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33125. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33126. if (scene !== undefined) {
  33127. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33128. updatable = scene;
  33129. }
  33130. scene = subdivisions;
  33131. subdivisions = 1;
  33132. }
  33133. var options = {
  33134. height: height,
  33135. diameterTop: diameterTop,
  33136. diameterBottom: diameterBottom,
  33137. tessellation: tessellation,
  33138. subdivisions: subdivisions,
  33139. sideOrientation: sideOrientation,
  33140. updatable: updatable
  33141. };
  33142. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33143. };
  33144. // Torus (Code from SharpDX.org)
  33145. /**
  33146. * Creates a torus mesh.
  33147. * Please consider using the same method from the MeshBuilder class instead.
  33148. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33149. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33150. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33151. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33152. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33154. */
  33155. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33156. var options = {
  33157. diameter: diameter,
  33158. thickness: thickness,
  33159. tessellation: tessellation,
  33160. sideOrientation: sideOrientation,
  33161. updatable: updatable
  33162. };
  33163. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33164. };
  33165. /**
  33166. * Creates a torus knot mesh.
  33167. * Please consider using the same method from the MeshBuilder class instead.
  33168. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33169. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33170. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33171. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33173. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33175. */
  33176. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33177. var options = {
  33178. radius: radius,
  33179. tube: tube,
  33180. radialSegments: radialSegments,
  33181. tubularSegments: tubularSegments,
  33182. p: p,
  33183. q: q,
  33184. sideOrientation: sideOrientation,
  33185. updatable: updatable
  33186. };
  33187. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33188. };
  33189. /**
  33190. * Creates a line mesh.
  33191. * Please consider using the same method from the MeshBuilder class instead.
  33192. * 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.
  33193. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33194. * The parameter `points` is an array successive Vector3.
  33195. * 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
  33196. * When updating an instance, remember that only point positions can change, not the number of points.
  33197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33198. */
  33199. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33200. if (scene === void 0) { scene = null; }
  33201. if (updatable === void 0) { updatable = false; }
  33202. if (instance === void 0) { instance = null; }
  33203. var options = {
  33204. points: points,
  33205. updatable: updatable,
  33206. instance: instance
  33207. };
  33208. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33209. };
  33210. /**
  33211. * Creates a dashed line mesh.
  33212. * Please consider using the same method from the MeshBuilder class instead.
  33213. * 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.
  33214. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33215. * The parameter `points` is an array successive Vector3.
  33216. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33217. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33218. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33219. * 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
  33220. * When updating an instance, remember that only point positions can change, not the number of points.
  33221. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33222. */
  33223. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33224. if (scene === void 0) { scene = null; }
  33225. var options = {
  33226. points: points,
  33227. dashSize: dashSize,
  33228. gapSize: gapSize,
  33229. dashNb: dashNb,
  33230. updatable: updatable,
  33231. instance: instance
  33232. };
  33233. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33234. };
  33235. /**
  33236. * Creates a polygon mesh.
  33237. * Please consider using the same method from the MeshBuilder class instead.
  33238. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33239. * 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.
  33240. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33242. * Remember you can only change the shape positions, not their number when updating a polygon.
  33243. */
  33244. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33245. var options = {
  33246. shape: shape,
  33247. holes: holes,
  33248. updatable: updatable,
  33249. sideOrientation: sideOrientation
  33250. };
  33251. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33252. };
  33253. /**
  33254. * Creates an extruded polygon mesh, with depth in the Y direction.
  33255. * Please consider using the same method from the MeshBuilder class instead.
  33256. */
  33257. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33258. var options = {
  33259. shape: shape,
  33260. holes: holes,
  33261. depth: depth,
  33262. updatable: updatable,
  33263. sideOrientation: sideOrientation
  33264. };
  33265. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33266. };
  33267. /**
  33268. * Creates an extruded shape mesh.
  33269. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33270. * Please consider using the same method from the MeshBuilder class instead.
  33271. *
  33272. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33273. * 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
  33274. * extruded along the Z axis.
  33275. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33276. * 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.
  33277. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33278. * 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
  33279. * 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
  33280. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33282. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33284. */
  33285. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33286. if (scene === void 0) { scene = null; }
  33287. var options = {
  33288. shape: shape,
  33289. path: path,
  33290. scale: scale,
  33291. rotation: rotation,
  33292. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33293. sideOrientation: sideOrientation,
  33294. instance: instance,
  33295. updatable: updatable
  33296. };
  33297. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33298. };
  33299. /**
  33300. * Creates an custom extruded shape mesh.
  33301. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33302. * Please consider using the same method from the MeshBuilder class instead.
  33303. *
  33304. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33305. * 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
  33306. * extruded along the Z axis.
  33307. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33308. * 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
  33309. * and the distance of this point from the begining of the path :
  33310. * ```javascript
  33311. * var rotationFunction = function(i, distance) {
  33312. * // do things
  33313. * return rotationValue; }
  33314. * ```
  33315. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33316. * 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
  33317. * and the distance of this point from the begining of the path :
  33318. * ```javascript
  33319. * var scaleFunction = function(i, distance) {
  33320. * // do things
  33321. * return scaleValue;}
  33322. * ```
  33323. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33324. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33325. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33326. * 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
  33327. * 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
  33328. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33330. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33332. */
  33333. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33334. var options = {
  33335. shape: shape,
  33336. path: path,
  33337. scaleFunction: scaleFunction,
  33338. rotationFunction: rotationFunction,
  33339. ribbonCloseArray: ribbonCloseArray,
  33340. ribbonClosePath: ribbonClosePath,
  33341. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33342. sideOrientation: sideOrientation,
  33343. instance: instance,
  33344. updatable: updatable
  33345. };
  33346. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33347. };
  33348. /**
  33349. * Creates lathe mesh.
  33350. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33351. * Please consider using the same method from the MeshBuilder class instead.
  33352. * 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
  33353. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33354. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33355. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33356. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33357. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33358. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33359. */
  33360. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33361. var options = {
  33362. shape: shape,
  33363. radius: radius,
  33364. tessellation: tessellation,
  33365. sideOrientation: sideOrientation,
  33366. updatable: updatable
  33367. };
  33368. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33369. };
  33370. /**
  33371. * Creates a plane mesh.
  33372. * Please consider using the same method from the MeshBuilder class instead.
  33373. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33374. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33375. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33376. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33377. */
  33378. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33379. var options = {
  33380. size: size,
  33381. width: size,
  33382. height: size,
  33383. sideOrientation: sideOrientation,
  33384. updatable: updatable
  33385. };
  33386. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33387. };
  33388. /**
  33389. * Creates a ground mesh.
  33390. * Please consider using the same method from the MeshBuilder class instead.
  33391. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33392. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33394. */
  33395. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33396. var options = {
  33397. width: width,
  33398. height: height,
  33399. subdivisions: subdivisions,
  33400. updatable: updatable
  33401. };
  33402. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33403. };
  33404. /**
  33405. * Creates a tiled ground mesh.
  33406. * Please consider using the same method from the MeshBuilder class instead.
  33407. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33408. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33409. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33410. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33411. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33412. * numbers of subdivisions on the ground width and height of each tile.
  33413. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33414. */
  33415. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33416. var options = {
  33417. xmin: xmin,
  33418. zmin: zmin,
  33419. xmax: xmax,
  33420. zmax: zmax,
  33421. subdivisions: subdivisions,
  33422. precision: precision,
  33423. updatable: updatable
  33424. };
  33425. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33426. };
  33427. /**
  33428. * Creates a ground mesh from a height map.
  33429. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33430. * Please consider using the same method from the MeshBuilder class instead.
  33431. * The parameter `url` sets the URL of the height map image resource.
  33432. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33433. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33434. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33435. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33436. * 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).
  33437. * This function is passed the newly built mesh :
  33438. * ```javascript
  33439. * function(mesh) { // do things
  33440. * return; }
  33441. * ```
  33442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33443. */
  33444. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33445. var options = {
  33446. width: width,
  33447. height: height,
  33448. subdivisions: subdivisions,
  33449. minHeight: minHeight,
  33450. maxHeight: maxHeight,
  33451. updatable: updatable,
  33452. onReady: onReady
  33453. };
  33454. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33455. };
  33456. /**
  33457. * Creates a tube mesh.
  33458. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33459. * Please consider using the same method from the MeshBuilder class instead.
  33460. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33461. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33462. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33463. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33464. * 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.
  33465. * It must return a radius value (positive float) :
  33466. * ```javascript
  33467. * var radiusFunction = function(i, distance) {
  33468. * // do things
  33469. * return radius; }
  33470. * ```
  33471. * 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
  33472. * 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
  33473. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33474. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33475. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33476. */
  33477. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33478. var options = {
  33479. path: path,
  33480. radius: radius,
  33481. tessellation: tessellation,
  33482. radiusFunction: radiusFunction,
  33483. arc: 1,
  33484. cap: cap,
  33485. updatable: updatable,
  33486. sideOrientation: sideOrientation,
  33487. instance: instance
  33488. };
  33489. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33490. };
  33491. /**
  33492. * Creates a polyhedron mesh.
  33493. * Please consider using the same method from the MeshBuilder class instead.
  33494. * 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
  33495. * to choose the wanted type.
  33496. * The parameter `size` (positive float, default 1) sets the polygon size.
  33497. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33498. * 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`.
  33499. * 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
  33500. * 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)`).
  33501. * 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
  33502. * 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.
  33503. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33504. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33506. */
  33507. Mesh.CreatePolyhedron = function (name, options, scene) {
  33508. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33509. };
  33510. /**
  33511. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33512. * Please consider using the same method from the MeshBuilder class instead.
  33513. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33514. * 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`).
  33515. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33516. * 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.
  33517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33518. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33520. */
  33521. Mesh.CreateIcoSphere = function (name, options, scene) {
  33522. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33523. };
  33524. /**
  33525. * Creates a decal mesh.
  33526. * Please consider using the same method from the MeshBuilder class instead.
  33527. * 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.
  33528. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33529. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33530. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33531. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33532. */
  33533. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33534. var options = {
  33535. position: position,
  33536. normal: normal,
  33537. size: size,
  33538. angle: angle
  33539. };
  33540. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33541. };
  33542. // Skeletons
  33543. /**
  33544. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33545. */
  33546. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33547. if (!this._sourcePositions) {
  33548. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33549. if (!source) {
  33550. return this._sourcePositions;
  33551. }
  33552. this._sourcePositions = new Float32Array(source);
  33553. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33554. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33555. }
  33556. }
  33557. return this._sourcePositions;
  33558. };
  33559. /**
  33560. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33561. */
  33562. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33563. if (!this._sourceNormals) {
  33564. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33565. if (!source) {
  33566. return this._sourceNormals;
  33567. }
  33568. this._sourceNormals = new Float32Array(source);
  33569. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33570. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33571. }
  33572. }
  33573. return this._sourceNormals;
  33574. };
  33575. /**
  33576. * Updates the vertex buffer by applying transformation from the bones.
  33577. * Returns the Mesh.
  33578. *
  33579. * @param {skeleton} skeleton to apply
  33580. */
  33581. Mesh.prototype.applySkeleton = function (skeleton) {
  33582. if (!this.geometry) {
  33583. return this;
  33584. }
  33585. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33586. return this;
  33587. }
  33588. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33589. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33590. return this;
  33591. }
  33592. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33593. return this;
  33594. }
  33595. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33596. return this;
  33597. }
  33598. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33599. return this;
  33600. }
  33601. if (!this._sourcePositions) {
  33602. var submeshes = this.subMeshes.slice();
  33603. this.setPositionsForCPUSkinning();
  33604. this.subMeshes = submeshes;
  33605. }
  33606. if (!this._sourceNormals) {
  33607. this.setNormalsForCPUSkinning();
  33608. }
  33609. // positionsData checks for not being Float32Array will only pass at most once
  33610. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33611. if (!positionsData) {
  33612. return this;
  33613. }
  33614. if (!(positionsData instanceof Float32Array)) {
  33615. positionsData = new Float32Array(positionsData);
  33616. }
  33617. // normalsData checks for not being Float32Array will only pass at most once
  33618. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33619. if (!normalsData) {
  33620. return this;
  33621. }
  33622. if (!(normalsData instanceof Float32Array)) {
  33623. normalsData = new Float32Array(normalsData);
  33624. }
  33625. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33626. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33627. if (!matricesWeightsData || !matricesIndicesData) {
  33628. return this;
  33629. }
  33630. var needExtras = this.numBoneInfluencers > 4;
  33631. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33632. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33633. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33634. var tempVector3 = BABYLON.Vector3.Zero();
  33635. var finalMatrix = new BABYLON.Matrix();
  33636. var tempMatrix = new BABYLON.Matrix();
  33637. var matWeightIdx = 0;
  33638. var inf;
  33639. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33640. var weight;
  33641. for (inf = 0; inf < 4; inf++) {
  33642. weight = matricesWeightsData[matWeightIdx + inf];
  33643. if (weight > 0) {
  33644. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33645. finalMatrix.addToSelf(tempMatrix);
  33646. }
  33647. else
  33648. break;
  33649. }
  33650. if (needExtras) {
  33651. for (inf = 0; inf < 4; inf++) {
  33652. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33653. if (weight > 0) {
  33654. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33655. finalMatrix.addToSelf(tempMatrix);
  33656. }
  33657. else
  33658. break;
  33659. }
  33660. }
  33661. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33662. tempVector3.toArray(positionsData, index);
  33663. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33664. tempVector3.toArray(normalsData, index);
  33665. finalMatrix.reset();
  33666. }
  33667. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33668. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33669. return this;
  33670. };
  33671. // Tools
  33672. /**
  33673. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33674. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33675. */
  33676. Mesh.MinMax = function (meshes) {
  33677. var minVector = null;
  33678. var maxVector = null;
  33679. meshes.forEach(function (mesh, index, array) {
  33680. var boundingInfo = mesh.getBoundingInfo();
  33681. var boundingBox = boundingInfo.boundingBox;
  33682. if (!minVector || !maxVector) {
  33683. minVector = boundingBox.minimumWorld;
  33684. maxVector = boundingBox.maximumWorld;
  33685. }
  33686. else {
  33687. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33688. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33689. }
  33690. });
  33691. if (!minVector || !maxVector) {
  33692. return {
  33693. min: BABYLON.Vector3.Zero(),
  33694. max: BABYLON.Vector3.Zero()
  33695. };
  33696. }
  33697. return {
  33698. min: minVector,
  33699. max: maxVector
  33700. };
  33701. };
  33702. /**
  33703. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33704. */
  33705. Mesh.Center = function (meshesOrMinMaxVector) {
  33706. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33707. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33708. };
  33709. /**
  33710. * Merge the array of meshes into a single mesh for performance reasons.
  33711. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33712. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33713. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33714. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33715. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33716. */
  33717. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33718. if (disposeSource === void 0) { disposeSource = true; }
  33719. var index;
  33720. if (!allow32BitsIndices) {
  33721. var totalVertices = 0;
  33722. // Counting vertices
  33723. for (index = 0; index < meshes.length; index++) {
  33724. if (meshes[index]) {
  33725. totalVertices += meshes[index].getTotalVertices();
  33726. if (totalVertices > 65536) {
  33727. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33728. return null;
  33729. }
  33730. }
  33731. }
  33732. }
  33733. // Merge
  33734. var vertexData = null;
  33735. var otherVertexData;
  33736. var indiceArray = new Array();
  33737. var source = null;
  33738. for (index = 0; index < meshes.length; index++) {
  33739. if (meshes[index]) {
  33740. meshes[index].computeWorldMatrix(true);
  33741. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33742. otherVertexData.transform(meshes[index].getWorldMatrix());
  33743. if (vertexData) {
  33744. vertexData.merge(otherVertexData);
  33745. }
  33746. else {
  33747. vertexData = otherVertexData;
  33748. source = meshes[index];
  33749. }
  33750. if (subdivideWithSubMeshes) {
  33751. indiceArray.push(meshes[index].getTotalIndices());
  33752. }
  33753. }
  33754. }
  33755. source = source;
  33756. if (!meshSubclass) {
  33757. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33758. }
  33759. vertexData.applyToMesh(meshSubclass);
  33760. // Setting properties
  33761. meshSubclass.material = source.material;
  33762. meshSubclass.checkCollisions = source.checkCollisions;
  33763. // Cleaning
  33764. if (disposeSource) {
  33765. for (index = 0; index < meshes.length; index++) {
  33766. if (meshes[index]) {
  33767. meshes[index].dispose();
  33768. }
  33769. }
  33770. }
  33771. // Subdivide
  33772. if (subdivideWithSubMeshes) {
  33773. //-- Suppresions du submesh global
  33774. meshSubclass.releaseSubMeshes();
  33775. index = 0;
  33776. var offset = 0;
  33777. //-- aplique la subdivision en fonction du tableau d'indices
  33778. while (index < indiceArray.length) {
  33779. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33780. offset += indiceArray[index];
  33781. index++;
  33782. }
  33783. }
  33784. return meshSubclass;
  33785. };
  33786. // Consts
  33787. Mesh._FRONTSIDE = 0;
  33788. Mesh._BACKSIDE = 1;
  33789. Mesh._DOUBLESIDE = 2;
  33790. Mesh._DEFAULTSIDE = 0;
  33791. Mesh._NO_CAP = 0;
  33792. Mesh._CAP_START = 1;
  33793. Mesh._CAP_END = 2;
  33794. Mesh._CAP_ALL = 3;
  33795. return Mesh;
  33796. }(BABYLON.AbstractMesh));
  33797. BABYLON.Mesh = Mesh;
  33798. })(BABYLON || (BABYLON = {}));
  33799. //# sourceMappingURL=babylon.mesh.js.map
  33800. var BABYLON;
  33801. (function (BABYLON) {
  33802. var BaseSubMesh = /** @class */ (function () {
  33803. function BaseSubMesh() {
  33804. }
  33805. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33806. get: function () {
  33807. return this._materialEffect;
  33808. },
  33809. enumerable: true,
  33810. configurable: true
  33811. });
  33812. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33813. if (defines === void 0) { defines = null; }
  33814. if (this._materialEffect === effect) {
  33815. if (!effect) {
  33816. this._materialDefines = null;
  33817. }
  33818. return;
  33819. }
  33820. this._materialDefines = defines;
  33821. this._materialEffect = effect;
  33822. };
  33823. return BaseSubMesh;
  33824. }());
  33825. BABYLON.BaseSubMesh = BaseSubMesh;
  33826. var SubMesh = /** @class */ (function (_super) {
  33827. __extends(SubMesh, _super);
  33828. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33829. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33830. var _this = _super.call(this) || this;
  33831. _this.materialIndex = materialIndex;
  33832. _this.verticesStart = verticesStart;
  33833. _this.verticesCount = verticesCount;
  33834. _this.indexStart = indexStart;
  33835. _this.indexCount = indexCount;
  33836. _this._renderId = 0;
  33837. _this._mesh = mesh;
  33838. _this._renderingMesh = renderingMesh || mesh;
  33839. mesh.subMeshes.push(_this);
  33840. _this._trianglePlanes = [];
  33841. _this._id = mesh.subMeshes.length - 1;
  33842. if (createBoundingBox) {
  33843. _this.refreshBoundingInfo();
  33844. mesh.computeWorldMatrix(true);
  33845. }
  33846. return _this;
  33847. }
  33848. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33849. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33850. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33851. };
  33852. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33853. get: function () {
  33854. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33855. },
  33856. enumerable: true,
  33857. configurable: true
  33858. });
  33859. /**
  33860. * Returns the submesh BoudingInfo object.
  33861. */
  33862. SubMesh.prototype.getBoundingInfo = function () {
  33863. if (this.IsGlobal) {
  33864. return this._mesh.getBoundingInfo();
  33865. }
  33866. return this._boundingInfo;
  33867. };
  33868. /**
  33869. * Sets the submesh BoundingInfo.
  33870. * Return the SubMesh.
  33871. */
  33872. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33873. this._boundingInfo = boundingInfo;
  33874. return this;
  33875. };
  33876. /**
  33877. * Returns the mesh of the current submesh.
  33878. */
  33879. SubMesh.prototype.getMesh = function () {
  33880. return this._mesh;
  33881. };
  33882. /**
  33883. * Returns the rendering mesh of the submesh.
  33884. */
  33885. SubMesh.prototype.getRenderingMesh = function () {
  33886. return this._renderingMesh;
  33887. };
  33888. /**
  33889. * Returns the submesh material.
  33890. */
  33891. SubMesh.prototype.getMaterial = function () {
  33892. var rootMaterial = this._renderingMesh.material;
  33893. if (rootMaterial === null || rootMaterial === undefined) {
  33894. return this._mesh.getScene().defaultMaterial;
  33895. }
  33896. else if (rootMaterial.getSubMaterial) {
  33897. var multiMaterial = rootMaterial;
  33898. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33899. if (this._currentMaterial !== effectiveMaterial) {
  33900. this._currentMaterial = effectiveMaterial;
  33901. this._materialDefines = null;
  33902. }
  33903. return effectiveMaterial;
  33904. }
  33905. return rootMaterial;
  33906. };
  33907. // Methods
  33908. /**
  33909. * Sets a new updated BoundingInfo object to the submesh.
  33910. * Returns the SubMesh.
  33911. */
  33912. SubMesh.prototype.refreshBoundingInfo = function () {
  33913. this._lastColliderWorldVertices = null;
  33914. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33915. return this;
  33916. }
  33917. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33918. if (!data) {
  33919. this._boundingInfo = this._mesh.getBoundingInfo();
  33920. return this;
  33921. }
  33922. var indices = this._renderingMesh.getIndices();
  33923. var extend;
  33924. //is this the only submesh?
  33925. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33926. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33927. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33928. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33929. }
  33930. else {
  33931. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33932. }
  33933. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33934. return this;
  33935. };
  33936. SubMesh.prototype._checkCollision = function (collider) {
  33937. var boundingInfo = this.getBoundingInfo();
  33938. return boundingInfo._checkCollision(collider);
  33939. };
  33940. /**
  33941. * Updates the submesh BoundingInfo.
  33942. * Returns the Submesh.
  33943. */
  33944. SubMesh.prototype.updateBoundingInfo = function (world) {
  33945. var boundingInfo = this.getBoundingInfo();
  33946. if (!boundingInfo) {
  33947. this.refreshBoundingInfo();
  33948. boundingInfo = this.getBoundingInfo();
  33949. }
  33950. boundingInfo.update(world);
  33951. return this;
  33952. };
  33953. /**
  33954. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33955. * Boolean returned.
  33956. */
  33957. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33958. var boundingInfo = this.getBoundingInfo();
  33959. if (!boundingInfo) {
  33960. return false;
  33961. }
  33962. return boundingInfo.isInFrustum(frustumPlanes);
  33963. };
  33964. /**
  33965. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33966. * Boolean returned.
  33967. */
  33968. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33969. var boundingInfo = this.getBoundingInfo();
  33970. if (!boundingInfo) {
  33971. return false;
  33972. }
  33973. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33974. };
  33975. /**
  33976. * Renders the submesh.
  33977. * Returns it.
  33978. */
  33979. SubMesh.prototype.render = function (enableAlphaMode) {
  33980. this._renderingMesh.render(this, enableAlphaMode);
  33981. return this;
  33982. };
  33983. /**
  33984. * Returns a new Index Buffer.
  33985. * Type returned : WebGLBuffer.
  33986. */
  33987. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33988. if (!this._linesIndexBuffer) {
  33989. var linesIndices = [];
  33990. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33991. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33992. }
  33993. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33994. this.linesIndexCount = linesIndices.length;
  33995. }
  33996. return this._linesIndexBuffer;
  33997. };
  33998. /**
  33999. * True is the passed Ray intersects the submesh bounding box.
  34000. * Boolean returned.
  34001. */
  34002. SubMesh.prototype.canIntersects = function (ray) {
  34003. var boundingInfo = this.getBoundingInfo();
  34004. if (!boundingInfo) {
  34005. return false;
  34006. }
  34007. return ray.intersectsBox(boundingInfo.boundingBox);
  34008. };
  34009. /**
  34010. * Returns an object IntersectionInfo.
  34011. */
  34012. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34013. var intersectInfo = null;
  34014. var material = this.getMaterial();
  34015. if (!material) {
  34016. return null;
  34017. }
  34018. switch (material.fillMode) {
  34019. case BABYLON.Material.PointListDrawMode:
  34020. case BABYLON.Material.LineListDrawMode:
  34021. case BABYLON.Material.LineLoopDrawMode:
  34022. case BABYLON.Material.LineStripDrawMode:
  34023. case BABYLON.Material.TriangleFanDrawMode:
  34024. case BABYLON.Material.TriangleStripDrawMode:
  34025. return null;
  34026. }
  34027. // LineMesh first as it's also a Mesh...
  34028. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34029. var lineMesh = this._mesh;
  34030. // Line test
  34031. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34032. var p0 = positions[indices[index]];
  34033. var p1 = positions[indices[index + 1]];
  34034. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34035. if (length < 0) {
  34036. continue;
  34037. }
  34038. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34039. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34040. if (fastCheck) {
  34041. break;
  34042. }
  34043. }
  34044. }
  34045. }
  34046. else {
  34047. // Triangles test
  34048. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34049. var p0 = positions[indices[index]];
  34050. var p1 = positions[indices[index + 1]];
  34051. var p2 = positions[indices[index + 2]];
  34052. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34053. if (currentIntersectInfo) {
  34054. if (currentIntersectInfo.distance < 0) {
  34055. continue;
  34056. }
  34057. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34058. intersectInfo = currentIntersectInfo;
  34059. intersectInfo.faceId = index / 3;
  34060. if (fastCheck) {
  34061. break;
  34062. }
  34063. }
  34064. }
  34065. }
  34066. }
  34067. return intersectInfo;
  34068. };
  34069. SubMesh.prototype._rebuild = function () {
  34070. if (this._linesIndexBuffer) {
  34071. this._linesIndexBuffer = null;
  34072. }
  34073. };
  34074. // Clone
  34075. /**
  34076. * Creates a new Submesh from the passed Mesh.
  34077. */
  34078. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34079. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34080. if (!this.IsGlobal) {
  34081. var boundingInfo = this.getBoundingInfo();
  34082. if (!boundingInfo) {
  34083. return result;
  34084. }
  34085. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34086. }
  34087. return result;
  34088. };
  34089. // Dispose
  34090. /**
  34091. * Disposes the Submesh.
  34092. * Returns nothing.
  34093. */
  34094. SubMesh.prototype.dispose = function () {
  34095. if (this._linesIndexBuffer) {
  34096. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34097. this._linesIndexBuffer = null;
  34098. }
  34099. // Remove from mesh
  34100. var index = this._mesh.subMeshes.indexOf(this);
  34101. this._mesh.subMeshes.splice(index, 1);
  34102. };
  34103. // Statics
  34104. /**
  34105. * Creates a new Submesh from the passed parameters :
  34106. * - materialIndex (integer) : the index of the main mesh material.
  34107. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34108. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34109. * - mesh (Mesh) : the main mesh to create the submesh from.
  34110. * - renderingMesh (optional Mesh) : rendering mesh.
  34111. */
  34112. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34113. var minVertexIndex = Number.MAX_VALUE;
  34114. var maxVertexIndex = -Number.MAX_VALUE;
  34115. renderingMesh = (renderingMesh || mesh);
  34116. var indices = renderingMesh.getIndices();
  34117. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34118. var vertexIndex = indices[index];
  34119. if (vertexIndex < minVertexIndex)
  34120. minVertexIndex = vertexIndex;
  34121. if (vertexIndex > maxVertexIndex)
  34122. maxVertexIndex = vertexIndex;
  34123. }
  34124. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34125. };
  34126. return SubMesh;
  34127. }(BaseSubMesh));
  34128. BABYLON.SubMesh = SubMesh;
  34129. })(BABYLON || (BABYLON = {}));
  34130. //# sourceMappingURL=babylon.subMesh.js.map
  34131. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34132. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34133. s = arguments[i];
  34134. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34135. t[p] = s[p];
  34136. }
  34137. return t;
  34138. };
  34139. var BABYLON;
  34140. (function (BABYLON) {
  34141. /**
  34142. * Manages the defines for the Material
  34143. */
  34144. var MaterialDefines = /** @class */ (function () {
  34145. function MaterialDefines() {
  34146. this._isDirty = true;
  34147. /** @hidden */
  34148. this._areLightsDirty = true;
  34149. /** @hidden */
  34150. this._areAttributesDirty = true;
  34151. /** @hidden */
  34152. this._areTexturesDirty = true;
  34153. /** @hidden */
  34154. this._areFresnelDirty = true;
  34155. /** @hidden */
  34156. this._areMiscDirty = true;
  34157. /** @hidden */
  34158. this._areImageProcessingDirty = true;
  34159. /** @hidden */
  34160. this._normals = false;
  34161. /** @hidden */
  34162. this._uvs = false;
  34163. /** @hidden */
  34164. this._needNormals = false;
  34165. /** @hidden */
  34166. this._needUVs = false;
  34167. }
  34168. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34169. /**
  34170. * Specifies if the material needs to be re-calculated
  34171. */
  34172. get: function () {
  34173. return this._isDirty;
  34174. },
  34175. enumerable: true,
  34176. configurable: true
  34177. });
  34178. /**
  34179. * Marks the material to indicate that it has been re-calculated
  34180. */
  34181. MaterialDefines.prototype.markAsProcessed = function () {
  34182. this._isDirty = false;
  34183. this._areAttributesDirty = false;
  34184. this._areTexturesDirty = false;
  34185. this._areFresnelDirty = false;
  34186. this._areLightsDirty = false;
  34187. this._areMiscDirty = false;
  34188. this._areImageProcessingDirty = false;
  34189. };
  34190. /**
  34191. * Marks the material to indicate that it needs to be re-calculated
  34192. */
  34193. MaterialDefines.prototype.markAsUnprocessed = function () {
  34194. this._isDirty = true;
  34195. };
  34196. /**
  34197. * Marks the material to indicate all of its defines need to be re-calculated
  34198. */
  34199. MaterialDefines.prototype.markAllAsDirty = function () {
  34200. this._areTexturesDirty = true;
  34201. this._areAttributesDirty = true;
  34202. this._areLightsDirty = true;
  34203. this._areFresnelDirty = true;
  34204. this._areMiscDirty = true;
  34205. this._areImageProcessingDirty = true;
  34206. this._isDirty = true;
  34207. };
  34208. /**
  34209. * Marks the material to indicate that image processing needs to be re-calculated
  34210. */
  34211. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34212. this._areImageProcessingDirty = true;
  34213. this._isDirty = true;
  34214. };
  34215. /**
  34216. * Marks the material to indicate the lights need to be re-calculated
  34217. */
  34218. MaterialDefines.prototype.markAsLightDirty = function () {
  34219. this._areLightsDirty = true;
  34220. this._isDirty = true;
  34221. };
  34222. /**
  34223. * Marks the attribute state as changed
  34224. */
  34225. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34226. this._areAttributesDirty = true;
  34227. this._isDirty = true;
  34228. };
  34229. /**
  34230. * Marks the texture state as changed
  34231. */
  34232. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34233. this._areTexturesDirty = true;
  34234. this._isDirty = true;
  34235. };
  34236. /**
  34237. * Marks the fresnel state as changed
  34238. */
  34239. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34240. this._areFresnelDirty = true;
  34241. this._isDirty = true;
  34242. };
  34243. /**
  34244. * Marks the misc state as changed
  34245. */
  34246. MaterialDefines.prototype.markAsMiscDirty = function () {
  34247. this._areMiscDirty = true;
  34248. this._isDirty = true;
  34249. };
  34250. /**
  34251. * Rebuilds the material defines
  34252. */
  34253. MaterialDefines.prototype.rebuild = function () {
  34254. if (this._keys) {
  34255. delete this._keys;
  34256. }
  34257. this._keys = [];
  34258. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34259. var key = _a[_i];
  34260. if (key[0] === "_") {
  34261. continue;
  34262. }
  34263. this._keys.push(key);
  34264. }
  34265. };
  34266. /**
  34267. * Specifies if two material defines are equal
  34268. * @param other - A material define instance to compare to
  34269. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34270. */
  34271. MaterialDefines.prototype.isEqual = function (other) {
  34272. if (this._keys.length !== other._keys.length) {
  34273. return false;
  34274. }
  34275. for (var index = 0; index < this._keys.length; index++) {
  34276. var prop = this._keys[index];
  34277. if (this[prop] !== other[prop]) {
  34278. return false;
  34279. }
  34280. }
  34281. return true;
  34282. };
  34283. /**
  34284. * Clones this instance's defines to another instance
  34285. * @param other - material defines to clone values to
  34286. */
  34287. MaterialDefines.prototype.cloneTo = function (other) {
  34288. if (this._keys.length !== other._keys.length) {
  34289. other._keys = this._keys.slice(0);
  34290. }
  34291. for (var index = 0; index < this._keys.length; index++) {
  34292. var prop = this._keys[index];
  34293. other[prop] = this[prop];
  34294. }
  34295. };
  34296. /**
  34297. * Resets the material define values
  34298. */
  34299. MaterialDefines.prototype.reset = function () {
  34300. for (var index = 0; index < this._keys.length; index++) {
  34301. var prop = this._keys[index];
  34302. var type = typeof this[prop];
  34303. switch (type) {
  34304. case "number":
  34305. this[prop] = 0;
  34306. break;
  34307. case "string":
  34308. this[prop] = "";
  34309. break;
  34310. default:
  34311. this[prop] = false;
  34312. break;
  34313. }
  34314. }
  34315. };
  34316. /**
  34317. * Converts the material define values to a string
  34318. * @returns - String of material define information
  34319. */
  34320. MaterialDefines.prototype.toString = function () {
  34321. var result = "";
  34322. for (var index = 0; index < this._keys.length; index++) {
  34323. var prop = this._keys[index];
  34324. var value = this[prop];
  34325. var type = typeof value;
  34326. switch (type) {
  34327. case "number":
  34328. case "string":
  34329. result += "#define " + prop + " " + value + "\n";
  34330. break;
  34331. default:
  34332. if (value) {
  34333. result += "#define " + prop + "\n";
  34334. }
  34335. break;
  34336. }
  34337. }
  34338. return result;
  34339. };
  34340. return MaterialDefines;
  34341. }());
  34342. BABYLON.MaterialDefines = MaterialDefines;
  34343. /**
  34344. * Base class for the main features of a material in Babylon.js
  34345. */
  34346. var Material = /** @class */ (function () {
  34347. /**
  34348. * Creates a material instance
  34349. * @param name defines the name of the material
  34350. * @param scene defines the scene to reference
  34351. * @param doNotAdd specifies if the material should be added to the scene
  34352. */
  34353. function Material(name, scene, doNotAdd) {
  34354. /**
  34355. * Specifies if the ready state should be checked on each call
  34356. */
  34357. this.checkReadyOnEveryCall = false;
  34358. /**
  34359. * Specifies if the ready state should be checked once
  34360. */
  34361. this.checkReadyOnlyOnce = false;
  34362. /**
  34363. * The state of the material
  34364. */
  34365. this.state = "";
  34366. /**
  34367. * The alpha value of the material
  34368. */
  34369. this._alpha = 1.0;
  34370. /**
  34371. * Specifies if back face culling is enabled
  34372. */
  34373. this._backFaceCulling = true;
  34374. /**
  34375. * Specifies if the material should be serialized
  34376. */
  34377. this.doNotSerialize = false;
  34378. /**
  34379. * Specifies if the effect should be stored on sub meshes
  34380. */
  34381. this.storeEffectOnSubMeshes = false;
  34382. /**
  34383. * An event triggered when the material is disposed
  34384. */
  34385. this.onDisposeObservable = new BABYLON.Observable();
  34386. /**
  34387. * An event triggered when the material is bound
  34388. */
  34389. this.onBindObservable = new BABYLON.Observable();
  34390. /**
  34391. * An event triggered when the material is unbound
  34392. */
  34393. this.onUnBindObservable = new BABYLON.Observable();
  34394. /**
  34395. * Stores the value of the alpha mode
  34396. */
  34397. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34398. /**
  34399. * Stores the state of the need depth pre-pass value
  34400. */
  34401. this._needDepthPrePass = false;
  34402. /**
  34403. * Specifies if depth writing should be disabled
  34404. */
  34405. this.disableDepthWrite = false;
  34406. /**
  34407. * Specifies if depth writing should be forced
  34408. */
  34409. this.forceDepthWrite = false;
  34410. /**
  34411. * Specifies if there should be a separate pass for culling
  34412. */
  34413. this.separateCullingPass = false;
  34414. /**
  34415. * Stores the state specifing if fog should be enabled
  34416. */
  34417. this._fogEnabled = true;
  34418. /**
  34419. * Stores the size of points
  34420. */
  34421. this.pointSize = 1.0;
  34422. /**
  34423. * Stores the z offset value
  34424. */
  34425. this.zOffset = 0;
  34426. /**
  34427. * Specifies if the material was previously ready
  34428. */
  34429. this._wasPreviouslyReady = false;
  34430. /**
  34431. * Stores the fill mode state
  34432. */
  34433. this._fillMode = Material.TriangleFillMode;
  34434. this.name = name;
  34435. this.id = name || BABYLON.Tools.RandomId();
  34436. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34437. if (this._scene.useRightHandedSystem) {
  34438. this.sideOrientation = Material.ClockWiseSideOrientation;
  34439. }
  34440. else {
  34441. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34442. }
  34443. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34444. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34445. if (!doNotAdd) {
  34446. this._scene.materials.push(this);
  34447. }
  34448. }
  34449. Object.defineProperty(Material, "TriangleFillMode", {
  34450. /**
  34451. * Returns the triangle fill mode
  34452. */
  34453. get: function () {
  34454. return Material._TriangleFillMode;
  34455. },
  34456. enumerable: true,
  34457. configurable: true
  34458. });
  34459. Object.defineProperty(Material, "WireFrameFillMode", {
  34460. /**
  34461. * Returns the wireframe mode
  34462. */
  34463. get: function () {
  34464. return Material._WireFrameFillMode;
  34465. },
  34466. enumerable: true,
  34467. configurable: true
  34468. });
  34469. Object.defineProperty(Material, "PointFillMode", {
  34470. /**
  34471. * Returns the point fill mode
  34472. */
  34473. get: function () {
  34474. return Material._PointFillMode;
  34475. },
  34476. enumerable: true,
  34477. configurable: true
  34478. });
  34479. Object.defineProperty(Material, "PointListDrawMode", {
  34480. /**
  34481. * Returns the point list draw mode
  34482. */
  34483. get: function () {
  34484. return Material._PointListDrawMode;
  34485. },
  34486. enumerable: true,
  34487. configurable: true
  34488. });
  34489. Object.defineProperty(Material, "LineListDrawMode", {
  34490. /**
  34491. * Returns the line list draw mode
  34492. */
  34493. get: function () {
  34494. return Material._LineListDrawMode;
  34495. },
  34496. enumerable: true,
  34497. configurable: true
  34498. });
  34499. Object.defineProperty(Material, "LineLoopDrawMode", {
  34500. /**
  34501. * Returns the line loop draw mode
  34502. */
  34503. get: function () {
  34504. return Material._LineLoopDrawMode;
  34505. },
  34506. enumerable: true,
  34507. configurable: true
  34508. });
  34509. Object.defineProperty(Material, "LineStripDrawMode", {
  34510. /**
  34511. * Returns the line strip draw mode
  34512. */
  34513. get: function () {
  34514. return Material._LineStripDrawMode;
  34515. },
  34516. enumerable: true,
  34517. configurable: true
  34518. });
  34519. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34520. /**
  34521. * Returns the triangle strip draw mode
  34522. */
  34523. get: function () {
  34524. return Material._TriangleStripDrawMode;
  34525. },
  34526. enumerable: true,
  34527. configurable: true
  34528. });
  34529. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34530. /**
  34531. * Returns the triangle fan draw mode
  34532. */
  34533. get: function () {
  34534. return Material._TriangleFanDrawMode;
  34535. },
  34536. enumerable: true,
  34537. configurable: true
  34538. });
  34539. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34540. /**
  34541. * Returns the clock-wise side orientation
  34542. */
  34543. get: function () {
  34544. return Material._ClockWiseSideOrientation;
  34545. },
  34546. enumerable: true,
  34547. configurable: true
  34548. });
  34549. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34550. /**
  34551. * Returns the counter clock-wise side orientation
  34552. */
  34553. get: function () {
  34554. return Material._CounterClockWiseSideOrientation;
  34555. },
  34556. enumerable: true,
  34557. configurable: true
  34558. });
  34559. Object.defineProperty(Material, "TextureDirtyFlag", {
  34560. /**
  34561. * Returns the dirty texture flag value
  34562. */
  34563. get: function () {
  34564. return Material._TextureDirtyFlag;
  34565. },
  34566. enumerable: true,
  34567. configurable: true
  34568. });
  34569. Object.defineProperty(Material, "LightDirtyFlag", {
  34570. /**
  34571. * Returns the dirty light flag value
  34572. */
  34573. get: function () {
  34574. return Material._LightDirtyFlag;
  34575. },
  34576. enumerable: true,
  34577. configurable: true
  34578. });
  34579. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34580. /**
  34581. * Returns the dirty fresnel flag value
  34582. */
  34583. get: function () {
  34584. return Material._FresnelDirtyFlag;
  34585. },
  34586. enumerable: true,
  34587. configurable: true
  34588. });
  34589. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34590. /**
  34591. * Returns the dirty attributes flag value
  34592. */
  34593. get: function () {
  34594. return Material._AttributesDirtyFlag;
  34595. },
  34596. enumerable: true,
  34597. configurable: true
  34598. });
  34599. Object.defineProperty(Material, "MiscDirtyFlag", {
  34600. /**
  34601. * Returns the dirty misc flag value
  34602. */
  34603. get: function () {
  34604. return Material._MiscDirtyFlag;
  34605. },
  34606. enumerable: true,
  34607. configurable: true
  34608. });
  34609. Object.defineProperty(Material.prototype, "alpha", {
  34610. /**
  34611. * Gets the alpha value of the material
  34612. */
  34613. get: function () {
  34614. return this._alpha;
  34615. },
  34616. /**
  34617. * Sets the alpha value of the material
  34618. */
  34619. set: function (value) {
  34620. if (this._alpha === value) {
  34621. return;
  34622. }
  34623. this._alpha = value;
  34624. this.markAsDirty(Material.MiscDirtyFlag);
  34625. },
  34626. enumerable: true,
  34627. configurable: true
  34628. });
  34629. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34630. /**
  34631. * Gets the back-face culling state
  34632. */
  34633. get: function () {
  34634. return this._backFaceCulling;
  34635. },
  34636. /**
  34637. * Sets the back-face culling state
  34638. */
  34639. set: function (value) {
  34640. if (this._backFaceCulling === value) {
  34641. return;
  34642. }
  34643. this._backFaceCulling = value;
  34644. this.markAsDirty(Material.TextureDirtyFlag);
  34645. },
  34646. enumerable: true,
  34647. configurable: true
  34648. });
  34649. Object.defineProperty(Material.prototype, "onDispose", {
  34650. /**
  34651. * Called during a dispose event
  34652. */
  34653. set: function (callback) {
  34654. if (this._onDisposeObserver) {
  34655. this.onDisposeObservable.remove(this._onDisposeObserver);
  34656. }
  34657. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34658. },
  34659. enumerable: true,
  34660. configurable: true
  34661. });
  34662. Object.defineProperty(Material.prototype, "onBind", {
  34663. /**
  34664. * Called during a bind event
  34665. */
  34666. set: function (callback) {
  34667. if (this._onBindObserver) {
  34668. this.onBindObservable.remove(this._onBindObserver);
  34669. }
  34670. this._onBindObserver = this.onBindObservable.add(callback);
  34671. },
  34672. enumerable: true,
  34673. configurable: true
  34674. });
  34675. Object.defineProperty(Material.prototype, "alphaMode", {
  34676. /**
  34677. * Gets the value of the alpha mode
  34678. */
  34679. get: function () {
  34680. return this._alphaMode;
  34681. },
  34682. /**
  34683. * Sets the value of the alpha mode.
  34684. *
  34685. * | Value | Type | Description |
  34686. * | --- | --- | --- |
  34687. * | 0 | ALPHA_DISABLE | |
  34688. * | 1 | ALPHA_ADD | |
  34689. * | 2 | ALPHA_COMBINE | |
  34690. * | 3 | ALPHA_SUBTRACT | |
  34691. * | 4 | ALPHA_MULTIPLY | |
  34692. * | 5 | ALPHA_MAXIMIZED | |
  34693. * | 6 | ALPHA_ONEONE | |
  34694. * | 7 | ALPHA_PREMULTIPLIED | |
  34695. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34696. * | 9 | ALPHA_INTERPOLATE | |
  34697. * | 10 | ALPHA_SCREENMODE | |
  34698. *
  34699. */
  34700. set: function (value) {
  34701. if (this._alphaMode === value) {
  34702. return;
  34703. }
  34704. this._alphaMode = value;
  34705. this.markAsDirty(Material.TextureDirtyFlag);
  34706. },
  34707. enumerable: true,
  34708. configurable: true
  34709. });
  34710. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34711. /**
  34712. * Gets the depth pre-pass value
  34713. */
  34714. get: function () {
  34715. return this._needDepthPrePass;
  34716. },
  34717. /**
  34718. * Sets the need depth pre-pass value
  34719. */
  34720. set: function (value) {
  34721. if (this._needDepthPrePass === value) {
  34722. return;
  34723. }
  34724. this._needDepthPrePass = value;
  34725. if (this._needDepthPrePass) {
  34726. this.checkReadyOnEveryCall = true;
  34727. }
  34728. },
  34729. enumerable: true,
  34730. configurable: true
  34731. });
  34732. Object.defineProperty(Material.prototype, "fogEnabled", {
  34733. /**
  34734. * Gets the value of the fog enabled state
  34735. */
  34736. get: function () {
  34737. return this._fogEnabled;
  34738. },
  34739. /**
  34740. * Sets the state for enabling fog
  34741. */
  34742. set: function (value) {
  34743. if (this._fogEnabled === value) {
  34744. return;
  34745. }
  34746. this._fogEnabled = value;
  34747. this.markAsDirty(Material.MiscDirtyFlag);
  34748. },
  34749. enumerable: true,
  34750. configurable: true
  34751. });
  34752. Object.defineProperty(Material.prototype, "wireframe", {
  34753. /**
  34754. * Gets a value specifying if wireframe mode is enabled
  34755. */
  34756. get: function () {
  34757. switch (this._fillMode) {
  34758. case Material.WireFrameFillMode:
  34759. case Material.LineListDrawMode:
  34760. case Material.LineLoopDrawMode:
  34761. case Material.LineStripDrawMode:
  34762. return true;
  34763. }
  34764. return this._scene.forceWireframe;
  34765. },
  34766. /**
  34767. * Sets the state of wireframe mode
  34768. */
  34769. set: function (value) {
  34770. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34771. },
  34772. enumerable: true,
  34773. configurable: true
  34774. });
  34775. Object.defineProperty(Material.prototype, "pointsCloud", {
  34776. /**
  34777. * Gets the value specifying if point clouds are enabled
  34778. */
  34779. get: function () {
  34780. switch (this._fillMode) {
  34781. case Material.PointFillMode:
  34782. case Material.PointListDrawMode:
  34783. return true;
  34784. }
  34785. return this._scene.forcePointsCloud;
  34786. },
  34787. /**
  34788. * Sets the state of point cloud mode
  34789. */
  34790. set: function (value) {
  34791. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34792. },
  34793. enumerable: true,
  34794. configurable: true
  34795. });
  34796. Object.defineProperty(Material.prototype, "fillMode", {
  34797. /**
  34798. * Gets the material fill mode
  34799. */
  34800. get: function () {
  34801. return this._fillMode;
  34802. },
  34803. /**
  34804. * Sets the material fill mode
  34805. */
  34806. set: function (value) {
  34807. if (this._fillMode === value) {
  34808. return;
  34809. }
  34810. this._fillMode = value;
  34811. this.markAsDirty(Material.MiscDirtyFlag);
  34812. },
  34813. enumerable: true,
  34814. configurable: true
  34815. });
  34816. /**
  34817. * Returns a string representation of the current material
  34818. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34819. * @returns a string with material information
  34820. */
  34821. Material.prototype.toString = function (fullDetails) {
  34822. var ret = "Name: " + this.name;
  34823. if (fullDetails) {
  34824. }
  34825. return ret;
  34826. };
  34827. /**
  34828. * Gets the class name of the material
  34829. * @returns a string with the class name of the material
  34830. */
  34831. Material.prototype.getClassName = function () {
  34832. return "Material";
  34833. };
  34834. Object.defineProperty(Material.prototype, "isFrozen", {
  34835. /**
  34836. * Specifies if updates for the material been locked
  34837. */
  34838. get: function () {
  34839. return this.checkReadyOnlyOnce;
  34840. },
  34841. enumerable: true,
  34842. configurable: true
  34843. });
  34844. /**
  34845. * Locks updates for the material
  34846. */
  34847. Material.prototype.freeze = function () {
  34848. this.checkReadyOnlyOnce = true;
  34849. };
  34850. /**
  34851. * Unlocks updates for the material
  34852. */
  34853. Material.prototype.unfreeze = function () {
  34854. this.checkReadyOnlyOnce = false;
  34855. };
  34856. /**
  34857. * Specifies if the material is ready to be used
  34858. * @param mesh defines the mesh to check
  34859. * @param useInstances specifies if instances should be used
  34860. * @returns a boolean indicating if the material is ready to be used
  34861. */
  34862. Material.prototype.isReady = function (mesh, useInstances) {
  34863. return true;
  34864. };
  34865. /**
  34866. * Specifies that the submesh is ready to be used
  34867. * @param mesh defines the mesh to check
  34868. * @param subMesh defines which submesh to check
  34869. * @param useInstances specifies that instances should be used
  34870. * @returns a boolean indicating that the submesh is ready or not
  34871. */
  34872. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34873. return false;
  34874. };
  34875. /**
  34876. * Returns the material effect
  34877. * @returns the effect associated with the material
  34878. */
  34879. Material.prototype.getEffect = function () {
  34880. return this._effect;
  34881. };
  34882. /**
  34883. * Returns the current scene
  34884. * @returns a Scene
  34885. */
  34886. Material.prototype.getScene = function () {
  34887. return this._scene;
  34888. };
  34889. /**
  34890. * Specifies if the material will require alpha blending
  34891. * @returns a boolean specifying if alpha blending is needed
  34892. */
  34893. Material.prototype.needAlphaBlending = function () {
  34894. return (this.alpha < 1.0);
  34895. };
  34896. /**
  34897. * Specifies if the mesh will require alpha blending
  34898. * @param mesh defines the mesh to check
  34899. * @returns a boolean specifying if alpha blending is needed for the mesh
  34900. */
  34901. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34902. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34903. };
  34904. /**
  34905. * Specifies if this material should be rendered in alpha test mode
  34906. * @returns a boolean specifying if an alpha test is needed.
  34907. */
  34908. Material.prototype.needAlphaTesting = function () {
  34909. return false;
  34910. };
  34911. /**
  34912. * Gets the texture used for the alpha test
  34913. * @returns the texture to use for alpha testing
  34914. */
  34915. Material.prototype.getAlphaTestTexture = function () {
  34916. return null;
  34917. };
  34918. /**
  34919. * Marks the material to indicate that it needs to be re-calculated
  34920. */
  34921. Material.prototype.markDirty = function () {
  34922. this._wasPreviouslyReady = false;
  34923. };
  34924. /** @hidden */
  34925. Material.prototype._preBind = function (effect, overrideOrientation) {
  34926. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34927. var engine = this._scene.getEngine();
  34928. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34929. var reverse = orientation === Material.ClockWiseSideOrientation;
  34930. engine.enableEffect(effect ? effect : this._effect);
  34931. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34932. return reverse;
  34933. };
  34934. /**
  34935. * Binds the material to the mesh
  34936. * @param world defines the world transformation matrix
  34937. * @param mesh defines the mesh to bind the material to
  34938. */
  34939. Material.prototype.bind = function (world, mesh) {
  34940. };
  34941. /**
  34942. * Binds the submesh to the material
  34943. * @param world defines the world transformation matrix
  34944. * @param mesh defines the mesh containing the submesh
  34945. * @param subMesh defines the submesh to bind the material to
  34946. */
  34947. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34948. };
  34949. /**
  34950. * Binds the world matrix to the material
  34951. * @param world defines the world transformation matrix
  34952. */
  34953. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34954. };
  34955. /**
  34956. * Binds the scene's uniform buffer to the effect.
  34957. * @param effect defines the effect to bind to the scene uniform buffer
  34958. * @param sceneUbo defines the uniform buffer storing scene data
  34959. */
  34960. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34961. sceneUbo.bindToEffect(effect, "Scene");
  34962. };
  34963. /**
  34964. * Binds the view matrix to the effect
  34965. * @param effect defines the effect to bind the view matrix to
  34966. */
  34967. Material.prototype.bindView = function (effect) {
  34968. if (!this._useUBO) {
  34969. effect.setMatrix("view", this.getScene().getViewMatrix());
  34970. }
  34971. else {
  34972. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34973. }
  34974. };
  34975. /**
  34976. * Binds the view projection matrix to the effect
  34977. * @param effect defines the effect to bind the view projection matrix to
  34978. */
  34979. Material.prototype.bindViewProjection = function (effect) {
  34980. if (!this._useUBO) {
  34981. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34982. }
  34983. else {
  34984. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34985. }
  34986. };
  34987. /**
  34988. * Specifies if material alpha testing should be turned on for the mesh
  34989. * @param mesh defines the mesh to check
  34990. */
  34991. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34992. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34993. };
  34994. /**
  34995. * Processes to execute after binding the material to a mesh
  34996. * @param mesh defines the rendered mesh
  34997. */
  34998. Material.prototype._afterBind = function (mesh) {
  34999. this._scene._cachedMaterial = this;
  35000. if (mesh) {
  35001. this._scene._cachedVisibility = mesh.visibility;
  35002. }
  35003. else {
  35004. this._scene._cachedVisibility = 1;
  35005. }
  35006. if (mesh) {
  35007. this.onBindObservable.notifyObservers(mesh);
  35008. }
  35009. if (this.disableDepthWrite) {
  35010. var engine = this._scene.getEngine();
  35011. this._cachedDepthWriteState = engine.getDepthWrite();
  35012. engine.setDepthWrite(false);
  35013. }
  35014. };
  35015. /**
  35016. * Unbinds the material from the mesh
  35017. */
  35018. Material.prototype.unbind = function () {
  35019. this.onUnBindObservable.notifyObservers(this);
  35020. if (this.disableDepthWrite) {
  35021. var engine = this._scene.getEngine();
  35022. engine.setDepthWrite(this._cachedDepthWriteState);
  35023. }
  35024. };
  35025. /**
  35026. * Gets the active textures from the material
  35027. * @returns an array of textures
  35028. */
  35029. Material.prototype.getActiveTextures = function () {
  35030. return [];
  35031. };
  35032. /**
  35033. * Specifies if the material uses a texture
  35034. * @param texture defines the texture to check against the material
  35035. * @returns a boolean specifying if the material uses the texture
  35036. */
  35037. Material.prototype.hasTexture = function (texture) {
  35038. return false;
  35039. };
  35040. /**
  35041. * Makes a duplicate of the material, and gives it a new name
  35042. * @param name defines the new name for the duplicated material
  35043. * @returns the cloned material
  35044. */
  35045. Material.prototype.clone = function (name) {
  35046. return null;
  35047. };
  35048. /**
  35049. * Gets the meshes bound to the material
  35050. * @returns an array of meshes bound to the material
  35051. */
  35052. Material.prototype.getBindedMeshes = function () {
  35053. var result = new Array();
  35054. for (var index = 0; index < this._scene.meshes.length; index++) {
  35055. var mesh = this._scene.meshes[index];
  35056. if (mesh.material === this) {
  35057. result.push(mesh);
  35058. }
  35059. }
  35060. return result;
  35061. };
  35062. /**
  35063. * Force shader compilation
  35064. * @param mesh defines the mesh associated with this material
  35065. * @param onCompiled defines a function to execute once the material is compiled
  35066. * @param options defines the options to configure the compilation
  35067. */
  35068. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35069. var _this = this;
  35070. var localOptions = __assign({ clipPlane: false }, options);
  35071. var subMesh = new BABYLON.BaseSubMesh();
  35072. var scene = this.getScene();
  35073. var checkReady = function () {
  35074. if (!_this._scene || !_this._scene.getEngine()) {
  35075. return;
  35076. }
  35077. if (subMesh._materialDefines) {
  35078. subMesh._materialDefines._renderId = -1;
  35079. }
  35080. var clipPlaneState = scene.clipPlane;
  35081. if (localOptions.clipPlane) {
  35082. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35083. }
  35084. if (_this.storeEffectOnSubMeshes) {
  35085. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35086. if (onCompiled) {
  35087. onCompiled(_this);
  35088. }
  35089. }
  35090. else {
  35091. setTimeout(checkReady, 16);
  35092. }
  35093. }
  35094. else {
  35095. if (_this.isReady(mesh)) {
  35096. if (onCompiled) {
  35097. onCompiled(_this);
  35098. }
  35099. }
  35100. else {
  35101. setTimeout(checkReady, 16);
  35102. }
  35103. }
  35104. if (localOptions.clipPlane) {
  35105. scene.clipPlane = clipPlaneState;
  35106. }
  35107. };
  35108. checkReady();
  35109. };
  35110. /**
  35111. * Force shader compilation
  35112. * @param mesh defines the mesh that will use this material
  35113. * @param options defines additional options for compiling the shaders
  35114. * @returns a promise that resolves when the compilation completes
  35115. */
  35116. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35117. var _this = this;
  35118. return new Promise(function (resolve) {
  35119. _this.forceCompilation(mesh, function () {
  35120. resolve();
  35121. }, options);
  35122. });
  35123. };
  35124. /**
  35125. * Marks a define in the material to indicate that it needs to be re-computed
  35126. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35127. */
  35128. Material.prototype.markAsDirty = function (flag) {
  35129. if (flag & Material.TextureDirtyFlag) {
  35130. this._markAllSubMeshesAsTexturesDirty();
  35131. }
  35132. if (flag & Material.LightDirtyFlag) {
  35133. this._markAllSubMeshesAsLightsDirty();
  35134. }
  35135. if (flag & Material.FresnelDirtyFlag) {
  35136. this._markAllSubMeshesAsFresnelDirty();
  35137. }
  35138. if (flag & Material.AttributesDirtyFlag) {
  35139. this._markAllSubMeshesAsAttributesDirty();
  35140. }
  35141. if (flag & Material.MiscDirtyFlag) {
  35142. this._markAllSubMeshesAsMiscDirty();
  35143. }
  35144. this.getScene().resetCachedMaterial();
  35145. };
  35146. /**
  35147. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35148. * @param func defines a function which checks material defines against the submeshes
  35149. */
  35150. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35151. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35152. var mesh = _a[_i];
  35153. if (!mesh.subMeshes) {
  35154. continue;
  35155. }
  35156. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35157. var subMesh = _c[_b];
  35158. if (subMesh.getMaterial() !== this) {
  35159. continue;
  35160. }
  35161. if (!subMesh._materialDefines) {
  35162. continue;
  35163. }
  35164. func(subMesh._materialDefines);
  35165. }
  35166. }
  35167. };
  35168. /**
  35169. * Indicates that image processing needs to be re-calculated for all submeshes
  35170. */
  35171. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35172. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35173. };
  35174. /**
  35175. * Indicates that textures need to be re-calculated for all submeshes
  35176. */
  35177. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35178. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35179. };
  35180. /**
  35181. * Indicates that fresnel needs to be re-calculated for all submeshes
  35182. */
  35183. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35184. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35185. };
  35186. /**
  35187. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35188. */
  35189. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35190. this._markAllSubMeshesAsDirty(function (defines) {
  35191. defines.markAsFresnelDirty();
  35192. defines.markAsMiscDirty();
  35193. });
  35194. };
  35195. /**
  35196. * Indicates that lights need to be re-calculated for all submeshes
  35197. */
  35198. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35199. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35200. };
  35201. /**
  35202. * Indicates that attributes need to be re-calculated for all submeshes
  35203. */
  35204. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35205. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35206. };
  35207. /**
  35208. * Indicates that misc needs to be re-calculated for all submeshes
  35209. */
  35210. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35211. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35212. };
  35213. /**
  35214. * Indicates that textures and misc need to be re-calculated for all submeshes
  35215. */
  35216. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35217. this._markAllSubMeshesAsDirty(function (defines) {
  35218. defines.markAsTexturesDirty();
  35219. defines.markAsMiscDirty();
  35220. });
  35221. };
  35222. /**
  35223. * Disposes the material
  35224. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35225. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35226. */
  35227. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35228. // Animations
  35229. this.getScene().stopAnimation(this);
  35230. this.getScene().freeProcessedMaterials();
  35231. // Remove from scene
  35232. var index = this._scene.materials.indexOf(this);
  35233. if (index >= 0) {
  35234. this._scene.materials.splice(index, 1);
  35235. }
  35236. // Remove from meshes
  35237. for (index = 0; index < this._scene.meshes.length; index++) {
  35238. var mesh = this._scene.meshes[index];
  35239. if (mesh.material === this) {
  35240. mesh.material = null;
  35241. if (mesh.geometry) {
  35242. var geometry = (mesh.geometry);
  35243. if (this.storeEffectOnSubMeshes) {
  35244. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35245. var subMesh = _a[_i];
  35246. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35247. if (forceDisposeEffect && subMesh._materialEffect) {
  35248. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35249. }
  35250. }
  35251. }
  35252. else {
  35253. geometry._releaseVertexArrayObject(this._effect);
  35254. }
  35255. }
  35256. }
  35257. }
  35258. this._uniformBuffer.dispose();
  35259. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35260. if (forceDisposeEffect && this._effect) {
  35261. if (!this.storeEffectOnSubMeshes) {
  35262. this._scene.getEngine()._releaseEffect(this._effect);
  35263. }
  35264. this._effect = null;
  35265. }
  35266. // Callback
  35267. this.onDisposeObservable.notifyObservers(this);
  35268. this.onDisposeObservable.clear();
  35269. this.onBindObservable.clear();
  35270. this.onUnBindObservable.clear();
  35271. };
  35272. /**
  35273. * Serializes this material
  35274. * @returns the serialized material object
  35275. */
  35276. Material.prototype.serialize = function () {
  35277. return BABYLON.SerializationHelper.Serialize(this);
  35278. };
  35279. /**
  35280. * Creates a MultiMaterial from parsed MultiMaterial data.
  35281. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35282. * @param scene defines the hosting scene
  35283. * @returns a new MultiMaterial
  35284. */
  35285. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35286. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35287. multiMaterial.id = parsedMultiMaterial.id;
  35288. if (BABYLON.Tags) {
  35289. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35290. }
  35291. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35292. var subMatId = parsedMultiMaterial.materials[matIndex];
  35293. if (subMatId) {
  35294. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35295. }
  35296. else {
  35297. multiMaterial.subMaterials.push(null);
  35298. }
  35299. }
  35300. return multiMaterial;
  35301. };
  35302. /**
  35303. * Creates a material from parsed material data
  35304. * @param parsedMaterial defines parsed material data
  35305. * @param scene defines the hosting scene
  35306. * @param rootUrl defines the root URL to use to load textures
  35307. * @returns a new material
  35308. */
  35309. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35310. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35311. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35312. }
  35313. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35314. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35315. if (!BABYLON.LegacyPBRMaterial) {
  35316. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35317. return;
  35318. }
  35319. }
  35320. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35321. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35322. ;
  35323. };
  35324. // Triangle views
  35325. Material._TriangleFillMode = 0;
  35326. Material._WireFrameFillMode = 1;
  35327. Material._PointFillMode = 2;
  35328. // Draw modes
  35329. Material._PointListDrawMode = 3;
  35330. Material._LineListDrawMode = 4;
  35331. Material._LineLoopDrawMode = 5;
  35332. Material._LineStripDrawMode = 6;
  35333. Material._TriangleStripDrawMode = 7;
  35334. Material._TriangleFanDrawMode = 8;
  35335. /**
  35336. * Stores the clock-wise side orientation
  35337. */
  35338. Material._ClockWiseSideOrientation = 0;
  35339. /**
  35340. * Stores the counter clock-wise side orientation
  35341. */
  35342. Material._CounterClockWiseSideOrientation = 1;
  35343. /**
  35344. * The dirty texture flag value
  35345. */
  35346. Material._TextureDirtyFlag = 1;
  35347. /**
  35348. * The dirty light flag value
  35349. */
  35350. Material._LightDirtyFlag = 2;
  35351. /**
  35352. * The dirty fresnel flag value
  35353. */
  35354. Material._FresnelDirtyFlag = 4;
  35355. /**
  35356. * The dirty attribute flag value
  35357. */
  35358. Material._AttributesDirtyFlag = 8;
  35359. /**
  35360. * The dirty misc flag value
  35361. */
  35362. Material._MiscDirtyFlag = 16;
  35363. __decorate([
  35364. BABYLON.serialize()
  35365. ], Material.prototype, "id", void 0);
  35366. __decorate([
  35367. BABYLON.serialize()
  35368. ], Material.prototype, "name", void 0);
  35369. __decorate([
  35370. BABYLON.serialize()
  35371. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35372. __decorate([
  35373. BABYLON.serialize()
  35374. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35375. __decorate([
  35376. BABYLON.serialize()
  35377. ], Material.prototype, "state", void 0);
  35378. __decorate([
  35379. BABYLON.serialize("alpha")
  35380. ], Material.prototype, "_alpha", void 0);
  35381. __decorate([
  35382. BABYLON.serialize("backFaceCulling")
  35383. ], Material.prototype, "_backFaceCulling", void 0);
  35384. __decorate([
  35385. BABYLON.serialize()
  35386. ], Material.prototype, "sideOrientation", void 0);
  35387. __decorate([
  35388. BABYLON.serialize("alphaMode")
  35389. ], Material.prototype, "_alphaMode", void 0);
  35390. __decorate([
  35391. BABYLON.serialize()
  35392. ], Material.prototype, "_needDepthPrePass", void 0);
  35393. __decorate([
  35394. BABYLON.serialize()
  35395. ], Material.prototype, "disableDepthWrite", void 0);
  35396. __decorate([
  35397. BABYLON.serialize()
  35398. ], Material.prototype, "forceDepthWrite", void 0);
  35399. __decorate([
  35400. BABYLON.serialize()
  35401. ], Material.prototype, "separateCullingPass", void 0);
  35402. __decorate([
  35403. BABYLON.serialize("fogEnabled")
  35404. ], Material.prototype, "_fogEnabled", void 0);
  35405. __decorate([
  35406. BABYLON.serialize()
  35407. ], Material.prototype, "pointSize", void 0);
  35408. __decorate([
  35409. BABYLON.serialize()
  35410. ], Material.prototype, "zOffset", void 0);
  35411. __decorate([
  35412. BABYLON.serialize()
  35413. ], Material.prototype, "wireframe", null);
  35414. __decorate([
  35415. BABYLON.serialize()
  35416. ], Material.prototype, "pointsCloud", null);
  35417. __decorate([
  35418. BABYLON.serialize()
  35419. ], Material.prototype, "fillMode", null);
  35420. return Material;
  35421. }());
  35422. BABYLON.Material = Material;
  35423. })(BABYLON || (BABYLON = {}));
  35424. //# sourceMappingURL=babylon.material.js.map
  35425. var BABYLON;
  35426. (function (BABYLON) {
  35427. var UniformBuffer = /** @class */ (function () {
  35428. /**
  35429. * Uniform buffer objects.
  35430. *
  35431. * Handles blocks of uniform on the GPU.
  35432. *
  35433. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35434. *
  35435. * For more information, please refer to :
  35436. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35437. */
  35438. function UniformBuffer(engine, data, dynamic) {
  35439. this._engine = engine;
  35440. this._noUBO = !engine.supportsUniformBuffers;
  35441. this._dynamic = dynamic;
  35442. this._data = data || [];
  35443. this._uniformLocations = {};
  35444. this._uniformSizes = {};
  35445. this._uniformLocationPointer = 0;
  35446. this._needSync = false;
  35447. if (this._noUBO) {
  35448. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35449. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35450. this.updateFloat = this._updateFloatForEffect;
  35451. this.updateFloat2 = this._updateFloat2ForEffect;
  35452. this.updateFloat3 = this._updateFloat3ForEffect;
  35453. this.updateFloat4 = this._updateFloat4ForEffect;
  35454. this.updateMatrix = this._updateMatrixForEffect;
  35455. this.updateVector3 = this._updateVector3ForEffect;
  35456. this.updateVector4 = this._updateVector4ForEffect;
  35457. this.updateColor3 = this._updateColor3ForEffect;
  35458. this.updateColor4 = this._updateColor4ForEffect;
  35459. }
  35460. else {
  35461. this._engine._uniformBuffers.push(this);
  35462. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35463. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35464. this.updateFloat = this._updateFloatForUniform;
  35465. this.updateFloat2 = this._updateFloat2ForUniform;
  35466. this.updateFloat3 = this._updateFloat3ForUniform;
  35467. this.updateFloat4 = this._updateFloat4ForUniform;
  35468. this.updateMatrix = this._updateMatrixForUniform;
  35469. this.updateVector3 = this._updateVector3ForUniform;
  35470. this.updateVector4 = this._updateVector4ForUniform;
  35471. this.updateColor3 = this._updateColor3ForUniform;
  35472. this.updateColor4 = this._updateColor4ForUniform;
  35473. }
  35474. }
  35475. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35476. // Properties
  35477. /**
  35478. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35479. * or just falling back on setUniformXXX calls.
  35480. */
  35481. get: function () {
  35482. return !this._noUBO;
  35483. },
  35484. enumerable: true,
  35485. configurable: true
  35486. });
  35487. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35488. /**
  35489. * Indicates if the WebGL underlying uniform buffer is in sync
  35490. * with the javascript cache data.
  35491. */
  35492. get: function () {
  35493. return !this._needSync;
  35494. },
  35495. enumerable: true,
  35496. configurable: true
  35497. });
  35498. /**
  35499. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35500. * Also, a dynamic UniformBuffer will disable cache verification and always
  35501. * update the underlying WebGL uniform buffer to the GPU.
  35502. */
  35503. UniformBuffer.prototype.isDynamic = function () {
  35504. return this._dynamic !== undefined;
  35505. };
  35506. /**
  35507. * The data cache on JS side.
  35508. */
  35509. UniformBuffer.prototype.getData = function () {
  35510. return this._bufferData;
  35511. };
  35512. /**
  35513. * The underlying WebGL Uniform buffer.
  35514. */
  35515. UniformBuffer.prototype.getBuffer = function () {
  35516. return this._buffer;
  35517. };
  35518. /**
  35519. * std140 layout specifies how to align data within an UBO structure.
  35520. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35521. * for specs.
  35522. */
  35523. UniformBuffer.prototype._fillAlignment = function (size) {
  35524. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35525. // and 4x4 matrices
  35526. // TODO : change if other types are used
  35527. var alignment;
  35528. if (size <= 2) {
  35529. alignment = size;
  35530. }
  35531. else {
  35532. alignment = 4;
  35533. }
  35534. if ((this._uniformLocationPointer % alignment) !== 0) {
  35535. var oldPointer = this._uniformLocationPointer;
  35536. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35537. var diff = this._uniformLocationPointer - oldPointer;
  35538. for (var i = 0; i < diff; i++) {
  35539. this._data.push(0);
  35540. }
  35541. }
  35542. };
  35543. /**
  35544. * Adds an uniform in the buffer.
  35545. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35546. * for the layout to be correct !
  35547. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35548. * @param {number|number[]} size Data size, or data directly.
  35549. */
  35550. UniformBuffer.prototype.addUniform = function (name, size) {
  35551. if (this._noUBO) {
  35552. return;
  35553. }
  35554. if (this._uniformLocations[name] !== undefined) {
  35555. // Already existing uniform
  35556. return;
  35557. }
  35558. // This function must be called in the order of the shader layout !
  35559. // size can be the size of the uniform, or data directly
  35560. var data;
  35561. if (size instanceof Array) {
  35562. data = size;
  35563. size = data.length;
  35564. }
  35565. else {
  35566. size = size;
  35567. data = [];
  35568. // Fill with zeros
  35569. for (var i = 0; i < size; i++) {
  35570. data.push(0);
  35571. }
  35572. }
  35573. this._fillAlignment(size);
  35574. this._uniformSizes[name] = size;
  35575. this._uniformLocations[name] = this._uniformLocationPointer;
  35576. this._uniformLocationPointer += size;
  35577. for (var i = 0; i < size; i++) {
  35578. this._data.push(data[i]);
  35579. }
  35580. this._needSync = true;
  35581. };
  35582. /**
  35583. * Wrapper for addUniform.
  35584. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35585. * @param {Matrix} mat A 4x4 matrix.
  35586. */
  35587. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35588. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35589. };
  35590. /**
  35591. * Wrapper for addUniform.
  35592. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35593. * @param {number} x
  35594. * @param {number} y
  35595. */
  35596. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35597. var temp = [x, y];
  35598. this.addUniform(name, temp);
  35599. };
  35600. /**
  35601. * Wrapper for addUniform.
  35602. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35603. * @param {number} x
  35604. * @param {number} y
  35605. * @param {number} z
  35606. */
  35607. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35608. var temp = [x, y, z];
  35609. this.addUniform(name, temp);
  35610. };
  35611. /**
  35612. * Wrapper for addUniform.
  35613. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35614. * @param {Color3} color
  35615. */
  35616. UniformBuffer.prototype.addColor3 = function (name, color) {
  35617. var temp = new Array();
  35618. color.toArray(temp);
  35619. this.addUniform(name, temp);
  35620. };
  35621. /**
  35622. * Wrapper for addUniform.
  35623. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35624. * @param {Color3} color
  35625. * @param {number} alpha
  35626. */
  35627. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35628. var temp = new Array();
  35629. color.toArray(temp);
  35630. temp.push(alpha);
  35631. this.addUniform(name, temp);
  35632. };
  35633. /**
  35634. * Wrapper for addUniform.
  35635. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35636. * @param {Vector3} vector
  35637. */
  35638. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35639. var temp = new Array();
  35640. vector.toArray(temp);
  35641. this.addUniform(name, temp);
  35642. };
  35643. /**
  35644. * Wrapper for addUniform.
  35645. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35646. */
  35647. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35648. this.addUniform(name, 12);
  35649. };
  35650. /**
  35651. * Wrapper for addUniform.
  35652. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35653. */
  35654. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35655. this.addUniform(name, 8);
  35656. };
  35657. /**
  35658. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35659. */
  35660. UniformBuffer.prototype.create = function () {
  35661. if (this._noUBO) {
  35662. return;
  35663. }
  35664. if (this._buffer) {
  35665. return; // nothing to do
  35666. }
  35667. // See spec, alignment must be filled as a vec4
  35668. this._fillAlignment(4);
  35669. this._bufferData = new Float32Array(this._data);
  35670. this._rebuild();
  35671. this._needSync = true;
  35672. };
  35673. UniformBuffer.prototype._rebuild = function () {
  35674. if (this._noUBO) {
  35675. return;
  35676. }
  35677. if (this._dynamic) {
  35678. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35679. }
  35680. else {
  35681. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35682. }
  35683. };
  35684. /**
  35685. * Updates the WebGL Uniform Buffer on the GPU.
  35686. * If the `dynamic` flag is set to true, no cache comparison is done.
  35687. * Otherwise, the buffer will be updated only if the cache differs.
  35688. */
  35689. UniformBuffer.prototype.update = function () {
  35690. if (!this._buffer) {
  35691. this.create();
  35692. return;
  35693. }
  35694. if (!this._dynamic && !this._needSync) {
  35695. return;
  35696. }
  35697. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35698. this._needSync = false;
  35699. };
  35700. /**
  35701. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35702. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35703. * @param {number[]|Float32Array} data Flattened data
  35704. * @param {number} size Size of the data.
  35705. */
  35706. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35707. var location = this._uniformLocations[uniformName];
  35708. if (location === undefined) {
  35709. if (this._buffer) {
  35710. // Cannot add an uniform if the buffer is already created
  35711. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35712. return;
  35713. }
  35714. this.addUniform(uniformName, size);
  35715. location = this._uniformLocations[uniformName];
  35716. }
  35717. if (!this._buffer) {
  35718. this.create();
  35719. }
  35720. if (!this._dynamic) {
  35721. // Cache for static uniform buffers
  35722. var changed = false;
  35723. for (var i = 0; i < size; i++) {
  35724. if (this._bufferData[location + i] !== data[i]) {
  35725. changed = true;
  35726. this._bufferData[location + i] = data[i];
  35727. }
  35728. }
  35729. this._needSync = this._needSync || changed;
  35730. }
  35731. else {
  35732. // No cache for dynamic
  35733. for (var i = 0; i < size; i++) {
  35734. this._bufferData[location + i] = data[i];
  35735. }
  35736. }
  35737. };
  35738. // Update methods
  35739. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35740. // To match std140, matrix must be realigned
  35741. for (var i = 0; i < 3; i++) {
  35742. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35743. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35744. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35745. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35746. }
  35747. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35748. };
  35749. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35750. this._currentEffect.setMatrix3x3(name, matrix);
  35751. };
  35752. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35753. this._currentEffect.setMatrix2x2(name, matrix);
  35754. };
  35755. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35756. // To match std140, matrix must be realigned
  35757. for (var i = 0; i < 2; i++) {
  35758. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35759. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35760. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35761. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35762. }
  35763. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35764. };
  35765. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35766. this._currentEffect.setFloat(name, x);
  35767. };
  35768. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35769. UniformBuffer._tempBuffer[0] = x;
  35770. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35771. };
  35772. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35773. if (suffix === void 0) { suffix = ""; }
  35774. this._currentEffect.setFloat2(name + suffix, x, y);
  35775. };
  35776. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35777. if (suffix === void 0) { suffix = ""; }
  35778. UniformBuffer._tempBuffer[0] = x;
  35779. UniformBuffer._tempBuffer[1] = y;
  35780. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35781. };
  35782. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35783. if (suffix === void 0) { suffix = ""; }
  35784. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35785. };
  35786. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35787. if (suffix === void 0) { suffix = ""; }
  35788. UniformBuffer._tempBuffer[0] = x;
  35789. UniformBuffer._tempBuffer[1] = y;
  35790. UniformBuffer._tempBuffer[2] = z;
  35791. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35792. };
  35793. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35794. if (suffix === void 0) { suffix = ""; }
  35795. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35796. };
  35797. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35798. if (suffix === void 0) { suffix = ""; }
  35799. UniformBuffer._tempBuffer[0] = x;
  35800. UniformBuffer._tempBuffer[1] = y;
  35801. UniformBuffer._tempBuffer[2] = z;
  35802. UniformBuffer._tempBuffer[3] = w;
  35803. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35804. };
  35805. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35806. this._currentEffect.setMatrix(name, mat);
  35807. };
  35808. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35809. this.updateUniform(name, mat.toArray(), 16);
  35810. };
  35811. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35812. this._currentEffect.setVector3(name, vector);
  35813. };
  35814. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35815. vector.toArray(UniformBuffer._tempBuffer);
  35816. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35817. };
  35818. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35819. this._currentEffect.setVector4(name, vector);
  35820. };
  35821. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35822. vector.toArray(UniformBuffer._tempBuffer);
  35823. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35824. };
  35825. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35826. if (suffix === void 0) { suffix = ""; }
  35827. this._currentEffect.setColor3(name + suffix, color);
  35828. };
  35829. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35830. if (suffix === void 0) { suffix = ""; }
  35831. color.toArray(UniformBuffer._tempBuffer);
  35832. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35833. };
  35834. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35835. if (suffix === void 0) { suffix = ""; }
  35836. this._currentEffect.setColor4(name + suffix, color, alpha);
  35837. };
  35838. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35839. if (suffix === void 0) { suffix = ""; }
  35840. color.toArray(UniformBuffer._tempBuffer);
  35841. UniformBuffer._tempBuffer[3] = alpha;
  35842. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35843. };
  35844. /**
  35845. * Sets a sampler uniform on the effect.
  35846. * @param {string} name Name of the sampler.
  35847. * @param {Texture} texture
  35848. */
  35849. UniformBuffer.prototype.setTexture = function (name, texture) {
  35850. this._currentEffect.setTexture(name, texture);
  35851. };
  35852. /**
  35853. * Directly updates the value of the uniform in the cache AND on the GPU.
  35854. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35855. * @param {number[]|Float32Array} data Flattened data
  35856. */
  35857. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35858. this.updateUniform(uniformName, data, data.length);
  35859. this.update();
  35860. };
  35861. /**
  35862. * Binds this uniform buffer to an effect.
  35863. * @param {Effect} effect
  35864. * @param {string} name Name of the uniform block in the shader.
  35865. */
  35866. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35867. this._currentEffect = effect;
  35868. if (this._noUBO || !this._buffer) {
  35869. return;
  35870. }
  35871. effect.bindUniformBuffer(this._buffer, name);
  35872. };
  35873. /**
  35874. * Disposes the uniform buffer.
  35875. */
  35876. UniformBuffer.prototype.dispose = function () {
  35877. if (this._noUBO) {
  35878. return;
  35879. }
  35880. var index = this._engine._uniformBuffers.indexOf(this);
  35881. if (index !== -1) {
  35882. this._engine._uniformBuffers.splice(index, 1);
  35883. }
  35884. if (!this._buffer) {
  35885. return;
  35886. }
  35887. if (this._engine._releaseBuffer(this._buffer)) {
  35888. this._buffer = null;
  35889. }
  35890. };
  35891. // Pool for avoiding memory leaks
  35892. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35893. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35894. return UniformBuffer;
  35895. }());
  35896. BABYLON.UniformBuffer = UniformBuffer;
  35897. })(BABYLON || (BABYLON = {}));
  35898. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35899. var BABYLON;
  35900. (function (BABYLON) {
  35901. /**
  35902. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35903. */
  35904. var VertexData = /** @class */ (function () {
  35905. function VertexData() {
  35906. }
  35907. /**
  35908. * Uses the passed data array to set the set the values for the specified kind of data
  35909. * @param data a linear array of floating numbers
  35910. * @param kind the type of data that is being set, eg positions, colors etc
  35911. */
  35912. VertexData.prototype.set = function (data, kind) {
  35913. switch (kind) {
  35914. case BABYLON.VertexBuffer.PositionKind:
  35915. this.positions = data;
  35916. break;
  35917. case BABYLON.VertexBuffer.NormalKind:
  35918. this.normals = data;
  35919. break;
  35920. case BABYLON.VertexBuffer.TangentKind:
  35921. this.tangents = data;
  35922. break;
  35923. case BABYLON.VertexBuffer.UVKind:
  35924. this.uvs = data;
  35925. break;
  35926. case BABYLON.VertexBuffer.UV2Kind:
  35927. this.uvs2 = data;
  35928. break;
  35929. case BABYLON.VertexBuffer.UV3Kind:
  35930. this.uvs3 = data;
  35931. break;
  35932. case BABYLON.VertexBuffer.UV4Kind:
  35933. this.uvs4 = data;
  35934. break;
  35935. case BABYLON.VertexBuffer.UV5Kind:
  35936. this.uvs5 = data;
  35937. break;
  35938. case BABYLON.VertexBuffer.UV6Kind:
  35939. this.uvs6 = data;
  35940. break;
  35941. case BABYLON.VertexBuffer.ColorKind:
  35942. this.colors = data;
  35943. break;
  35944. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35945. this.matricesIndices = data;
  35946. break;
  35947. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35948. this.matricesWeights = data;
  35949. break;
  35950. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35951. this.matricesIndicesExtra = data;
  35952. break;
  35953. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35954. this.matricesWeightsExtra = data;
  35955. break;
  35956. }
  35957. };
  35958. /**
  35959. * Associates the vertexData to the passed Mesh.
  35960. * Sets it as updatable or not (default `false`)
  35961. * @param mesh the mesh the vertexData is applied to
  35962. * @param updatable when used and having the value true allows new data to update the vertexData
  35963. * @returns the VertexData
  35964. */
  35965. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35966. this._applyTo(mesh, updatable);
  35967. return this;
  35968. };
  35969. /**
  35970. * Associates the vertexData to the passed Geometry.
  35971. * Sets it as updatable or not (default `false`)
  35972. * @param geometry the geometry the vertexData is applied to
  35973. * @param updatable when used and having the value true allows new data to update the vertexData
  35974. * @returns VertexData
  35975. */
  35976. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35977. this._applyTo(geometry, updatable);
  35978. return this;
  35979. };
  35980. /**
  35981. * Updates the associated mesh
  35982. * @param mesh the mesh to be updated
  35983. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35984. * @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
  35985. * @returns VertexData
  35986. */
  35987. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35988. this._update(mesh);
  35989. return this;
  35990. };
  35991. /**
  35992. * Updates the associated geometry
  35993. * @param geometry the geometry to be updated
  35994. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35995. * @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
  35996. * @returns VertexData.
  35997. */
  35998. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35999. this._update(geometry);
  36000. return this;
  36001. };
  36002. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36003. if (updatable === void 0) { updatable = false; }
  36004. if (this.positions) {
  36005. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36006. }
  36007. if (this.normals) {
  36008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36009. }
  36010. if (this.tangents) {
  36011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36012. }
  36013. if (this.uvs) {
  36014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36015. }
  36016. if (this.uvs2) {
  36017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36018. }
  36019. if (this.uvs3) {
  36020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36021. }
  36022. if (this.uvs4) {
  36023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36024. }
  36025. if (this.uvs5) {
  36026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36027. }
  36028. if (this.uvs6) {
  36029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36030. }
  36031. if (this.colors) {
  36032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36033. }
  36034. if (this.matricesIndices) {
  36035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36036. }
  36037. if (this.matricesWeights) {
  36038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36039. }
  36040. if (this.matricesIndicesExtra) {
  36041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36042. }
  36043. if (this.matricesWeightsExtra) {
  36044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36045. }
  36046. if (this.indices) {
  36047. meshOrGeometry.setIndices(this.indices, null, updatable);
  36048. }
  36049. return this;
  36050. };
  36051. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36052. if (this.positions) {
  36053. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36054. }
  36055. if (this.normals) {
  36056. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36057. }
  36058. if (this.tangents) {
  36059. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36060. }
  36061. if (this.uvs) {
  36062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36063. }
  36064. if (this.uvs2) {
  36065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36066. }
  36067. if (this.uvs3) {
  36068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36069. }
  36070. if (this.uvs4) {
  36071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36072. }
  36073. if (this.uvs5) {
  36074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36075. }
  36076. if (this.uvs6) {
  36077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36078. }
  36079. if (this.colors) {
  36080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36081. }
  36082. if (this.matricesIndices) {
  36083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36084. }
  36085. if (this.matricesWeights) {
  36086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36087. }
  36088. if (this.matricesIndicesExtra) {
  36089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36090. }
  36091. if (this.matricesWeightsExtra) {
  36092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36093. }
  36094. if (this.indices) {
  36095. meshOrGeometry.setIndices(this.indices, null);
  36096. }
  36097. return this;
  36098. };
  36099. /**
  36100. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36101. * @param matrix the transforming matrix
  36102. * @returns the VertexData
  36103. */
  36104. VertexData.prototype.transform = function (matrix) {
  36105. var transformed = BABYLON.Vector3.Zero();
  36106. var index;
  36107. if (this.positions) {
  36108. var position = BABYLON.Vector3.Zero();
  36109. for (index = 0; index < this.positions.length; index += 3) {
  36110. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36111. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36112. this.positions[index] = transformed.x;
  36113. this.positions[index + 1] = transformed.y;
  36114. this.positions[index + 2] = transformed.z;
  36115. }
  36116. }
  36117. if (this.normals) {
  36118. var normal = BABYLON.Vector3.Zero();
  36119. for (index = 0; index < this.normals.length; index += 3) {
  36120. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36121. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36122. this.normals[index] = transformed.x;
  36123. this.normals[index + 1] = transformed.y;
  36124. this.normals[index + 2] = transformed.z;
  36125. }
  36126. }
  36127. if (this.tangents) {
  36128. var tangent = BABYLON.Vector4.Zero();
  36129. var tangentTransformed = BABYLON.Vector4.Zero();
  36130. for (index = 0; index < this.tangents.length; index += 4) {
  36131. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36132. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36133. this.tangents[index] = tangentTransformed.x;
  36134. this.tangents[index + 1] = tangentTransformed.y;
  36135. this.tangents[index + 2] = tangentTransformed.z;
  36136. this.tangents[index + 3] = tangentTransformed.w;
  36137. }
  36138. }
  36139. return this;
  36140. };
  36141. /**
  36142. * Merges the passed VertexData into the current one
  36143. * @param other the VertexData to be merged into the current one
  36144. * @returns the modified VertexData
  36145. */
  36146. VertexData.prototype.merge = function (other) {
  36147. this._validate();
  36148. other._validate();
  36149. if (!this.normals !== !other.normals ||
  36150. !this.tangents !== !other.tangents ||
  36151. !this.uvs !== !other.uvs ||
  36152. !this.uvs2 !== !other.uvs2 ||
  36153. !this.uvs3 !== !other.uvs3 ||
  36154. !this.uvs4 !== !other.uvs4 ||
  36155. !this.uvs5 !== !other.uvs5 ||
  36156. !this.uvs6 !== !other.uvs6 ||
  36157. !this.colors !== !other.colors ||
  36158. !this.matricesIndices !== !other.matricesIndices ||
  36159. !this.matricesWeights !== !other.matricesWeights ||
  36160. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36161. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36162. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36163. }
  36164. if (other.indices) {
  36165. if (!this.indices) {
  36166. this.indices = [];
  36167. }
  36168. var offset = this.positions ? this.positions.length / 3 : 0;
  36169. for (var index = 0; index < other.indices.length; index++) {
  36170. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36171. this.indices.push(other.indices[index] + offset);
  36172. }
  36173. }
  36174. this.positions = this._mergeElement(this.positions, other.positions);
  36175. this.normals = this._mergeElement(this.normals, other.normals);
  36176. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36177. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36178. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36179. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36180. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36181. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36182. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36183. this.colors = this._mergeElement(this.colors, other.colors);
  36184. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36185. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36186. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36187. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36188. return this;
  36189. };
  36190. VertexData.prototype._mergeElement = function (source, other) {
  36191. if (!source) {
  36192. return other;
  36193. }
  36194. if (!other) {
  36195. return source;
  36196. }
  36197. var len = other.length + source.length;
  36198. var isSrcTypedArray = source instanceof Float32Array;
  36199. var isOthTypedArray = other instanceof Float32Array;
  36200. // use non-loop method when the source is Float32Array
  36201. if (isSrcTypedArray) {
  36202. var ret32 = new Float32Array(len);
  36203. ret32.set(source);
  36204. ret32.set(other, source.length);
  36205. return ret32;
  36206. // source is number[], when other is also use concat
  36207. }
  36208. else if (!isOthTypedArray) {
  36209. return source.concat(other);
  36210. // source is a number[], but other is a Float32Array, loop required
  36211. }
  36212. else {
  36213. var ret = source.slice(0); // copy source to a separate array
  36214. for (var i = 0, len = other.length; i < len; i++) {
  36215. ret.push(other[i]);
  36216. }
  36217. return ret;
  36218. }
  36219. };
  36220. VertexData.prototype._validate = function () {
  36221. if (!this.positions) {
  36222. throw new Error("Positions are required");
  36223. }
  36224. var getElementCount = function (kind, values) {
  36225. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36226. if ((values.length % stride) !== 0) {
  36227. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36228. }
  36229. return values.length / stride;
  36230. };
  36231. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36232. var validateElementCount = function (kind, values) {
  36233. var elementCount = getElementCount(kind, values);
  36234. if (elementCount !== positionsElementCount) {
  36235. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36236. }
  36237. };
  36238. if (this.normals)
  36239. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36240. if (this.tangents)
  36241. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36242. if (this.uvs)
  36243. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36244. if (this.uvs2)
  36245. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36246. if (this.uvs3)
  36247. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36248. if (this.uvs4)
  36249. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36250. if (this.uvs5)
  36251. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36252. if (this.uvs6)
  36253. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36254. if (this.colors)
  36255. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36256. if (this.matricesIndices)
  36257. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36258. if (this.matricesWeights)
  36259. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36260. if (this.matricesIndicesExtra)
  36261. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36262. if (this.matricesWeightsExtra)
  36263. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36264. };
  36265. /**
  36266. * Serializes the VertexData
  36267. * @returns a serialized object
  36268. */
  36269. VertexData.prototype.serialize = function () {
  36270. var serializationObject = this.serialize();
  36271. if (this.positions) {
  36272. serializationObject.positions = this.positions;
  36273. }
  36274. if (this.normals) {
  36275. serializationObject.normals = this.normals;
  36276. }
  36277. if (this.tangents) {
  36278. serializationObject.tangents = this.tangents;
  36279. }
  36280. if (this.uvs) {
  36281. serializationObject.uvs = this.uvs;
  36282. }
  36283. if (this.uvs2) {
  36284. serializationObject.uvs2 = this.uvs2;
  36285. }
  36286. if (this.uvs3) {
  36287. serializationObject.uvs3 = this.uvs3;
  36288. }
  36289. if (this.uvs4) {
  36290. serializationObject.uvs4 = this.uvs4;
  36291. }
  36292. if (this.uvs5) {
  36293. serializationObject.uvs5 = this.uvs5;
  36294. }
  36295. if (this.uvs6) {
  36296. serializationObject.uvs6 = this.uvs6;
  36297. }
  36298. if (this.colors) {
  36299. serializationObject.colors = this.colors;
  36300. }
  36301. if (this.matricesIndices) {
  36302. serializationObject.matricesIndices = this.matricesIndices;
  36303. serializationObject.matricesIndices._isExpanded = true;
  36304. }
  36305. if (this.matricesWeights) {
  36306. serializationObject.matricesWeights = this.matricesWeights;
  36307. }
  36308. if (this.matricesIndicesExtra) {
  36309. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36310. serializationObject.matricesIndicesExtra._isExpanded = true;
  36311. }
  36312. if (this.matricesWeightsExtra) {
  36313. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36314. }
  36315. serializationObject.indices = this.indices;
  36316. return serializationObject;
  36317. };
  36318. // Statics
  36319. /**
  36320. * Extracts the vertexData from a mesh
  36321. * @param mesh the mesh from which to extract the VertexData
  36322. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36323. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36324. * @returns the object VertexData associated to the passed mesh
  36325. */
  36326. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36327. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36328. };
  36329. /**
  36330. * Extracts the vertexData from the geometry
  36331. * @param geometry the geometry from which to extract the VertexData
  36332. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36333. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36334. * @returns the object VertexData associated to the passed mesh
  36335. */
  36336. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36337. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36338. };
  36339. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36340. var result = new VertexData();
  36341. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36342. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36343. }
  36344. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36345. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36346. }
  36347. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36348. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36349. }
  36350. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36351. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36352. }
  36353. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36354. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36355. }
  36356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36357. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36358. }
  36359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36360. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36361. }
  36362. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36363. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36364. }
  36365. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36366. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36367. }
  36368. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36369. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36370. }
  36371. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36372. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36373. }
  36374. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36375. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36376. }
  36377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36378. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36379. }
  36380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36381. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36382. }
  36383. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36384. return result;
  36385. };
  36386. /**
  36387. * Creates the VertexData for a Ribbon
  36388. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36389. * * pathArray array of paths, each of which an array of successive Vector3
  36390. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36391. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36392. * * 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
  36393. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36394. * * 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)
  36395. * * 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)
  36396. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36397. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36398. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36399. * @returns the VertexData of the ribbon
  36400. */
  36401. VertexData.CreateRibbon = function (options) {
  36402. var pathArray = options.pathArray;
  36403. var closeArray = options.closeArray || false;
  36404. var closePath = options.closePath || false;
  36405. var invertUV = options.invertUV || false;
  36406. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36407. var offset = options.offset || defaultOffset;
  36408. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36409. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36410. var customUV = options.uvs;
  36411. var customColors = options.colors;
  36412. var positions = [];
  36413. var indices = [];
  36414. var normals = [];
  36415. var uvs = [];
  36416. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36417. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36418. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36419. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36420. var minlg; // minimal length among all paths from pathArray
  36421. var lg = []; // array of path lengths : nb of vertex per path
  36422. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36423. var p; // path iterator
  36424. var i; // point iterator
  36425. var j; // point iterator
  36426. // if single path in pathArray
  36427. if (pathArray.length < 2) {
  36428. var ar1 = [];
  36429. var ar2 = [];
  36430. for (i = 0; i < pathArray[0].length - offset; i++) {
  36431. ar1.push(pathArray[0][i]);
  36432. ar2.push(pathArray[0][i + offset]);
  36433. }
  36434. pathArray = [ar1, ar2];
  36435. }
  36436. // positions and horizontal distances (u)
  36437. var idc = 0;
  36438. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36439. var path;
  36440. var l;
  36441. minlg = pathArray[0].length;
  36442. var vectlg;
  36443. var dist;
  36444. for (p = 0; p < pathArray.length; p++) {
  36445. uTotalDistance[p] = 0;
  36446. us[p] = [0];
  36447. path = pathArray[p];
  36448. l = path.length;
  36449. minlg = (minlg < l) ? minlg : l;
  36450. j = 0;
  36451. while (j < l) {
  36452. positions.push(path[j].x, path[j].y, path[j].z);
  36453. if (j > 0) {
  36454. vectlg = path[j].subtract(path[j - 1]).length();
  36455. dist = vectlg + uTotalDistance[p];
  36456. us[p].push(dist);
  36457. uTotalDistance[p] = dist;
  36458. }
  36459. j++;
  36460. }
  36461. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36462. j--;
  36463. positions.push(path[0].x, path[0].y, path[0].z);
  36464. vectlg = path[j].subtract(path[0]).length();
  36465. dist = vectlg + uTotalDistance[p];
  36466. us[p].push(dist);
  36467. uTotalDistance[p] = dist;
  36468. }
  36469. lg[p] = l + closePathCorr;
  36470. idx[p] = idc;
  36471. idc += (l + closePathCorr);
  36472. }
  36473. // vertical distances (v)
  36474. var path1;
  36475. var path2;
  36476. var vertex1 = null;
  36477. var vertex2 = null;
  36478. for (i = 0; i < minlg + closePathCorr; i++) {
  36479. vTotalDistance[i] = 0;
  36480. vs[i] = [0];
  36481. for (p = 0; p < pathArray.length - 1; p++) {
  36482. path1 = pathArray[p];
  36483. path2 = pathArray[p + 1];
  36484. if (i === minlg) { // closePath
  36485. vertex1 = path1[0];
  36486. vertex2 = path2[0];
  36487. }
  36488. else {
  36489. vertex1 = path1[i];
  36490. vertex2 = path2[i];
  36491. }
  36492. vectlg = vertex2.subtract(vertex1).length();
  36493. dist = vectlg + vTotalDistance[i];
  36494. vs[i].push(dist);
  36495. vTotalDistance[i] = dist;
  36496. }
  36497. if (closeArray && vertex2 && vertex1) {
  36498. path1 = pathArray[p];
  36499. path2 = pathArray[0];
  36500. if (i === minlg) { // closePath
  36501. vertex2 = path2[0];
  36502. }
  36503. vectlg = vertex2.subtract(vertex1).length();
  36504. dist = vectlg + vTotalDistance[i];
  36505. vTotalDistance[i] = dist;
  36506. }
  36507. }
  36508. // uvs
  36509. var u;
  36510. var v;
  36511. if (customUV) {
  36512. for (p = 0; p < customUV.length; p++) {
  36513. uvs.push(customUV[p].x, customUV[p].y);
  36514. }
  36515. }
  36516. else {
  36517. for (p = 0; p < pathArray.length; p++) {
  36518. for (i = 0; i < minlg + closePathCorr; i++) {
  36519. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36520. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36521. if (invertUV) {
  36522. uvs.push(v, u);
  36523. }
  36524. else {
  36525. uvs.push(u, v);
  36526. }
  36527. }
  36528. }
  36529. }
  36530. // indices
  36531. p = 0; // path index
  36532. var pi = 0; // positions array index
  36533. var l1 = lg[p] - 1; // path1 length
  36534. var l2 = lg[p + 1] - 1; // path2 length
  36535. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36536. var shft = idx[1] - idx[0]; // shift
  36537. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36538. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36539. // 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
  36540. indices.push(pi, pi + shft, pi + 1);
  36541. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36542. pi += 1;
  36543. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36544. p++;
  36545. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36546. shft = idx[0] - idx[p];
  36547. l1 = lg[p] - 1;
  36548. l2 = lg[0] - 1;
  36549. }
  36550. else {
  36551. shft = idx[p + 1] - idx[p];
  36552. l1 = lg[p] - 1;
  36553. l2 = lg[p + 1] - 1;
  36554. }
  36555. pi = idx[p];
  36556. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36557. }
  36558. }
  36559. // normals
  36560. VertexData.ComputeNormals(positions, indices, normals);
  36561. if (closePath) { // update both the first and last vertex normals to their average value
  36562. var indexFirst = 0;
  36563. var indexLast = 0;
  36564. for (p = 0; p < pathArray.length; p++) {
  36565. indexFirst = idx[p] * 3;
  36566. if (p + 1 < pathArray.length) {
  36567. indexLast = (idx[p + 1] - 1) * 3;
  36568. }
  36569. else {
  36570. indexLast = normals.length - 3;
  36571. }
  36572. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36573. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36574. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36575. normals[indexLast] = normals[indexFirst];
  36576. normals[indexLast + 1] = normals[indexFirst + 1];
  36577. normals[indexLast + 2] = normals[indexFirst + 2];
  36578. }
  36579. }
  36580. // sides
  36581. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36582. // Colors
  36583. var colors = null;
  36584. if (customColors) {
  36585. colors = new Float32Array(customColors.length * 4);
  36586. for (var c = 0; c < customColors.length; c++) {
  36587. colors[c * 4] = customColors[c].r;
  36588. colors[c * 4 + 1] = customColors[c].g;
  36589. colors[c * 4 + 2] = customColors[c].b;
  36590. colors[c * 4 + 3] = customColors[c].a;
  36591. }
  36592. }
  36593. // Result
  36594. var vertexData = new VertexData();
  36595. var positions32 = new Float32Array(positions);
  36596. var normals32 = new Float32Array(normals);
  36597. var uvs32 = new Float32Array(uvs);
  36598. vertexData.indices = indices;
  36599. vertexData.positions = positions32;
  36600. vertexData.normals = normals32;
  36601. vertexData.uvs = uvs32;
  36602. if (colors) {
  36603. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36604. }
  36605. if (closePath) {
  36606. vertexData._idx = idx;
  36607. }
  36608. return vertexData;
  36609. };
  36610. /**
  36611. * Creates the VertexData for a box
  36612. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36613. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36614. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36615. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36616. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36617. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36618. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36619. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36620. * * 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)
  36621. * * 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)
  36622. * @returns the VertexData of the box
  36623. */
  36624. VertexData.CreateBox = function (options) {
  36625. var normalsSource = [
  36626. new BABYLON.Vector3(0, 0, 1),
  36627. new BABYLON.Vector3(0, 0, -1),
  36628. new BABYLON.Vector3(1, 0, 0),
  36629. new BABYLON.Vector3(-1, 0, 0),
  36630. new BABYLON.Vector3(0, 1, 0),
  36631. new BABYLON.Vector3(0, -1, 0)
  36632. ];
  36633. var indices = [];
  36634. var positions = [];
  36635. var normals = [];
  36636. var uvs = [];
  36637. var width = options.width || options.size || 1;
  36638. var height = options.height || options.size || 1;
  36639. var depth = options.depth || options.size || 1;
  36640. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36641. var faceUV = options.faceUV || new Array(6);
  36642. var faceColors = options.faceColors;
  36643. var colors = [];
  36644. // default face colors and UV if undefined
  36645. for (var f = 0; f < 6; f++) {
  36646. if (faceUV[f] === undefined) {
  36647. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36648. }
  36649. if (faceColors && faceColors[f] === undefined) {
  36650. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36651. }
  36652. }
  36653. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36654. // Create each face in turn.
  36655. for (var index = 0; index < normalsSource.length; index++) {
  36656. var normal = normalsSource[index];
  36657. // Get two vectors perpendicular to the face normal and to each other.
  36658. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36659. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36660. // Six indices (two triangles) per face.
  36661. var verticesLength = positions.length / 3;
  36662. indices.push(verticesLength);
  36663. indices.push(verticesLength + 1);
  36664. indices.push(verticesLength + 2);
  36665. indices.push(verticesLength);
  36666. indices.push(verticesLength + 2);
  36667. indices.push(verticesLength + 3);
  36668. // Four vertices per face.
  36669. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36670. positions.push(vertex.x, vertex.y, vertex.z);
  36671. normals.push(normal.x, normal.y, normal.z);
  36672. uvs.push(faceUV[index].z, faceUV[index].w);
  36673. if (faceColors) {
  36674. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36675. }
  36676. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36677. positions.push(vertex.x, vertex.y, vertex.z);
  36678. normals.push(normal.x, normal.y, normal.z);
  36679. uvs.push(faceUV[index].x, faceUV[index].w);
  36680. if (faceColors) {
  36681. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36682. }
  36683. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36684. positions.push(vertex.x, vertex.y, vertex.z);
  36685. normals.push(normal.x, normal.y, normal.z);
  36686. uvs.push(faceUV[index].x, faceUV[index].y);
  36687. if (faceColors) {
  36688. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36689. }
  36690. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36691. positions.push(vertex.x, vertex.y, vertex.z);
  36692. normals.push(normal.x, normal.y, normal.z);
  36693. uvs.push(faceUV[index].z, faceUV[index].y);
  36694. if (faceColors) {
  36695. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36696. }
  36697. }
  36698. // sides
  36699. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36700. // Result
  36701. var vertexData = new VertexData();
  36702. vertexData.indices = indices;
  36703. vertexData.positions = positions;
  36704. vertexData.normals = normals;
  36705. vertexData.uvs = uvs;
  36706. if (faceColors) {
  36707. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36708. vertexData.colors = totalColors;
  36709. }
  36710. return vertexData;
  36711. };
  36712. /**
  36713. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36714. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36715. * * segments sets the number of horizontal strips optional, default 32
  36716. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36717. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36718. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36719. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36720. * * 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
  36721. * * 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
  36722. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36723. * * 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)
  36724. * * 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)
  36725. * @returns the VertexData of the ellipsoid
  36726. */
  36727. VertexData.CreateSphere = function (options) {
  36728. var segments = options.segments || 32;
  36729. var diameterX = options.diameterX || options.diameter || 1;
  36730. var diameterY = options.diameterY || options.diameter || 1;
  36731. var diameterZ = options.diameterZ || options.diameter || 1;
  36732. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36733. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36734. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36735. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36736. var totalZRotationSteps = 2 + segments;
  36737. var totalYRotationSteps = 2 * totalZRotationSteps;
  36738. var indices = [];
  36739. var positions = [];
  36740. var normals = [];
  36741. var uvs = [];
  36742. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36743. var normalizedZ = zRotationStep / totalZRotationSteps;
  36744. var angleZ = normalizedZ * Math.PI * slice;
  36745. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36746. var normalizedY = yRotationStep / totalYRotationSteps;
  36747. var angleY = normalizedY * Math.PI * 2 * arc;
  36748. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36749. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36750. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36751. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36752. var vertex = complete.multiply(radius);
  36753. var normal = complete.divide(radius).normalize();
  36754. positions.push(vertex.x, vertex.y, vertex.z);
  36755. normals.push(normal.x, normal.y, normal.z);
  36756. uvs.push(normalizedY, normalizedZ);
  36757. }
  36758. if (zRotationStep > 0) {
  36759. var verticesCount = positions.length / 3;
  36760. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36761. indices.push((firstIndex));
  36762. indices.push((firstIndex + 1));
  36763. indices.push(firstIndex + totalYRotationSteps + 1);
  36764. indices.push((firstIndex + totalYRotationSteps + 1));
  36765. indices.push((firstIndex + 1));
  36766. indices.push((firstIndex + totalYRotationSteps + 2));
  36767. }
  36768. }
  36769. }
  36770. // Sides
  36771. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36772. // Result
  36773. var vertexData = new VertexData();
  36774. vertexData.indices = indices;
  36775. vertexData.positions = positions;
  36776. vertexData.normals = normals;
  36777. vertexData.uvs = uvs;
  36778. return vertexData;
  36779. };
  36780. /**
  36781. * Creates the VertexData for a cylinder, cone or prism
  36782. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36783. * * height sets the height (y direction) of the cylinder, optional, default 2
  36784. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36785. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36786. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36787. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36788. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36789. * * 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
  36790. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36791. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36792. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36793. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36794. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36795. * * 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)
  36796. * * 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)
  36797. * @returns the VertexData of the cylinder, cone or prism
  36798. */
  36799. VertexData.CreateCylinder = function (options) {
  36800. var height = options.height || 2;
  36801. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36802. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36803. var tessellation = options.tessellation || 24;
  36804. var subdivisions = options.subdivisions || 1;
  36805. var hasRings = options.hasRings ? true : false;
  36806. var enclose = options.enclose ? true : false;
  36807. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36808. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36809. var faceUV = options.faceUV || new Array(3);
  36810. var faceColors = options.faceColors;
  36811. // default face colors and UV if undefined
  36812. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36813. var ringNb = (hasRings) ? subdivisions : 1;
  36814. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36815. var f;
  36816. for (f = 0; f < surfaceNb; f++) {
  36817. if (faceColors && faceColors[f] === undefined) {
  36818. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36819. }
  36820. }
  36821. for (f = 0; f < surfaceNb; f++) {
  36822. if (faceUV && faceUV[f] === undefined) {
  36823. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36824. }
  36825. }
  36826. var indices = new Array();
  36827. var positions = new Array();
  36828. var normals = new Array();
  36829. var uvs = new Array();
  36830. var colors = new Array();
  36831. var angle_step = Math.PI * 2 * arc / tessellation;
  36832. var angle;
  36833. var h;
  36834. var radius;
  36835. var tan = (diameterBottom - diameterTop) / 2 / height;
  36836. var ringVertex = BABYLON.Vector3.Zero();
  36837. var ringNormal = BABYLON.Vector3.Zero();
  36838. var ringFirstVertex = BABYLON.Vector3.Zero();
  36839. var ringFirstNormal = BABYLON.Vector3.Zero();
  36840. var quadNormal = BABYLON.Vector3.Zero();
  36841. var Y = BABYLON.Axis.Y;
  36842. // positions, normals, uvs
  36843. var i;
  36844. var j;
  36845. var r;
  36846. var ringIdx = 1;
  36847. var s = 1; // surface index
  36848. var cs = 0;
  36849. var v = 0;
  36850. for (i = 0; i <= subdivisions; i++) {
  36851. h = i / subdivisions;
  36852. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36853. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36854. for (r = 0; r < ringIdx; r++) {
  36855. if (hasRings) {
  36856. s += r;
  36857. }
  36858. if (enclose) {
  36859. s += 2 * r;
  36860. }
  36861. for (j = 0; j <= tessellation; j++) {
  36862. angle = j * angle_step;
  36863. // position
  36864. ringVertex.x = Math.cos(-angle) * radius;
  36865. ringVertex.y = -height / 2 + h * height;
  36866. ringVertex.z = Math.sin(-angle) * radius;
  36867. // normal
  36868. if (diameterTop === 0 && i === subdivisions) {
  36869. // if no top cap, reuse former normals
  36870. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36871. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36872. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36873. }
  36874. else {
  36875. ringNormal.x = ringVertex.x;
  36876. ringNormal.z = ringVertex.z;
  36877. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36878. ringNormal.normalize();
  36879. }
  36880. // keep first ring vertex values for enclose
  36881. if (j === 0) {
  36882. ringFirstVertex.copyFrom(ringVertex);
  36883. ringFirstNormal.copyFrom(ringNormal);
  36884. }
  36885. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36886. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36887. if (hasRings) {
  36888. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36889. }
  36890. else {
  36891. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36892. }
  36893. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36894. if (faceColors) {
  36895. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36896. }
  36897. }
  36898. // if enclose, add four vertices and their dedicated normals
  36899. if (arc !== 1 && enclose) {
  36900. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36901. positions.push(0, ringVertex.y, 0);
  36902. positions.push(0, ringVertex.y, 0);
  36903. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36904. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36905. quadNormal.normalize();
  36906. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36907. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36908. quadNormal.normalize();
  36909. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36910. if (hasRings) {
  36911. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36912. }
  36913. else {
  36914. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36915. }
  36916. uvs.push(faceUV[s + 1].x, v);
  36917. uvs.push(faceUV[s + 1].z, v);
  36918. if (hasRings) {
  36919. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36920. }
  36921. else {
  36922. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36923. }
  36924. uvs.push(faceUV[s + 2].x, v);
  36925. uvs.push(faceUV[s + 2].z, v);
  36926. if (faceColors) {
  36927. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36928. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36929. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36930. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36931. }
  36932. }
  36933. if (cs !== s) {
  36934. cs = s;
  36935. }
  36936. }
  36937. }
  36938. // indices
  36939. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36940. var s;
  36941. i = 0;
  36942. for (s = 0; s < subdivisions; s++) {
  36943. var i0 = 0;
  36944. var i1 = 0;
  36945. var i2 = 0;
  36946. var i3 = 0;
  36947. for (j = 0; j < tessellation; j++) {
  36948. i0 = i * (e + 1) + j;
  36949. i1 = (i + 1) * (e + 1) + j;
  36950. i2 = i * (e + 1) + (j + 1);
  36951. i3 = (i + 1) * (e + 1) + (j + 1);
  36952. indices.push(i0, i1, i2);
  36953. indices.push(i3, i2, i1);
  36954. }
  36955. if (arc !== 1 && enclose) { // if enclose, add two quads
  36956. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36957. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36958. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36959. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36960. }
  36961. i = (hasRings) ? (i + 2) : (i + 1);
  36962. }
  36963. // Caps
  36964. var createCylinderCap = function (isTop) {
  36965. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36966. if (radius === 0) {
  36967. return;
  36968. }
  36969. // Cap positions, normals & uvs
  36970. var angle;
  36971. var circleVector;
  36972. var i;
  36973. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36974. var c = null;
  36975. if (faceColors) {
  36976. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36977. }
  36978. // cap center
  36979. var vbase = positions.length / 3;
  36980. var offset = isTop ? height / 2 : -height / 2;
  36981. var center = new BABYLON.Vector3(0, offset, 0);
  36982. positions.push(center.x, center.y, center.z);
  36983. normals.push(0, isTop ? 1 : -1, 0);
  36984. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36985. if (c) {
  36986. colors.push(c.r, c.g, c.b, c.a);
  36987. }
  36988. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36989. for (i = 0; i <= tessellation; i++) {
  36990. angle = Math.PI * 2 * i * arc / tessellation;
  36991. var cos = Math.cos(-angle);
  36992. var sin = Math.sin(-angle);
  36993. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36994. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36995. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36996. normals.push(0, isTop ? 1 : -1, 0);
  36997. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36998. if (c) {
  36999. colors.push(c.r, c.g, c.b, c.a);
  37000. }
  37001. }
  37002. // Cap indices
  37003. for (i = 0; i < tessellation; i++) {
  37004. if (!isTop) {
  37005. indices.push(vbase);
  37006. indices.push(vbase + (i + 1));
  37007. indices.push(vbase + (i + 2));
  37008. }
  37009. else {
  37010. indices.push(vbase);
  37011. indices.push(vbase + (i + 2));
  37012. indices.push(vbase + (i + 1));
  37013. }
  37014. }
  37015. };
  37016. // add caps to geometry
  37017. createCylinderCap(false);
  37018. createCylinderCap(true);
  37019. // Sides
  37020. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37021. var vertexData = new VertexData();
  37022. vertexData.indices = indices;
  37023. vertexData.positions = positions;
  37024. vertexData.normals = normals;
  37025. vertexData.uvs = uvs;
  37026. if (faceColors) {
  37027. vertexData.colors = colors;
  37028. }
  37029. return vertexData;
  37030. };
  37031. /**
  37032. * Creates the VertexData for a torus
  37033. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37034. * * diameter the diameter of the torus, optional default 1
  37035. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37036. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37037. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37038. * * 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)
  37039. * * 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)
  37040. * @returns the VertexData of the torus
  37041. */
  37042. VertexData.CreateTorus = function (options) {
  37043. var indices = [];
  37044. var positions = [];
  37045. var normals = [];
  37046. var uvs = [];
  37047. var diameter = options.diameter || 1;
  37048. var thickness = options.thickness || 0.5;
  37049. var tessellation = options.tessellation || 16;
  37050. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37051. var stride = tessellation + 1;
  37052. for (var i = 0; i <= tessellation; i++) {
  37053. var u = i / tessellation;
  37054. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37055. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37056. for (var j = 0; j <= tessellation; j++) {
  37057. var v = 1 - j / tessellation;
  37058. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37059. var dx = Math.cos(innerAngle);
  37060. var dy = Math.sin(innerAngle);
  37061. // Create a vertex.
  37062. var normal = new BABYLON.Vector3(dx, dy, 0);
  37063. var position = normal.scale(thickness / 2);
  37064. var textureCoordinate = new BABYLON.Vector2(u, v);
  37065. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37066. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37067. positions.push(position.x, position.y, position.z);
  37068. normals.push(normal.x, normal.y, normal.z);
  37069. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37070. // And create indices for two triangles.
  37071. var nextI = (i + 1) % stride;
  37072. var nextJ = (j + 1) % stride;
  37073. indices.push(i * stride + j);
  37074. indices.push(i * stride + nextJ);
  37075. indices.push(nextI * stride + j);
  37076. indices.push(i * stride + nextJ);
  37077. indices.push(nextI * stride + nextJ);
  37078. indices.push(nextI * stride + j);
  37079. }
  37080. }
  37081. // Sides
  37082. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37083. // Result
  37084. var vertexData = new VertexData();
  37085. vertexData.indices = indices;
  37086. vertexData.positions = positions;
  37087. vertexData.normals = normals;
  37088. vertexData.uvs = uvs;
  37089. return vertexData;
  37090. };
  37091. /**
  37092. * Creates the VertexData of the LineSystem
  37093. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37094. * - lines an array of lines, each line being an array of successive Vector3
  37095. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37096. * @returns the VertexData of the LineSystem
  37097. */
  37098. VertexData.CreateLineSystem = function (options) {
  37099. var indices = [];
  37100. var positions = [];
  37101. var lines = options.lines;
  37102. var colors = options.colors;
  37103. var vertexColors = [];
  37104. var idx = 0;
  37105. for (var l = 0; l < lines.length; l++) {
  37106. var points = lines[l];
  37107. for (var index = 0; index < points.length; index++) {
  37108. positions.push(points[index].x, points[index].y, points[index].z);
  37109. if (colors) {
  37110. var color = colors[l];
  37111. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37112. }
  37113. if (index > 0) {
  37114. indices.push(idx - 1);
  37115. indices.push(idx);
  37116. }
  37117. idx++;
  37118. }
  37119. }
  37120. var vertexData = new VertexData();
  37121. vertexData.indices = indices;
  37122. vertexData.positions = positions;
  37123. if (colors) {
  37124. vertexData.colors = vertexColors;
  37125. }
  37126. return vertexData;
  37127. };
  37128. /**
  37129. * Create the VertexData for a DashedLines
  37130. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37131. * - points an array successive Vector3
  37132. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37133. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37134. * - dashNb the intended total number of dashes, optional, default 200
  37135. * @returns the VertexData for the DashedLines
  37136. */
  37137. VertexData.CreateDashedLines = function (options) {
  37138. var dashSize = options.dashSize || 3;
  37139. var gapSize = options.gapSize || 1;
  37140. var dashNb = options.dashNb || 200;
  37141. var points = options.points;
  37142. var positions = new Array();
  37143. var indices = new Array();
  37144. var curvect = BABYLON.Vector3.Zero();
  37145. var lg = 0;
  37146. var nb = 0;
  37147. var shft = 0;
  37148. var dashshft = 0;
  37149. var curshft = 0;
  37150. var idx = 0;
  37151. var i = 0;
  37152. for (i = 0; i < points.length - 1; i++) {
  37153. points[i + 1].subtractToRef(points[i], curvect);
  37154. lg += curvect.length();
  37155. }
  37156. shft = lg / dashNb;
  37157. dashshft = dashSize * shft / (dashSize + gapSize);
  37158. for (i = 0; i < points.length - 1; i++) {
  37159. points[i + 1].subtractToRef(points[i], curvect);
  37160. nb = Math.floor(curvect.length() / shft);
  37161. curvect.normalize();
  37162. for (var j = 0; j < nb; j++) {
  37163. curshft = shft * j;
  37164. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37165. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37166. indices.push(idx, idx + 1);
  37167. idx += 2;
  37168. }
  37169. }
  37170. // Result
  37171. var vertexData = new VertexData();
  37172. vertexData.positions = positions;
  37173. vertexData.indices = indices;
  37174. return vertexData;
  37175. };
  37176. /**
  37177. * Creates the VertexData for a Ground
  37178. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37179. * - width the width (x direction) of the ground, optional, default 1
  37180. * - height the height (z direction) of the ground, optional, default 1
  37181. * - subdivisions the number of subdivisions per side, optional, default 1
  37182. * @returns the VertexData of the Ground
  37183. */
  37184. VertexData.CreateGround = function (options) {
  37185. var indices = [];
  37186. var positions = [];
  37187. var normals = [];
  37188. var uvs = [];
  37189. var row, col;
  37190. var width = options.width || 1;
  37191. var height = options.height || 1;
  37192. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37193. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37194. for (row = 0; row <= subdivisionsY; row++) {
  37195. for (col = 0; col <= subdivisionsX; col++) {
  37196. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37197. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37198. positions.push(position.x, position.y, position.z);
  37199. normals.push(normal.x, normal.y, normal.z);
  37200. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37201. }
  37202. }
  37203. for (row = 0; row < subdivisionsY; row++) {
  37204. for (col = 0; col < subdivisionsX; col++) {
  37205. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37206. indices.push(col + 1 + row * (subdivisionsX + 1));
  37207. indices.push(col + row * (subdivisionsX + 1));
  37208. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37209. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37210. indices.push(col + row * (subdivisionsX + 1));
  37211. }
  37212. }
  37213. // Result
  37214. var vertexData = new VertexData();
  37215. vertexData.indices = indices;
  37216. vertexData.positions = positions;
  37217. vertexData.normals = normals;
  37218. vertexData.uvs = uvs;
  37219. return vertexData;
  37220. };
  37221. /**
  37222. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37223. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37224. * * xmin the ground minimum X coordinate, optional, default -1
  37225. * * zmin the ground minimum Z coordinate, optional, default -1
  37226. * * xmax the ground maximum X coordinate, optional, default 1
  37227. * * zmax the ground maximum Z coordinate, optional, default 1
  37228. * * 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}
  37229. * * 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}
  37230. * @returns the VertexData of the TiledGround
  37231. */
  37232. VertexData.CreateTiledGround = function (options) {
  37233. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37234. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37235. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37236. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37237. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37238. var precision = options.precision || { w: 1, h: 1 };
  37239. var indices = new Array();
  37240. var positions = new Array();
  37241. var normals = new Array();
  37242. var uvs = new Array();
  37243. var row, col, tileRow, tileCol;
  37244. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37245. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37246. precision.w = (precision.w < 1) ? 1 : precision.w;
  37247. precision.h = (precision.h < 1) ? 1 : precision.h;
  37248. var tileSize = {
  37249. 'w': (xmax - xmin) / subdivisions.w,
  37250. 'h': (zmax - zmin) / subdivisions.h
  37251. };
  37252. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37253. // Indices
  37254. var base = positions.length / 3;
  37255. var rowLength = precision.w + 1;
  37256. for (row = 0; row < precision.h; row++) {
  37257. for (col = 0; col < precision.w; col++) {
  37258. var square = [
  37259. base + col + row * rowLength,
  37260. base + (col + 1) + row * rowLength,
  37261. base + (col + 1) + (row + 1) * rowLength,
  37262. base + col + (row + 1) * rowLength
  37263. ];
  37264. indices.push(square[1]);
  37265. indices.push(square[2]);
  37266. indices.push(square[3]);
  37267. indices.push(square[0]);
  37268. indices.push(square[1]);
  37269. indices.push(square[3]);
  37270. }
  37271. }
  37272. // Position, normals and uvs
  37273. var position = BABYLON.Vector3.Zero();
  37274. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37275. for (row = 0; row <= precision.h; row++) {
  37276. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37277. for (col = 0; col <= precision.w; col++) {
  37278. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37279. position.y = 0;
  37280. positions.push(position.x, position.y, position.z);
  37281. normals.push(normal.x, normal.y, normal.z);
  37282. uvs.push(col / precision.w, row / precision.h);
  37283. }
  37284. }
  37285. }
  37286. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37287. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37288. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37289. }
  37290. }
  37291. // Result
  37292. var vertexData = new VertexData();
  37293. vertexData.indices = indices;
  37294. vertexData.positions = positions;
  37295. vertexData.normals = normals;
  37296. vertexData.uvs = uvs;
  37297. return vertexData;
  37298. };
  37299. /**
  37300. * Creates the VertexData of the Ground designed from a heightmap
  37301. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37302. * * width the width (x direction) of the ground
  37303. * * height the height (z direction) of the ground
  37304. * * subdivisions the number of subdivisions per side
  37305. * * minHeight the minimum altitude on the ground, optional, default 0
  37306. * * maxHeight the maximum altitude on the ground, optional default 1
  37307. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37308. * * buffer the array holding the image color data
  37309. * * bufferWidth the width of image
  37310. * * bufferHeight the height of image
  37311. * @returns the VertexData of the Ground designed from a heightmap
  37312. */
  37313. VertexData.CreateGroundFromHeightMap = function (options) {
  37314. var indices = [];
  37315. var positions = [];
  37316. var normals = [];
  37317. var uvs = [];
  37318. var row, col;
  37319. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37320. // Vertices
  37321. for (row = 0; row <= options.subdivisions; row++) {
  37322. for (col = 0; col <= options.subdivisions; col++) {
  37323. 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));
  37324. // Compute height
  37325. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37326. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37327. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37328. var r = options.buffer[pos] / 255.0;
  37329. var g = options.buffer[pos + 1] / 255.0;
  37330. var b = options.buffer[pos + 2] / 255.0;
  37331. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37332. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37333. // Add vertex
  37334. positions.push(position.x, position.y, position.z);
  37335. normals.push(0, 0, 0);
  37336. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37337. }
  37338. }
  37339. // Indices
  37340. for (row = 0; row < options.subdivisions; row++) {
  37341. for (col = 0; col < options.subdivisions; col++) {
  37342. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37343. indices.push(col + 1 + row * (options.subdivisions + 1));
  37344. indices.push(col + row * (options.subdivisions + 1));
  37345. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37346. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37347. indices.push(col + row * (options.subdivisions + 1));
  37348. }
  37349. }
  37350. // Normals
  37351. VertexData.ComputeNormals(positions, indices, normals);
  37352. // Result
  37353. var vertexData = new VertexData();
  37354. vertexData.indices = indices;
  37355. vertexData.positions = positions;
  37356. vertexData.normals = normals;
  37357. vertexData.uvs = uvs;
  37358. return vertexData;
  37359. };
  37360. /**
  37361. * Creates the VertexData for a Plane
  37362. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37363. * * size sets the width and height of the plane to the value of size, optional default 1
  37364. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37365. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37366. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37367. * * 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)
  37368. * * 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)
  37369. * @returns the VertexData of the box
  37370. */
  37371. VertexData.CreatePlane = function (options) {
  37372. var indices = [];
  37373. var positions = [];
  37374. var normals = [];
  37375. var uvs = [];
  37376. var width = options.width || options.size || 1;
  37377. var height = options.height || options.size || 1;
  37378. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37379. // Vertices
  37380. var halfWidth = width / 2.0;
  37381. var halfHeight = height / 2.0;
  37382. positions.push(-halfWidth, -halfHeight, 0);
  37383. normals.push(0, 0, -1.0);
  37384. uvs.push(0.0, 0.0);
  37385. positions.push(halfWidth, -halfHeight, 0);
  37386. normals.push(0, 0, -1.0);
  37387. uvs.push(1.0, 0.0);
  37388. positions.push(halfWidth, halfHeight, 0);
  37389. normals.push(0, 0, -1.0);
  37390. uvs.push(1.0, 1.0);
  37391. positions.push(-halfWidth, halfHeight, 0);
  37392. normals.push(0, 0, -1.0);
  37393. uvs.push(0.0, 1.0);
  37394. // Indices
  37395. indices.push(0);
  37396. indices.push(1);
  37397. indices.push(2);
  37398. indices.push(0);
  37399. indices.push(2);
  37400. indices.push(3);
  37401. // Sides
  37402. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37403. // Result
  37404. var vertexData = new VertexData();
  37405. vertexData.indices = indices;
  37406. vertexData.positions = positions;
  37407. vertexData.normals = normals;
  37408. vertexData.uvs = uvs;
  37409. return vertexData;
  37410. };
  37411. /**
  37412. * Creates the VertexData of the Disc or regular Polygon
  37413. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37414. * * radius the radius of the disc, optional default 0.5
  37415. * * tessellation the number of polygon sides, optional, default 64
  37416. * * 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
  37417. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37418. * * 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)
  37419. * * 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)
  37420. * @returns the VertexData of the box
  37421. */
  37422. VertexData.CreateDisc = function (options) {
  37423. var positions = new Array();
  37424. var indices = new Array();
  37425. var normals = new Array();
  37426. var uvs = new Array();
  37427. var radius = options.radius || 0.5;
  37428. var tessellation = options.tessellation || 64;
  37429. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37430. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37431. // positions and uvs
  37432. positions.push(0, 0, 0); // disc center first
  37433. uvs.push(0.5, 0.5);
  37434. var theta = Math.PI * 2 * arc;
  37435. var step = theta / tessellation;
  37436. for (var a = 0; a < theta; a += step) {
  37437. var x = Math.cos(a);
  37438. var y = Math.sin(a);
  37439. var u = (x + 1) / 2;
  37440. var v = (1 - y) / 2;
  37441. positions.push(radius * x, radius * y, 0);
  37442. uvs.push(u, v);
  37443. }
  37444. if (arc === 1) {
  37445. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37446. uvs.push(uvs[2], uvs[3]);
  37447. }
  37448. //indices
  37449. var vertexNb = positions.length / 3;
  37450. for (var i = 1; i < vertexNb - 1; i++) {
  37451. indices.push(i + 1, 0, i);
  37452. }
  37453. // result
  37454. VertexData.ComputeNormals(positions, indices, normals);
  37455. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37456. var vertexData = new VertexData();
  37457. vertexData.indices = indices;
  37458. vertexData.positions = positions;
  37459. vertexData.normals = normals;
  37460. vertexData.uvs = uvs;
  37461. return vertexData;
  37462. };
  37463. /**
  37464. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37465. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37466. * @param polygon a mesh built from polygonTriangulation.build()
  37467. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37468. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37469. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37470. * @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)
  37471. * @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)
  37472. * @returns the VertexData of the Polygon
  37473. */
  37474. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37475. var faceUV = fUV || new Array(3);
  37476. var faceColors = fColors;
  37477. var colors = [];
  37478. // default face colors and UV if undefined
  37479. for (var f = 0; f < 3; f++) {
  37480. if (faceUV[f] === undefined) {
  37481. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37482. }
  37483. if (faceColors && faceColors[f] === undefined) {
  37484. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37485. }
  37486. }
  37487. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37488. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37489. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37490. var indices = polygon.getIndices();
  37491. // set face colours and textures
  37492. var idx = 0;
  37493. var face = 0;
  37494. for (var index = 0; index < normals.length; index += 3) {
  37495. //Edge Face no. 1
  37496. if (Math.abs(normals[index + 1]) < 0.001) {
  37497. face = 1;
  37498. }
  37499. //Top Face no. 0
  37500. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37501. face = 0;
  37502. }
  37503. //Bottom Face no. 2
  37504. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37505. face = 2;
  37506. }
  37507. idx = index / 3;
  37508. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37509. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37510. if (faceColors) {
  37511. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37512. }
  37513. }
  37514. // sides
  37515. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37516. // Result
  37517. var vertexData = new VertexData();
  37518. vertexData.indices = indices;
  37519. vertexData.positions = positions;
  37520. vertexData.normals = normals;
  37521. vertexData.uvs = uvs;
  37522. if (faceColors) {
  37523. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37524. vertexData.colors = totalColors;
  37525. }
  37526. return vertexData;
  37527. };
  37528. /**
  37529. * Creates the VertexData of the IcoSphere
  37530. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37531. * * radius the radius of the IcoSphere, optional default 1
  37532. * * radiusX allows stretching in the x direction, optional, default radius
  37533. * * radiusY allows stretching in the y direction, optional, default radius
  37534. * * radiusZ allows stretching in the z direction, optional, default radius
  37535. * * flat when true creates a flat shaded mesh, optional, default true
  37536. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37537. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37538. * * 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)
  37539. * * 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)
  37540. * @returns the VertexData of the IcoSphere
  37541. */
  37542. VertexData.CreateIcoSphere = function (options) {
  37543. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37544. var radius = options.radius || 1;
  37545. var flat = (options.flat === undefined) ? true : options.flat;
  37546. var subdivisions = options.subdivisions || 4;
  37547. var radiusX = options.radiusX || radius;
  37548. var radiusY = options.radiusY || radius;
  37549. var radiusZ = options.radiusZ || radius;
  37550. var t = (1 + Math.sqrt(5)) / 2;
  37551. // 12 vertex x,y,z
  37552. var ico_vertices = [
  37553. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37554. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37555. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37556. ];
  37557. // index of 3 vertex makes a face of icopshere
  37558. var ico_indices = [
  37559. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37560. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37561. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37562. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37563. ];
  37564. // vertex for uv have aliased position, not for UV
  37565. var vertices_unalias_id = [
  37566. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37567. // vertex alias
  37568. 0,
  37569. 2,
  37570. 3,
  37571. 3,
  37572. 3,
  37573. 4,
  37574. 7,
  37575. 8,
  37576. 9,
  37577. 9,
  37578. 10,
  37579. 11 // 23: B + 12
  37580. ];
  37581. // uv as integer step (not pixels !)
  37582. var ico_vertexuv = [
  37583. 5, 1, 3, 1, 6, 4, 0, 0,
  37584. 5, 3, 4, 2, 2, 2, 4, 0,
  37585. 2, 0, 1, 1, 6, 0, 6, 2,
  37586. // vertex alias (for same vertex on different faces)
  37587. 0, 4,
  37588. 3, 3,
  37589. 4, 4,
  37590. 3, 1,
  37591. 4, 2,
  37592. 4, 4,
  37593. 0, 2,
  37594. 1, 1,
  37595. 2, 2,
  37596. 3, 3,
  37597. 1, 3,
  37598. 2, 4 // 23: B + 12
  37599. ];
  37600. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37601. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37602. // First island of uv mapping
  37603. // v = 4h 3+ 2
  37604. // v = 3h 9+ 4
  37605. // v = 2h 9+ 5 B
  37606. // v = 1h 9 1 0
  37607. // v = 0h 3 8 7 A
  37608. // u = 0 1 2 3 4 5 6 *a
  37609. // Second island of uv mapping
  37610. // v = 4h 0+ B+ 4+
  37611. // v = 3h A+ 2+
  37612. // v = 2h 7+ 6 3+
  37613. // v = 1h 8+ 3+
  37614. // v = 0h
  37615. // u = 0 1 2 3 4 5 6 *a
  37616. // Face layout on texture UV mapping
  37617. // ============
  37618. // \ 4 /\ 16 / ======
  37619. // \ / \ / /\ 11 /
  37620. // \/ 7 \/ / \ /
  37621. // ======= / 10 \/
  37622. // /\ 17 /\ =======
  37623. // / \ / \ \ 15 /\
  37624. // / 8 \/ 12 \ \ / \
  37625. // ============ \/ 6 \
  37626. // \ 18 /\ ============
  37627. // \ / \ \ 5 /\ 0 /
  37628. // \/ 13 \ \ / \ /
  37629. // ======= \/ 1 \/
  37630. // =============
  37631. // /\ 19 /\ 2 /\
  37632. // / \ / \ / \
  37633. // / 14 \/ 9 \/ 3 \
  37634. // ===================
  37635. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37636. var ustep = 138 / 1024;
  37637. var vstep = 239 / 1024;
  37638. var uoffset = 60 / 1024;
  37639. var voffset = 26 / 1024;
  37640. // Second island should have margin, not to touch the first island
  37641. // avoid any borderline artefact in pixel rounding
  37642. var island_u_offset = -40 / 1024;
  37643. var island_v_offset = +20 / 1024;
  37644. // face is either island 0 or 1 :
  37645. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37646. var island = [
  37647. 0, 0, 0, 0, 1,
  37648. 0, 0, 1, 1, 0,
  37649. 0, 0, 1, 1, 0,
  37650. 0, 1, 1, 1, 0 // 15 - 19
  37651. ];
  37652. var indices = new Array();
  37653. var positions = new Array();
  37654. var normals = new Array();
  37655. var uvs = new Array();
  37656. var current_indice = 0;
  37657. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37658. var face_vertex_pos = new Array(3);
  37659. var face_vertex_uv = new Array(3);
  37660. var v012;
  37661. for (v012 = 0; v012 < 3; v012++) {
  37662. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37663. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37664. }
  37665. // create all with normals
  37666. for (var face = 0; face < 20; face++) {
  37667. // 3 vertex per face
  37668. for (v012 = 0; v012 < 3; v012++) {
  37669. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37670. var v_id = ico_indices[3 * face + v012];
  37671. // vertex have 3D position (x,y,z)
  37672. 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]);
  37673. // Normalize to get normal, then scale to radius
  37674. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37675. // uv Coordinates from vertex ID
  37676. 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);
  37677. }
  37678. // Subdivide the face (interpolate pos, norm, uv)
  37679. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37680. // - norm is linear interpolation of vertex corner normal
  37681. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37682. // - uv is linear interpolation
  37683. //
  37684. // Topology is as below for sub-divide by 2
  37685. // vertex shown as v0,v1,v2
  37686. // interp index is i1 to progress in range [v0,v1[
  37687. // interp index is i2 to progress in range [v0,v2[
  37688. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37689. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37690. //
  37691. //
  37692. // i2 v2
  37693. // ^ ^
  37694. // / / \
  37695. // / / \
  37696. // / / \
  37697. // / / (0,1) \
  37698. // / #---------\
  37699. // / / \ (0,0)'/ \
  37700. // / / \ / \
  37701. // / / \ / \
  37702. // / / (0,0) \ / (1,0) \
  37703. // / #---------#---------\
  37704. // v0 v1
  37705. //
  37706. // --------------------> i1
  37707. //
  37708. // interp of (i1,i2):
  37709. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37710. // along i1 : lerp(x0,x1, i1/(S-i2))
  37711. //
  37712. // centroid of triangle is needed to get help normal computation
  37713. // (c1,c2) are used for centroid location
  37714. var interp_vertex = function (i1, i2, c1, c2) {
  37715. // vertex is interpolated from
  37716. // - face_vertex_pos[0..2]
  37717. // - face_vertex_uv[0..2]
  37718. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37719. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37720. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37721. pos_interp.normalize();
  37722. var vertex_normal;
  37723. if (flat) {
  37724. // in flat mode, recalculate normal as face centroid normal
  37725. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37726. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37727. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37728. }
  37729. else {
  37730. // in smooth mode, recalculate normal from each single vertex position
  37731. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37732. }
  37733. // Vertex normal need correction due to X,Y,Z radius scaling
  37734. vertex_normal.x /= radiusX;
  37735. vertex_normal.y /= radiusY;
  37736. vertex_normal.z /= radiusZ;
  37737. vertex_normal.normalize();
  37738. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37739. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37740. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37741. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37742. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37743. uvs.push(uv_interp.x, uv_interp.y);
  37744. // push each vertex has member of a face
  37745. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37746. indices.push(current_indice);
  37747. current_indice++;
  37748. };
  37749. for (var i2 = 0; i2 < subdivisions; i2++) {
  37750. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37751. // face : (i1,i2) for /\ :
  37752. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37753. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37754. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37755. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37756. if (i1 + i2 + 1 < subdivisions) {
  37757. // face : (i1,i2)' for \/ :
  37758. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37759. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37760. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37761. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37762. }
  37763. }
  37764. }
  37765. }
  37766. // Sides
  37767. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37768. // Result
  37769. var vertexData = new VertexData();
  37770. vertexData.indices = indices;
  37771. vertexData.positions = positions;
  37772. vertexData.normals = normals;
  37773. vertexData.uvs = uvs;
  37774. return vertexData;
  37775. };
  37776. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37777. /**
  37778. * Creates the VertexData for a Polyhedron
  37779. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37780. * * type provided types are:
  37781. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37782. * * 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)
  37783. * * size the size of the IcoSphere, optional default 1
  37784. * * sizeX allows stretching in the x direction, optional, default size
  37785. * * sizeY allows stretching in the y direction, optional, default size
  37786. * * sizeZ allows stretching in the z direction, optional, default size
  37787. * * 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
  37788. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37789. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37790. * * flat when true creates a flat shaded mesh, optional, default true
  37791. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37792. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37793. * * 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)
  37794. * * 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)
  37795. * @returns the VertexData of the Polyhedron
  37796. */
  37797. VertexData.CreatePolyhedron = function (options) {
  37798. // provided polyhedron types :
  37799. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37800. // 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)
  37801. var polyhedra = [];
  37802. 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]] };
  37803. 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]] };
  37804. polyhedra[2] = {
  37805. 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]],
  37806. 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]]
  37807. };
  37808. polyhedra[3] = {
  37809. 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]],
  37810. 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]]
  37811. };
  37812. polyhedra[4] = {
  37813. 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]],
  37814. 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]]
  37815. };
  37816. 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]] };
  37817. 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]] };
  37818. 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]] };
  37819. 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]] };
  37820. 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]] };
  37821. 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]] };
  37822. 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]] };
  37823. 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]] };
  37824. 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]] };
  37825. polyhedra[14] = {
  37826. 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]],
  37827. 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]]
  37828. };
  37829. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37830. var size = options.size;
  37831. var sizeX = options.sizeX || size || 1;
  37832. var sizeY = options.sizeY || size || 1;
  37833. var sizeZ = options.sizeZ || size || 1;
  37834. var data = options.custom || polyhedra[type];
  37835. var nbfaces = data.face.length;
  37836. var faceUV = options.faceUV || new Array(nbfaces);
  37837. var faceColors = options.faceColors;
  37838. var flat = (options.flat === undefined) ? true : options.flat;
  37839. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37840. var positions = new Array();
  37841. var indices = new Array();
  37842. var normals = new Array();
  37843. var uvs = new Array();
  37844. var colors = new Array();
  37845. var index = 0;
  37846. var faceIdx = 0; // face cursor in the array "indexes"
  37847. var indexes = new Array();
  37848. var i = 0;
  37849. var f = 0;
  37850. var u, v, ang, x, y, tmp;
  37851. // default face colors and UV if undefined
  37852. if (flat) {
  37853. for (f = 0; f < nbfaces; f++) {
  37854. if (faceColors && faceColors[f] === undefined) {
  37855. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37856. }
  37857. if (faceUV && faceUV[f] === undefined) {
  37858. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37859. }
  37860. }
  37861. }
  37862. if (!flat) {
  37863. for (i = 0; i < data.vertex.length; i++) {
  37864. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37865. uvs.push(0, 0);
  37866. }
  37867. for (f = 0; f < nbfaces; f++) {
  37868. for (i = 0; i < data.face[f].length - 2; i++) {
  37869. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37870. }
  37871. }
  37872. }
  37873. else {
  37874. for (f = 0; f < nbfaces; f++) {
  37875. var fl = data.face[f].length; // number of vertices of the current face
  37876. ang = 2 * Math.PI / fl;
  37877. x = 0.5 * Math.tan(ang / 2);
  37878. y = 0.5;
  37879. // positions, uvs, colors
  37880. for (i = 0; i < fl; i++) {
  37881. // positions
  37882. 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);
  37883. indexes.push(index);
  37884. index++;
  37885. // uvs
  37886. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37887. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37888. uvs.push(u, v);
  37889. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37890. y = x * Math.sin(ang) + y * Math.cos(ang);
  37891. x = tmp;
  37892. // colors
  37893. if (faceColors) {
  37894. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37895. }
  37896. }
  37897. // indices from indexes
  37898. for (i = 0; i < fl - 2; i++) {
  37899. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37900. }
  37901. faceIdx += fl;
  37902. }
  37903. }
  37904. VertexData.ComputeNormals(positions, indices, normals);
  37905. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37906. var vertexData = new VertexData();
  37907. vertexData.positions = positions;
  37908. vertexData.indices = indices;
  37909. vertexData.normals = normals;
  37910. vertexData.uvs = uvs;
  37911. if (faceColors && flat) {
  37912. vertexData.colors = colors;
  37913. }
  37914. return vertexData;
  37915. };
  37916. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37917. /**
  37918. * Creates the VertexData for a TorusKnot
  37919. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37920. * * radius the radius of the torus knot, optional, default 2
  37921. * * tube the thickness of the tube, optional, default 0.5
  37922. * * radialSegments the number of sides on each tube segments, optional, default 32
  37923. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37924. * * p the number of windings around the z axis, optional, default 2
  37925. * * q the number of windings around the x axis, optional, default 3
  37926. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37927. * * 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)
  37928. * * 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)
  37929. * @returns the VertexData of the Torus Knot
  37930. */
  37931. VertexData.CreateTorusKnot = function (options) {
  37932. var indices = new Array();
  37933. var positions = new Array();
  37934. var normals = new Array();
  37935. var uvs = new Array();
  37936. var radius = options.radius || 2;
  37937. var tube = options.tube || 0.5;
  37938. var radialSegments = options.radialSegments || 32;
  37939. var tubularSegments = options.tubularSegments || 32;
  37940. var p = options.p || 2;
  37941. var q = options.q || 3;
  37942. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37943. // Helper
  37944. var getPos = function (angle) {
  37945. var cu = Math.cos(angle);
  37946. var su = Math.sin(angle);
  37947. var quOverP = q / p * angle;
  37948. var cs = Math.cos(quOverP);
  37949. var tx = radius * (2 + cs) * 0.5 * cu;
  37950. var ty = radius * (2 + cs) * su * 0.5;
  37951. var tz = radius * Math.sin(quOverP) * 0.5;
  37952. return new BABYLON.Vector3(tx, ty, tz);
  37953. };
  37954. // Vertices
  37955. var i;
  37956. var j;
  37957. for (i = 0; i <= radialSegments; i++) {
  37958. var modI = i % radialSegments;
  37959. var u = modI / radialSegments * 2 * p * Math.PI;
  37960. var p1 = getPos(u);
  37961. var p2 = getPos(u + 0.01);
  37962. var tang = p2.subtract(p1);
  37963. var n = p2.add(p1);
  37964. var bitan = BABYLON.Vector3.Cross(tang, n);
  37965. n = BABYLON.Vector3.Cross(bitan, tang);
  37966. bitan.normalize();
  37967. n.normalize();
  37968. for (j = 0; j < tubularSegments; j++) {
  37969. var modJ = j % tubularSegments;
  37970. var v = modJ / tubularSegments * 2 * Math.PI;
  37971. var cx = -tube * Math.cos(v);
  37972. var cy = tube * Math.sin(v);
  37973. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37974. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37975. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37976. uvs.push(i / radialSegments);
  37977. uvs.push(j / tubularSegments);
  37978. }
  37979. }
  37980. for (i = 0; i < radialSegments; i++) {
  37981. for (j = 0; j < tubularSegments; j++) {
  37982. var jNext = (j + 1) % tubularSegments;
  37983. var a = i * tubularSegments + j;
  37984. var b = (i + 1) * tubularSegments + j;
  37985. var c = (i + 1) * tubularSegments + jNext;
  37986. var d = i * tubularSegments + jNext;
  37987. indices.push(d);
  37988. indices.push(b);
  37989. indices.push(a);
  37990. indices.push(d);
  37991. indices.push(c);
  37992. indices.push(b);
  37993. }
  37994. }
  37995. // Normals
  37996. VertexData.ComputeNormals(positions, indices, normals);
  37997. // Sides
  37998. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37999. // Result
  38000. var vertexData = new VertexData();
  38001. vertexData.indices = indices;
  38002. vertexData.positions = positions;
  38003. vertexData.normals = normals;
  38004. vertexData.uvs = uvs;
  38005. return vertexData;
  38006. };
  38007. // Tools
  38008. /**
  38009. * Compute normals for given positions and indices
  38010. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38011. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38012. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38013. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38014. * * facetNormals : optional array of facet normals (vector3)
  38015. * * facetPositions : optional array of facet positions (vector3)
  38016. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38017. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38018. * * bInfo : optional bounding info, required for facetPartitioning computation
  38019. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38020. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38021. * * useRightHandedSystem: optional boolean to for right handed system computation
  38022. * * depthSort : optional boolean to enable the facet depth sort computation
  38023. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38024. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38025. */
  38026. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38027. // temporary scalar variables
  38028. var index = 0; // facet index
  38029. var p1p2x = 0.0; // p1p2 vector x coordinate
  38030. var p1p2y = 0.0; // p1p2 vector y coordinate
  38031. var p1p2z = 0.0; // p1p2 vector z coordinate
  38032. var p3p2x = 0.0; // p3p2 vector x coordinate
  38033. var p3p2y = 0.0; // p3p2 vector y coordinate
  38034. var p3p2z = 0.0; // p3p2 vector z coordinate
  38035. var faceNormalx = 0.0; // facet normal x coordinate
  38036. var faceNormaly = 0.0; // facet normal y coordinate
  38037. var faceNormalz = 0.0; // facet normal z coordinate
  38038. var length = 0.0; // facet normal length before normalization
  38039. var v1x = 0; // vector1 x index in the positions array
  38040. var v1y = 0; // vector1 y index in the positions array
  38041. var v1z = 0; // vector1 z index in the positions array
  38042. var v2x = 0; // vector2 x index in the positions array
  38043. var v2y = 0; // vector2 y index in the positions array
  38044. var v2z = 0; // vector2 z index in the positions array
  38045. var v3x = 0; // vector3 x index in the positions array
  38046. var v3y = 0; // vector3 y index in the positions array
  38047. var v3z = 0; // vector3 z index in the positions array
  38048. var computeFacetNormals = false;
  38049. var computeFacetPositions = false;
  38050. var computeFacetPartitioning = false;
  38051. var computeDepthSort = false;
  38052. var faceNormalSign = 1;
  38053. var ratio = 0;
  38054. var distanceTo = null;
  38055. if (options) {
  38056. computeFacetNormals = (options.facetNormals) ? true : false;
  38057. computeFacetPositions = (options.facetPositions) ? true : false;
  38058. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38059. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38060. ratio = options.ratio || 0;
  38061. computeDepthSort = (options.depthSort) ? true : false;
  38062. distanceTo = (options.distanceTo);
  38063. if (computeDepthSort) {
  38064. if (distanceTo === undefined) {
  38065. distanceTo = BABYLON.Vector3.Zero();
  38066. }
  38067. var depthSortedFacets = options.depthSortedFacets;
  38068. }
  38069. }
  38070. // facetPartitioning reinit if needed
  38071. var xSubRatio = 0;
  38072. var ySubRatio = 0;
  38073. var zSubRatio = 0;
  38074. var subSq = 0;
  38075. if (computeFacetPartitioning && options && options.bbSize) {
  38076. var ox = 0; // X partitioning index for facet position
  38077. var oy = 0; // Y partinioning index for facet position
  38078. var oz = 0; // Z partinioning index for facet position
  38079. var b1x = 0; // X partitioning index for facet v1 vertex
  38080. var b1y = 0; // Y partitioning index for facet v1 vertex
  38081. var b1z = 0; // z partitioning index for facet v1 vertex
  38082. var b2x = 0; // X partitioning index for facet v2 vertex
  38083. var b2y = 0; // Y partitioning index for facet v2 vertex
  38084. var b2z = 0; // Z partitioning index for facet v2 vertex
  38085. var b3x = 0; // X partitioning index for facet v3 vertex
  38086. var b3y = 0; // Y partitioning index for facet v3 vertex
  38087. var b3z = 0; // Z partitioning index for facet v3 vertex
  38088. var block_idx_o = 0; // facet barycenter block index
  38089. var block_idx_v1 = 0; // v1 vertex block index
  38090. var block_idx_v2 = 0; // v2 vertex block index
  38091. var block_idx_v3 = 0; // v3 vertex block index
  38092. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38093. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38094. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38095. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38096. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38097. subSq = options.subDiv.max * options.subDiv.max;
  38098. options.facetPartitioning.length = 0;
  38099. }
  38100. // reset the normals
  38101. for (index = 0; index < positions.length; index++) {
  38102. normals[index] = 0.0;
  38103. }
  38104. // Loop : 1 indice triplet = 1 facet
  38105. var nbFaces = (indices.length / 3) | 0;
  38106. for (index = 0; index < nbFaces; index++) {
  38107. // get the indexes of the coordinates of each vertex of the facet
  38108. v1x = indices[index * 3] * 3;
  38109. v1y = v1x + 1;
  38110. v1z = v1x + 2;
  38111. v2x = indices[index * 3 + 1] * 3;
  38112. v2y = v2x + 1;
  38113. v2z = v2x + 2;
  38114. v3x = indices[index * 3 + 2] * 3;
  38115. v3y = v3x + 1;
  38116. v3z = v3x + 2;
  38117. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38118. p1p2y = positions[v1y] - positions[v2y];
  38119. p1p2z = positions[v1z] - positions[v2z];
  38120. p3p2x = positions[v3x] - positions[v2x];
  38121. p3p2y = positions[v3y] - positions[v2y];
  38122. p3p2z = positions[v3z] - positions[v2z];
  38123. // compute the face normal with the cross product
  38124. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38125. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38126. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38127. // normalize this normal and store it in the array facetData
  38128. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38129. length = (length === 0) ? 1.0 : length;
  38130. faceNormalx /= length;
  38131. faceNormaly /= length;
  38132. faceNormalz /= length;
  38133. if (computeFacetNormals && options) {
  38134. options.facetNormals[index].x = faceNormalx;
  38135. options.facetNormals[index].y = faceNormaly;
  38136. options.facetNormals[index].z = faceNormalz;
  38137. }
  38138. if (computeFacetPositions && options) {
  38139. // compute and the facet barycenter coordinates in the array facetPositions
  38140. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38141. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38142. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38143. }
  38144. if (computeFacetPartitioning && options) {
  38145. // store the facet indexes in arrays in the main facetPartitioning array :
  38146. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38147. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38148. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38149. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38150. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38151. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38152. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38153. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38154. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38155. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38156. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38157. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38158. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38159. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38160. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38161. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38162. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38163. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38164. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38165. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38166. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38167. // push each facet index in each block containing the vertex
  38168. options.facetPartitioning[block_idx_v1].push(index);
  38169. if (block_idx_v2 != block_idx_v1) {
  38170. options.facetPartitioning[block_idx_v2].push(index);
  38171. }
  38172. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38173. options.facetPartitioning[block_idx_v3].push(index);
  38174. }
  38175. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38176. options.facetPartitioning[block_idx_o].push(index);
  38177. }
  38178. }
  38179. if (computeDepthSort && options && options.facetPositions) {
  38180. var dsf = depthSortedFacets[index];
  38181. dsf.ind = index * 3;
  38182. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38183. }
  38184. // compute the normals anyway
  38185. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38186. normals[v1y] += faceNormaly;
  38187. normals[v1z] += faceNormalz;
  38188. normals[v2x] += faceNormalx;
  38189. normals[v2y] += faceNormaly;
  38190. normals[v2z] += faceNormalz;
  38191. normals[v3x] += faceNormalx;
  38192. normals[v3y] += faceNormaly;
  38193. normals[v3z] += faceNormalz;
  38194. }
  38195. // last normalization of each normal
  38196. for (index = 0; index < normals.length / 3; index++) {
  38197. faceNormalx = normals[index * 3];
  38198. faceNormaly = normals[index * 3 + 1];
  38199. faceNormalz = normals[index * 3 + 2];
  38200. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38201. length = (length === 0) ? 1.0 : length;
  38202. faceNormalx /= length;
  38203. faceNormaly /= length;
  38204. faceNormalz /= length;
  38205. normals[index * 3] = faceNormalx;
  38206. normals[index * 3 + 1] = faceNormaly;
  38207. normals[index * 3 + 2] = faceNormalz;
  38208. }
  38209. };
  38210. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38211. var li = indices.length;
  38212. var ln = normals.length;
  38213. var i;
  38214. var n;
  38215. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38216. switch (sideOrientation) {
  38217. case BABYLON.Mesh.FRONTSIDE:
  38218. // nothing changed
  38219. break;
  38220. case BABYLON.Mesh.BACKSIDE:
  38221. var tmp;
  38222. // indices
  38223. for (i = 0; i < li; i += 3) {
  38224. tmp = indices[i];
  38225. indices[i] = indices[i + 2];
  38226. indices[i + 2] = tmp;
  38227. }
  38228. // normals
  38229. for (n = 0; n < ln; n++) {
  38230. normals[n] = -normals[n];
  38231. }
  38232. break;
  38233. case BABYLON.Mesh.DOUBLESIDE:
  38234. // positions
  38235. var lp = positions.length;
  38236. var l = lp / 3;
  38237. for (var p = 0; p < lp; p++) {
  38238. positions[lp + p] = positions[p];
  38239. }
  38240. // indices
  38241. for (i = 0; i < li; i += 3) {
  38242. indices[i + li] = indices[i + 2] + l;
  38243. indices[i + 1 + li] = indices[i + 1] + l;
  38244. indices[i + 2 + li] = indices[i] + l;
  38245. }
  38246. // normals
  38247. for (n = 0; n < ln; n++) {
  38248. normals[ln + n] = -normals[n];
  38249. }
  38250. // uvs
  38251. var lu = uvs.length;
  38252. var u = 0;
  38253. for (u = 0; u < lu; u++) {
  38254. uvs[u + lu] = uvs[u];
  38255. }
  38256. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38257. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38258. u = 0;
  38259. for (i = 0; i < lu / 2; i++) {
  38260. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38261. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38262. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38263. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38264. u += 2;
  38265. }
  38266. break;
  38267. }
  38268. };
  38269. /**
  38270. * Applies VertexData created from the imported parameters to the geometry
  38271. * @param parsedVertexData the parsed data from an imported file
  38272. * @param geometry the geometry to apply the VertexData to
  38273. */
  38274. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38275. var vertexData = new VertexData();
  38276. // positions
  38277. var positions = parsedVertexData.positions;
  38278. if (positions) {
  38279. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38280. }
  38281. // normals
  38282. var normals = parsedVertexData.normals;
  38283. if (normals) {
  38284. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38285. }
  38286. // tangents
  38287. var tangents = parsedVertexData.tangents;
  38288. if (tangents) {
  38289. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38290. }
  38291. // uvs
  38292. var uvs = parsedVertexData.uvs;
  38293. if (uvs) {
  38294. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38295. }
  38296. // uv2s
  38297. var uv2s = parsedVertexData.uv2s;
  38298. if (uv2s) {
  38299. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38300. }
  38301. // uv3s
  38302. var uv3s = parsedVertexData.uv3s;
  38303. if (uv3s) {
  38304. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38305. }
  38306. // uv4s
  38307. var uv4s = parsedVertexData.uv4s;
  38308. if (uv4s) {
  38309. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38310. }
  38311. // uv5s
  38312. var uv5s = parsedVertexData.uv5s;
  38313. if (uv5s) {
  38314. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38315. }
  38316. // uv6s
  38317. var uv6s = parsedVertexData.uv6s;
  38318. if (uv6s) {
  38319. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38320. }
  38321. // colors
  38322. var colors = parsedVertexData.colors;
  38323. if (colors) {
  38324. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38325. }
  38326. // matricesIndices
  38327. var matricesIndices = parsedVertexData.matricesIndices;
  38328. if (matricesIndices) {
  38329. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38330. }
  38331. // matricesWeights
  38332. var matricesWeights = parsedVertexData.matricesWeights;
  38333. if (matricesWeights) {
  38334. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38335. }
  38336. // indices
  38337. var indices = parsedVertexData.indices;
  38338. if (indices) {
  38339. vertexData.indices = indices;
  38340. }
  38341. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38342. };
  38343. return VertexData;
  38344. }());
  38345. BABYLON.VertexData = VertexData;
  38346. })(BABYLON || (BABYLON = {}));
  38347. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38348. var BABYLON;
  38349. (function (BABYLON) {
  38350. /**
  38351. * Class used to store geometry data (vertex buffers + index buffer)
  38352. */
  38353. var Geometry = /** @class */ (function () {
  38354. /**
  38355. * Creates a new geometry
  38356. * @param id defines the unique ID
  38357. * @param scene defines the hosting scene
  38358. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38359. * @param updatable defines if geometry must be updatable (false by default)
  38360. * @param mesh defines the mesh that will be associated with the geometry
  38361. */
  38362. function Geometry(id, scene, vertexData, updatable, mesh) {
  38363. if (updatable === void 0) { updatable = false; }
  38364. if (mesh === void 0) { mesh = null; }
  38365. /**
  38366. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38367. */
  38368. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38369. this._totalVertices = 0;
  38370. this._isDisposed = false;
  38371. this._indexBufferIsUpdatable = false;
  38372. this.id = id;
  38373. this._engine = scene.getEngine();
  38374. this._meshes = [];
  38375. this._scene = scene;
  38376. //Init vertex buffer cache
  38377. this._vertexBuffers = {};
  38378. this._indices = [];
  38379. this._updatable = updatable;
  38380. // vertexData
  38381. if (vertexData) {
  38382. this.setAllVerticesData(vertexData, updatable);
  38383. }
  38384. else {
  38385. this._totalVertices = 0;
  38386. this._indices = [];
  38387. }
  38388. if (this._engine.getCaps().vertexArrayObject) {
  38389. this._vertexArrayObjects = {};
  38390. }
  38391. // applyToMesh
  38392. if (mesh) {
  38393. if (mesh.getClassName() === "LinesMesh") {
  38394. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38395. this._updateExtend();
  38396. }
  38397. this.applyToMesh(mesh);
  38398. mesh.computeWorldMatrix(true);
  38399. }
  38400. }
  38401. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38402. /**
  38403. * 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
  38404. */
  38405. get: function () {
  38406. return this._boundingBias;
  38407. },
  38408. /**
  38409. * 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
  38410. */
  38411. set: function (value) {
  38412. if (this._boundingBias && this._boundingBias.equals(value)) {
  38413. return;
  38414. }
  38415. this._boundingBias = value.clone();
  38416. this._updateBoundingInfo(true, null);
  38417. },
  38418. enumerable: true,
  38419. configurable: true
  38420. });
  38421. /**
  38422. * Static function used to attach a new empty geometry to a mesh
  38423. * @param mesh defines the mesh to attach the geometry to
  38424. * @returns the new {BABYLON.Geometry}
  38425. */
  38426. Geometry.CreateGeometryForMesh = function (mesh) {
  38427. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38428. geometry.applyToMesh(mesh);
  38429. return geometry;
  38430. };
  38431. Object.defineProperty(Geometry.prototype, "extend", {
  38432. /**
  38433. * Gets the current extend of the geometry
  38434. */
  38435. get: function () {
  38436. return this._extend;
  38437. },
  38438. enumerable: true,
  38439. configurable: true
  38440. });
  38441. /**
  38442. * Gets the hosting scene
  38443. * @returns the hosting {BABYLON.Scene}
  38444. */
  38445. Geometry.prototype.getScene = function () {
  38446. return this._scene;
  38447. };
  38448. /**
  38449. * Gets the hosting engine
  38450. * @returns the hosting {BABYLON.Engine}
  38451. */
  38452. Geometry.prototype.getEngine = function () {
  38453. return this._engine;
  38454. };
  38455. /**
  38456. * Defines if the geometry is ready to use
  38457. * @returns true if the geometry is ready to be used
  38458. */
  38459. Geometry.prototype.isReady = function () {
  38460. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38461. };
  38462. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38463. /**
  38464. * Gets a value indicating that the geometry should not be serialized
  38465. */
  38466. get: function () {
  38467. for (var index = 0; index < this._meshes.length; index++) {
  38468. if (!this._meshes[index].doNotSerialize) {
  38469. return false;
  38470. }
  38471. }
  38472. return true;
  38473. },
  38474. enumerable: true,
  38475. configurable: true
  38476. });
  38477. /** @hidden */
  38478. Geometry.prototype._rebuild = function () {
  38479. if (this._vertexArrayObjects) {
  38480. this._vertexArrayObjects = {};
  38481. }
  38482. // Index buffer
  38483. if (this._meshes.length !== 0 && this._indices) {
  38484. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38485. }
  38486. // Vertex buffers
  38487. for (var key in this._vertexBuffers) {
  38488. var vertexBuffer = this._vertexBuffers[key];
  38489. vertexBuffer._rebuild();
  38490. }
  38491. };
  38492. /**
  38493. * Affects all gemetry data in one call
  38494. * @param vertexData defines the geometry data
  38495. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38496. */
  38497. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38498. vertexData.applyToGeometry(this, updatable);
  38499. this.notifyUpdate();
  38500. };
  38501. /**
  38502. * Set specific vertex data
  38503. * @param kind defines the data kind (Position, normal, etc...)
  38504. * @param data defines the vertex data to use
  38505. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38506. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38507. */
  38508. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38509. if (updatable === void 0) { updatable = false; }
  38510. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38511. this.setVerticesBuffer(buffer);
  38512. };
  38513. /**
  38514. * Removes a specific vertex data
  38515. * @param kind defines the data kind (Position, normal, etc...)
  38516. */
  38517. Geometry.prototype.removeVerticesData = function (kind) {
  38518. if (this._vertexBuffers[kind]) {
  38519. this._vertexBuffers[kind].dispose();
  38520. delete this._vertexBuffers[kind];
  38521. }
  38522. };
  38523. /**
  38524. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38525. * @param buffer defines the vertex buffer to use
  38526. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38527. */
  38528. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38529. if (totalVertices === void 0) { totalVertices = null; }
  38530. var kind = buffer.getKind();
  38531. if (this._vertexBuffers[kind]) {
  38532. this._vertexBuffers[kind].dispose();
  38533. }
  38534. this._vertexBuffers[kind] = buffer;
  38535. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38536. var data = buffer.getData();
  38537. if (totalVertices != null) {
  38538. this._totalVertices = totalVertices;
  38539. }
  38540. else {
  38541. if (data != null) {
  38542. this._totalVertices = data.length / (buffer.byteStride / 4);
  38543. }
  38544. }
  38545. this._updateExtend(data);
  38546. this._resetPointsArrayCache();
  38547. var meshes = this._meshes;
  38548. var numOfMeshes = meshes.length;
  38549. for (var index = 0; index < numOfMeshes; index++) {
  38550. var mesh = meshes[index];
  38551. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38552. mesh._createGlobalSubMesh(false);
  38553. mesh.computeWorldMatrix(true);
  38554. }
  38555. }
  38556. this.notifyUpdate(kind);
  38557. if (this._vertexArrayObjects) {
  38558. this._disposeVertexArrayObjects();
  38559. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38560. }
  38561. };
  38562. /**
  38563. * Update a specific vertex buffer
  38564. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38565. * It will do nothing if the buffer is not updatable
  38566. * @param kind defines the data kind (Position, normal, etc...)
  38567. * @param data defines the data to use
  38568. * @param offset defines the offset in the target buffer where to store the data
  38569. * @param useBytes set to true if the offset is in bytes
  38570. */
  38571. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38572. if (useBytes === void 0) { useBytes = false; }
  38573. var vertexBuffer = this.getVertexBuffer(kind);
  38574. if (!vertexBuffer) {
  38575. return;
  38576. }
  38577. vertexBuffer.updateDirectly(data, offset, useBytes);
  38578. this.notifyUpdate(kind);
  38579. };
  38580. /**
  38581. * Update a specific vertex buffer
  38582. * This function will create a new buffer if the current one is not updatable
  38583. * @param kind defines the data kind (Position, normal, etc...)
  38584. * @param data defines the data to use
  38585. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38586. */
  38587. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38588. if (updateExtends === void 0) { updateExtends = false; }
  38589. var vertexBuffer = this.getVertexBuffer(kind);
  38590. if (!vertexBuffer) {
  38591. return;
  38592. }
  38593. vertexBuffer.update(data);
  38594. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38595. this._updateBoundingInfo(updateExtends, data);
  38596. }
  38597. this.notifyUpdate(kind);
  38598. };
  38599. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38600. if (updateExtends) {
  38601. this._updateExtend(data);
  38602. }
  38603. var meshes = this._meshes;
  38604. var numOfMeshes = meshes.length;
  38605. this._resetPointsArrayCache();
  38606. for (var index = 0; index < numOfMeshes; index++) {
  38607. var mesh = meshes[index];
  38608. if (updateExtends) {
  38609. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38610. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38611. var subMesh = mesh.subMeshes[subIndex];
  38612. subMesh.refreshBoundingInfo();
  38613. }
  38614. }
  38615. }
  38616. };
  38617. /** @hidden */
  38618. Geometry.prototype._bind = function (effect, indexToBind) {
  38619. if (!effect) {
  38620. return;
  38621. }
  38622. if (indexToBind === undefined) {
  38623. indexToBind = this._indexBuffer;
  38624. }
  38625. var vbs = this.getVertexBuffers();
  38626. if (!vbs) {
  38627. return;
  38628. }
  38629. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38630. this._engine.bindBuffers(vbs, indexToBind, effect);
  38631. return;
  38632. }
  38633. // Using VAO
  38634. if (!this._vertexArrayObjects[effect.key]) {
  38635. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38636. }
  38637. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38638. };
  38639. /**
  38640. * Gets total number of vertices
  38641. * @returns the total number of vertices
  38642. */
  38643. Geometry.prototype.getTotalVertices = function () {
  38644. if (!this.isReady()) {
  38645. return 0;
  38646. }
  38647. return this._totalVertices;
  38648. };
  38649. /**
  38650. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38651. * @param kind defines the data kind (Position, normal, etc...)
  38652. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38653. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38654. * @returns a float array containing vertex data
  38655. */
  38656. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38657. var vertexBuffer = this.getVertexBuffer(kind);
  38658. if (!vertexBuffer) {
  38659. return null;
  38660. }
  38661. var data = vertexBuffer.getData();
  38662. if (!data) {
  38663. return null;
  38664. }
  38665. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38666. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38667. var count = this._totalVertices * defaultStride;
  38668. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38669. var copy_1 = new Array(count);
  38670. vertexBuffer.forEach(count, function (value, index) {
  38671. copy_1[index] = value;
  38672. });
  38673. return copy_1;
  38674. }
  38675. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38676. if (data instanceof Array) {
  38677. var offset = vertexBuffer.byteOffset / 4;
  38678. return BABYLON.Tools.Slice(data, offset, offset + count);
  38679. }
  38680. else if (data instanceof ArrayBuffer) {
  38681. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38682. }
  38683. else {
  38684. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38685. }
  38686. }
  38687. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38688. return BABYLON.Tools.Slice(data);
  38689. }
  38690. return data;
  38691. };
  38692. /**
  38693. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38694. * @param kind defines the data kind (Position, normal, etc...)
  38695. * @returns true if the vertex buffer with the specified kind is updatable
  38696. */
  38697. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38698. var vb = this._vertexBuffers[kind];
  38699. if (!vb) {
  38700. return false;
  38701. }
  38702. return vb.isUpdatable();
  38703. };
  38704. /**
  38705. * Gets a specific vertex buffer
  38706. * @param kind defines the data kind (Position, normal, etc...)
  38707. * @returns a {BABYLON.VertexBuffer}
  38708. */
  38709. Geometry.prototype.getVertexBuffer = function (kind) {
  38710. if (!this.isReady()) {
  38711. return null;
  38712. }
  38713. return this._vertexBuffers[kind];
  38714. };
  38715. /**
  38716. * Returns all vertex buffers
  38717. * @return an object holding all vertex buffers indexed by kind
  38718. */
  38719. Geometry.prototype.getVertexBuffers = function () {
  38720. if (!this.isReady()) {
  38721. return null;
  38722. }
  38723. return this._vertexBuffers;
  38724. };
  38725. /**
  38726. * Gets a boolean indicating if specific vertex buffer is present
  38727. * @param kind defines the data kind (Position, normal, etc...)
  38728. * @returns true if data is present
  38729. */
  38730. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38731. if (!this._vertexBuffers) {
  38732. if (this._delayInfo) {
  38733. return this._delayInfo.indexOf(kind) !== -1;
  38734. }
  38735. return false;
  38736. }
  38737. return this._vertexBuffers[kind] !== undefined;
  38738. };
  38739. /**
  38740. * Gets a list of all attached data kinds (Position, normal, etc...)
  38741. * @returns a list of string containing all kinds
  38742. */
  38743. Geometry.prototype.getVerticesDataKinds = function () {
  38744. var result = [];
  38745. var kind;
  38746. if (!this._vertexBuffers && this._delayInfo) {
  38747. for (kind in this._delayInfo) {
  38748. result.push(kind);
  38749. }
  38750. }
  38751. else {
  38752. for (kind in this._vertexBuffers) {
  38753. result.push(kind);
  38754. }
  38755. }
  38756. return result;
  38757. };
  38758. /**
  38759. * Update index buffer
  38760. * @param indices defines the indices to store in the index buffer
  38761. * @param offset defines the offset in the target buffer where to store the data
  38762. */
  38763. Geometry.prototype.updateIndices = function (indices, offset) {
  38764. if (!this._indexBuffer) {
  38765. return;
  38766. }
  38767. if (!this._indexBufferIsUpdatable) {
  38768. this.setIndices(indices, null, true);
  38769. }
  38770. else {
  38771. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38772. }
  38773. };
  38774. /**
  38775. * Creates a new index buffer
  38776. * @param indices defines the indices to store in the index buffer
  38777. * @param totalVertices defines the total number of vertices (could be null)
  38778. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38779. */
  38780. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38781. if (totalVertices === void 0) { totalVertices = null; }
  38782. if (updatable === void 0) { updatable = false; }
  38783. if (this._indexBuffer) {
  38784. this._engine._releaseBuffer(this._indexBuffer);
  38785. }
  38786. this._disposeVertexArrayObjects();
  38787. this._indices = indices;
  38788. this._indexBufferIsUpdatable = updatable;
  38789. if (this._meshes.length !== 0 && this._indices) {
  38790. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38791. }
  38792. if (totalVertices != undefined) { // including null and undefined
  38793. this._totalVertices = totalVertices;
  38794. }
  38795. var meshes = this._meshes;
  38796. var numOfMeshes = meshes.length;
  38797. for (var index = 0; index < numOfMeshes; index++) {
  38798. meshes[index]._createGlobalSubMesh(true);
  38799. }
  38800. this.notifyUpdate();
  38801. };
  38802. /**
  38803. * Return the total number of indices
  38804. * @returns the total number of indices
  38805. */
  38806. Geometry.prototype.getTotalIndices = function () {
  38807. if (!this.isReady()) {
  38808. return 0;
  38809. }
  38810. return this._indices.length;
  38811. };
  38812. /**
  38813. * Gets the index buffer array
  38814. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38815. * @returns the index buffer array
  38816. */
  38817. Geometry.prototype.getIndices = function (copyWhenShared) {
  38818. if (!this.isReady()) {
  38819. return null;
  38820. }
  38821. var orig = this._indices;
  38822. if (!copyWhenShared || this._meshes.length === 1) {
  38823. return orig;
  38824. }
  38825. else {
  38826. var len = orig.length;
  38827. var copy = [];
  38828. for (var i = 0; i < len; i++) {
  38829. copy.push(orig[i]);
  38830. }
  38831. return copy;
  38832. }
  38833. };
  38834. /**
  38835. * Gets the index buffer
  38836. * @return the index buffer
  38837. */
  38838. Geometry.prototype.getIndexBuffer = function () {
  38839. if (!this.isReady()) {
  38840. return null;
  38841. }
  38842. return this._indexBuffer;
  38843. };
  38844. /** @hidden */
  38845. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38846. if (effect === void 0) { effect = null; }
  38847. if (!effect || !this._vertexArrayObjects) {
  38848. return;
  38849. }
  38850. if (this._vertexArrayObjects[effect.key]) {
  38851. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38852. delete this._vertexArrayObjects[effect.key];
  38853. }
  38854. };
  38855. /**
  38856. * Release the associated resources for a specific mesh
  38857. * @param mesh defines the source mesh
  38858. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38859. */
  38860. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38861. var meshes = this._meshes;
  38862. var index = meshes.indexOf(mesh);
  38863. if (index === -1) {
  38864. return;
  38865. }
  38866. meshes.splice(index, 1);
  38867. mesh._geometry = null;
  38868. if (meshes.length === 0 && shouldDispose) {
  38869. this.dispose();
  38870. }
  38871. };
  38872. /**
  38873. * Apply current geometry to a given mesh
  38874. * @param mesh defines the mesh to apply geometry to
  38875. */
  38876. Geometry.prototype.applyToMesh = function (mesh) {
  38877. if (mesh._geometry === this) {
  38878. return;
  38879. }
  38880. var previousGeometry = mesh._geometry;
  38881. if (previousGeometry) {
  38882. previousGeometry.releaseForMesh(mesh);
  38883. }
  38884. var meshes = this._meshes;
  38885. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38886. mesh._geometry = this;
  38887. this._scene.pushGeometry(this);
  38888. meshes.push(mesh);
  38889. if (this.isReady()) {
  38890. this._applyToMesh(mesh);
  38891. }
  38892. else {
  38893. mesh._boundingInfo = this._boundingInfo;
  38894. }
  38895. };
  38896. Geometry.prototype._updateExtend = function (data) {
  38897. if (data === void 0) { data = null; }
  38898. if (!data) {
  38899. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38900. }
  38901. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38902. };
  38903. Geometry.prototype._applyToMesh = function (mesh) {
  38904. var numOfMeshes = this._meshes.length;
  38905. // vertexBuffers
  38906. for (var kind in this._vertexBuffers) {
  38907. if (numOfMeshes === 1) {
  38908. this._vertexBuffers[kind].create();
  38909. }
  38910. var buffer = this._vertexBuffers[kind].getBuffer();
  38911. if (buffer)
  38912. buffer.references = numOfMeshes;
  38913. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38914. if (!this._extend) {
  38915. this._updateExtend();
  38916. }
  38917. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38918. mesh._createGlobalSubMesh(false);
  38919. //bounding info was just created again, world matrix should be applied again.
  38920. mesh._updateBoundingInfo();
  38921. }
  38922. }
  38923. // indexBuffer
  38924. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38925. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38926. }
  38927. if (this._indexBuffer) {
  38928. this._indexBuffer.references = numOfMeshes;
  38929. }
  38930. };
  38931. Geometry.prototype.notifyUpdate = function (kind) {
  38932. if (this.onGeometryUpdated) {
  38933. this.onGeometryUpdated(this, kind);
  38934. }
  38935. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38936. var mesh = _a[_i];
  38937. mesh._markSubMeshesAsAttributesDirty();
  38938. }
  38939. };
  38940. /**
  38941. * Load the geometry if it was flagged as delay loaded
  38942. * @param scene defines the hosting scene
  38943. * @param onLoaded defines a callback called when the geometry is loaded
  38944. */
  38945. Geometry.prototype.load = function (scene, onLoaded) {
  38946. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38947. return;
  38948. }
  38949. if (this.isReady()) {
  38950. if (onLoaded) {
  38951. onLoaded();
  38952. }
  38953. return;
  38954. }
  38955. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38956. this._queueLoad(scene, onLoaded);
  38957. };
  38958. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38959. var _this = this;
  38960. if (!this.delayLoadingFile) {
  38961. return;
  38962. }
  38963. scene._addPendingData(this);
  38964. scene._loadFile(this.delayLoadingFile, function (data) {
  38965. if (!_this._delayLoadingFunction) {
  38966. return;
  38967. }
  38968. _this._delayLoadingFunction(JSON.parse(data), _this);
  38969. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38970. _this._delayInfo = [];
  38971. scene._removePendingData(_this);
  38972. var meshes = _this._meshes;
  38973. var numOfMeshes = meshes.length;
  38974. for (var index = 0; index < numOfMeshes; index++) {
  38975. _this._applyToMesh(meshes[index]);
  38976. }
  38977. if (onLoaded) {
  38978. onLoaded();
  38979. }
  38980. }, undefined, true);
  38981. };
  38982. /**
  38983. * Invert the geometry to move from a right handed system to a left handed one.
  38984. */
  38985. Geometry.prototype.toLeftHanded = function () {
  38986. // Flip faces
  38987. var tIndices = this.getIndices(false);
  38988. if (tIndices != null && tIndices.length > 0) {
  38989. for (var i = 0; i < tIndices.length; i += 3) {
  38990. var tTemp = tIndices[i + 0];
  38991. tIndices[i + 0] = tIndices[i + 2];
  38992. tIndices[i + 2] = tTemp;
  38993. }
  38994. this.setIndices(tIndices);
  38995. }
  38996. // Negate position.z
  38997. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38998. if (tPositions != null && tPositions.length > 0) {
  38999. for (var i = 0; i < tPositions.length; i += 3) {
  39000. tPositions[i + 2] = -tPositions[i + 2];
  39001. }
  39002. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39003. }
  39004. // Negate normal.z
  39005. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39006. if (tNormals != null && tNormals.length > 0) {
  39007. for (var i = 0; i < tNormals.length; i += 3) {
  39008. tNormals[i + 2] = -tNormals[i + 2];
  39009. }
  39010. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39011. }
  39012. };
  39013. // Cache
  39014. /** @hidden */
  39015. Geometry.prototype._resetPointsArrayCache = function () {
  39016. this._positions = null;
  39017. };
  39018. /** @hidden */
  39019. Geometry.prototype._generatePointsArray = function () {
  39020. if (this._positions)
  39021. return true;
  39022. this._positions = [];
  39023. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39024. if (!data) {
  39025. return false;
  39026. }
  39027. for (var index = 0; index < data.length; index += 3) {
  39028. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39029. }
  39030. return true;
  39031. };
  39032. /**
  39033. * Gets a value indicating if the geometry is disposed
  39034. * @returns true if the geometry was disposed
  39035. */
  39036. Geometry.prototype.isDisposed = function () {
  39037. return this._isDisposed;
  39038. };
  39039. Geometry.prototype._disposeVertexArrayObjects = function () {
  39040. if (this._vertexArrayObjects) {
  39041. for (var kind in this._vertexArrayObjects) {
  39042. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39043. }
  39044. this._vertexArrayObjects = {};
  39045. }
  39046. };
  39047. /**
  39048. * Free all associated resources
  39049. */
  39050. Geometry.prototype.dispose = function () {
  39051. var meshes = this._meshes;
  39052. var numOfMeshes = meshes.length;
  39053. var index;
  39054. for (index = 0; index < numOfMeshes; index++) {
  39055. this.releaseForMesh(meshes[index]);
  39056. }
  39057. this._meshes = [];
  39058. this._disposeVertexArrayObjects();
  39059. for (var kind in this._vertexBuffers) {
  39060. this._vertexBuffers[kind].dispose();
  39061. }
  39062. this._vertexBuffers = {};
  39063. this._totalVertices = 0;
  39064. if (this._indexBuffer) {
  39065. this._engine._releaseBuffer(this._indexBuffer);
  39066. }
  39067. this._indexBuffer = null;
  39068. this._indices = [];
  39069. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39070. this.delayLoadingFile = null;
  39071. this._delayLoadingFunction = null;
  39072. this._delayInfo = [];
  39073. this._boundingInfo = null;
  39074. this._scene.removeGeometry(this);
  39075. this._isDisposed = true;
  39076. };
  39077. /**
  39078. * Clone the current geometry into a new geometry
  39079. * @param id defines the unique ID of the new geometry
  39080. * @returns a new geometry object
  39081. */
  39082. Geometry.prototype.copy = function (id) {
  39083. var vertexData = new BABYLON.VertexData();
  39084. vertexData.indices = [];
  39085. var indices = this.getIndices();
  39086. if (indices) {
  39087. for (var index = 0; index < indices.length; index++) {
  39088. vertexData.indices.push(indices[index]);
  39089. }
  39090. }
  39091. var updatable = false;
  39092. var stopChecking = false;
  39093. var kind;
  39094. for (kind in this._vertexBuffers) {
  39095. // using slice() to make a copy of the array and not just reference it
  39096. var data = this.getVerticesData(kind);
  39097. if (data instanceof Float32Array) {
  39098. vertexData.set(new Float32Array(data), kind);
  39099. }
  39100. else {
  39101. vertexData.set(data.slice(0), kind);
  39102. }
  39103. if (!stopChecking) {
  39104. var vb = this.getVertexBuffer(kind);
  39105. if (vb) {
  39106. updatable = vb.isUpdatable();
  39107. stopChecking = !updatable;
  39108. }
  39109. }
  39110. }
  39111. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39112. geometry.delayLoadState = this.delayLoadState;
  39113. geometry.delayLoadingFile = this.delayLoadingFile;
  39114. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39115. for (kind in this._delayInfo) {
  39116. geometry._delayInfo = geometry._delayInfo || [];
  39117. geometry._delayInfo.push(kind);
  39118. }
  39119. // Bounding info
  39120. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39121. return geometry;
  39122. };
  39123. /**
  39124. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39125. * @return a JSON representation of the current geometry data (without the vertices data)
  39126. */
  39127. Geometry.prototype.serialize = function () {
  39128. var serializationObject = {};
  39129. serializationObject.id = this.id;
  39130. serializationObject.updatable = this._updatable;
  39131. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39132. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39133. }
  39134. return serializationObject;
  39135. };
  39136. Geometry.prototype.toNumberArray = function (origin) {
  39137. if (Array.isArray(origin)) {
  39138. return origin;
  39139. }
  39140. else {
  39141. return Array.prototype.slice.call(origin);
  39142. }
  39143. };
  39144. /**
  39145. * Serialize all vertices data into a JSON oject
  39146. * @returns a JSON representation of the current geometry data
  39147. */
  39148. Geometry.prototype.serializeVerticeData = function () {
  39149. var serializationObject = this.serialize();
  39150. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39151. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39152. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39153. serializationObject.positions._updatable = true;
  39154. }
  39155. }
  39156. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39157. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39158. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39159. serializationObject.normals._updatable = true;
  39160. }
  39161. }
  39162. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39163. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39164. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39165. serializationObject.tangets._updatable = true;
  39166. }
  39167. }
  39168. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39169. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39170. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39171. serializationObject.uvs._updatable = true;
  39172. }
  39173. }
  39174. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39175. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39176. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39177. serializationObject.uv2s._updatable = true;
  39178. }
  39179. }
  39180. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39181. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39182. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39183. serializationObject.uv3s._updatable = true;
  39184. }
  39185. }
  39186. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39187. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39188. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39189. serializationObject.uv4s._updatable = true;
  39190. }
  39191. }
  39192. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39193. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39194. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39195. serializationObject.uv5s._updatable = true;
  39196. }
  39197. }
  39198. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39199. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39200. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39201. serializationObject.uv6s._updatable = true;
  39202. }
  39203. }
  39204. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39205. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39206. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39207. serializationObject.colors._updatable = true;
  39208. }
  39209. }
  39210. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39211. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39212. serializationObject.matricesIndices._isExpanded = true;
  39213. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39214. serializationObject.matricesIndices._updatable = true;
  39215. }
  39216. }
  39217. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39218. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39219. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39220. serializationObject.matricesWeights._updatable = true;
  39221. }
  39222. }
  39223. serializationObject.indices = this.toNumberArray(this.getIndices());
  39224. return serializationObject;
  39225. };
  39226. // Statics
  39227. /**
  39228. * Extracts a clone of a mesh geometry
  39229. * @param mesh defines the source mesh
  39230. * @param id defines the unique ID of the new geometry object
  39231. * @returns the new geometry object
  39232. */
  39233. Geometry.ExtractFromMesh = function (mesh, id) {
  39234. var geometry = mesh._geometry;
  39235. if (!geometry) {
  39236. return null;
  39237. }
  39238. return geometry.copy(id);
  39239. };
  39240. /**
  39241. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39242. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39243. * Be aware Math.random() could cause collisions, but:
  39244. * "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"
  39245. * @returns a string containing a new GUID
  39246. */
  39247. Geometry.RandomId = function () {
  39248. return BABYLON.Tools.RandomId();
  39249. };
  39250. /** @hidden */
  39251. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39252. var scene = mesh.getScene();
  39253. // Geometry
  39254. var geometryId = parsedGeometry.geometryId;
  39255. if (geometryId) {
  39256. var geometry = scene.getGeometryByID(geometryId);
  39257. if (geometry) {
  39258. geometry.applyToMesh(mesh);
  39259. }
  39260. }
  39261. else if (parsedGeometry instanceof ArrayBuffer) {
  39262. var binaryInfo = mesh._binaryInfo;
  39263. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39264. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39265. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39266. }
  39267. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39268. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39269. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39270. }
  39271. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39272. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39273. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39274. }
  39275. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39276. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39277. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39278. }
  39279. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39280. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39281. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39282. }
  39283. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39284. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39285. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39286. }
  39287. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39288. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39289. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39290. }
  39291. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39292. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39293. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39294. }
  39295. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39296. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39297. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39298. }
  39299. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39300. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39301. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39302. }
  39303. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39304. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39305. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39306. }
  39307. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39308. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39309. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39310. }
  39311. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39312. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39313. mesh.setIndices(indicesData, null);
  39314. }
  39315. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39316. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39317. mesh.subMeshes = [];
  39318. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39319. var materialIndex = subMeshesData[(i * 5) + 0];
  39320. var verticesStart = subMeshesData[(i * 5) + 1];
  39321. var verticesCount = subMeshesData[(i * 5) + 2];
  39322. var indexStart = subMeshesData[(i * 5) + 3];
  39323. var indexCount = subMeshesData[(i * 5) + 4];
  39324. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39325. }
  39326. }
  39327. }
  39328. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39329. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39330. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39331. if (parsedGeometry.tangents) {
  39332. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39333. }
  39334. if (parsedGeometry.uvs) {
  39335. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39336. }
  39337. if (parsedGeometry.uvs2) {
  39338. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39339. }
  39340. if (parsedGeometry.uvs3) {
  39341. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39342. }
  39343. if (parsedGeometry.uvs4) {
  39344. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39345. }
  39346. if (parsedGeometry.uvs5) {
  39347. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39348. }
  39349. if (parsedGeometry.uvs6) {
  39350. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39351. }
  39352. if (parsedGeometry.colors) {
  39353. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39354. }
  39355. if (parsedGeometry.matricesIndices) {
  39356. if (!parsedGeometry.matricesIndices._isExpanded) {
  39357. var floatIndices = [];
  39358. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39359. var matricesIndex = parsedGeometry.matricesIndices[i];
  39360. floatIndices.push(matricesIndex & 0x000000FF);
  39361. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39362. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39363. floatIndices.push(matricesIndex >> 24);
  39364. }
  39365. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39366. }
  39367. else {
  39368. delete parsedGeometry.matricesIndices._isExpanded;
  39369. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39370. }
  39371. }
  39372. if (parsedGeometry.matricesIndicesExtra) {
  39373. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39374. var floatIndices = [];
  39375. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39376. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39377. floatIndices.push(matricesIndex & 0x000000FF);
  39378. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39379. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39380. floatIndices.push(matricesIndex >> 24);
  39381. }
  39382. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39383. }
  39384. else {
  39385. delete parsedGeometry.matricesIndices._isExpanded;
  39386. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39387. }
  39388. }
  39389. if (parsedGeometry.matricesWeights) {
  39390. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39391. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39392. }
  39393. if (parsedGeometry.matricesWeightsExtra) {
  39394. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39395. }
  39396. mesh.setIndices(parsedGeometry.indices, null);
  39397. }
  39398. // SubMeshes
  39399. if (parsedGeometry.subMeshes) {
  39400. mesh.subMeshes = [];
  39401. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39402. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39403. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39404. }
  39405. }
  39406. // Flat shading
  39407. if (mesh._shouldGenerateFlatShading) {
  39408. mesh.convertToFlatShadedMesh();
  39409. delete mesh._shouldGenerateFlatShading;
  39410. }
  39411. // Update
  39412. mesh.computeWorldMatrix(true);
  39413. // Octree
  39414. var sceneOctree = scene.selectionOctree;
  39415. if (sceneOctree !== undefined && sceneOctree !== null) {
  39416. sceneOctree.addMesh(mesh);
  39417. }
  39418. };
  39419. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39420. var epsilon = 1e-3;
  39421. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39422. return;
  39423. }
  39424. var noInfluenceBoneIndex = 0.0;
  39425. if (parsedGeometry.skeletonId > -1) {
  39426. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39427. if (!skeleton) {
  39428. return;
  39429. }
  39430. noInfluenceBoneIndex = skeleton.bones.length;
  39431. }
  39432. else {
  39433. return;
  39434. }
  39435. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39436. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39437. var matricesWeights = parsedGeometry.matricesWeights;
  39438. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39439. var influencers = parsedGeometry.numBoneInfluencer;
  39440. var size = matricesWeights.length;
  39441. for (var i = 0; i < size; i += 4) {
  39442. var weight = 0.0;
  39443. var firstZeroWeight = -1;
  39444. for (var j = 0; j < 4; j++) {
  39445. var w = matricesWeights[i + j];
  39446. weight += w;
  39447. if (w < epsilon && firstZeroWeight < 0) {
  39448. firstZeroWeight = j;
  39449. }
  39450. }
  39451. if (matricesWeightsExtra) {
  39452. for (var j = 0; j < 4; j++) {
  39453. var w = matricesWeightsExtra[i + j];
  39454. weight += w;
  39455. if (w < epsilon && firstZeroWeight < 0) {
  39456. firstZeroWeight = j + 4;
  39457. }
  39458. }
  39459. }
  39460. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39461. firstZeroWeight = influencers - 1;
  39462. }
  39463. if (weight > epsilon) {
  39464. var mweight = 1.0 / weight;
  39465. for (var j = 0; j < 4; j++) {
  39466. matricesWeights[i + j] *= mweight;
  39467. }
  39468. if (matricesWeightsExtra) {
  39469. for (var j = 0; j < 4; j++) {
  39470. matricesWeightsExtra[i + j] *= mweight;
  39471. }
  39472. }
  39473. }
  39474. else {
  39475. if (firstZeroWeight >= 4) {
  39476. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39477. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39478. }
  39479. else {
  39480. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39481. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39482. }
  39483. }
  39484. }
  39485. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39486. if (parsedGeometry.matricesWeightsExtra) {
  39487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39488. }
  39489. };
  39490. /**
  39491. * Create a new geometry from persisted data (Using .babylon file format)
  39492. * @param parsedVertexData defines the persisted data
  39493. * @param scene defines the hosting scene
  39494. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39495. * @returns the new geometry object
  39496. */
  39497. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39498. if (scene.getGeometryByID(parsedVertexData.id)) {
  39499. return null; // null since geometry could be something else than a box...
  39500. }
  39501. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39502. if (BABYLON.Tags) {
  39503. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39504. }
  39505. if (parsedVertexData.delayLoadingFile) {
  39506. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39507. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39508. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39509. geometry._delayInfo = [];
  39510. if (parsedVertexData.hasUVs) {
  39511. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39512. }
  39513. if (parsedVertexData.hasUVs2) {
  39514. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39515. }
  39516. if (parsedVertexData.hasUVs3) {
  39517. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39518. }
  39519. if (parsedVertexData.hasUVs4) {
  39520. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39521. }
  39522. if (parsedVertexData.hasUVs5) {
  39523. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39524. }
  39525. if (parsedVertexData.hasUVs6) {
  39526. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39527. }
  39528. if (parsedVertexData.hasColors) {
  39529. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39530. }
  39531. if (parsedVertexData.hasMatricesIndices) {
  39532. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39533. }
  39534. if (parsedVertexData.hasMatricesWeights) {
  39535. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39536. }
  39537. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39538. }
  39539. else {
  39540. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39541. }
  39542. scene.pushGeometry(geometry, true);
  39543. return geometry;
  39544. };
  39545. return Geometry;
  39546. }());
  39547. BABYLON.Geometry = Geometry;
  39548. // Primitives
  39549. /// Abstract class
  39550. /**
  39551. * Abstract class used to provide common services for all typed geometries
  39552. * @hidden
  39553. */
  39554. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39555. __extends(_PrimitiveGeometry, _super);
  39556. /**
  39557. * Creates a new typed geometry
  39558. * @param id defines the unique ID of the geometry
  39559. * @param scene defines the hosting scene
  39560. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39561. * @param mesh defines the hosting mesh (can be null)
  39562. */
  39563. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39564. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39565. if (mesh === void 0) { mesh = null; }
  39566. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39567. _this._canBeRegenerated = _canBeRegenerated;
  39568. _this._beingRegenerated = true;
  39569. _this.regenerate();
  39570. _this._beingRegenerated = false;
  39571. return _this;
  39572. }
  39573. /**
  39574. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39575. * @returns true if the geometry can be regenerated
  39576. */
  39577. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39578. return this._canBeRegenerated;
  39579. };
  39580. /**
  39581. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39582. */
  39583. _PrimitiveGeometry.prototype.regenerate = function () {
  39584. if (!this._canBeRegenerated) {
  39585. return;
  39586. }
  39587. this._beingRegenerated = true;
  39588. this.setAllVerticesData(this._regenerateVertexData(), false);
  39589. this._beingRegenerated = false;
  39590. };
  39591. /**
  39592. * Clone the geometry
  39593. * @param id defines the unique ID of the new geometry
  39594. * @returns the new geometry
  39595. */
  39596. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39597. return _super.prototype.copy.call(this, id);
  39598. };
  39599. // overrides
  39600. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39601. if (!this._beingRegenerated) {
  39602. return;
  39603. }
  39604. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39605. };
  39606. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39607. if (!this._beingRegenerated) {
  39608. return;
  39609. }
  39610. _super.prototype.setVerticesData.call(this, kind, data, false);
  39611. };
  39612. // to override
  39613. /** @hidden */
  39614. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39615. throw new Error("Abstract method");
  39616. };
  39617. _PrimitiveGeometry.prototype.copy = function (id) {
  39618. throw new Error("Must be overriden in sub-classes.");
  39619. };
  39620. _PrimitiveGeometry.prototype.serialize = function () {
  39621. var serializationObject = _super.prototype.serialize.call(this);
  39622. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39623. return serializationObject;
  39624. };
  39625. return _PrimitiveGeometry;
  39626. }(Geometry));
  39627. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39628. /**
  39629. * Creates a ribbon geometry
  39630. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39631. */
  39632. var RibbonGeometry = /** @class */ (function (_super) {
  39633. __extends(RibbonGeometry, _super);
  39634. /**
  39635. * Creates a ribbon geometry
  39636. * @param id defines the unique ID of the geometry
  39637. * @param scene defines the hosting scene
  39638. * @param pathArray defines the array of paths to use
  39639. * @param closeArray defines if the last path and the first path must be joined
  39640. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39641. * @param offset defines the offset between points
  39642. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39643. * @param mesh defines the hosting mesh (can be null)
  39644. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39645. */
  39646. function RibbonGeometry(id, scene,
  39647. /**
  39648. * Defines the array of paths to use
  39649. */
  39650. pathArray,
  39651. /**
  39652. * Defines if the last and first points of each path in your pathArray must be joined
  39653. */
  39654. closeArray,
  39655. /**
  39656. * Defines if the last and first points of each path in your pathArray must be joined
  39657. */
  39658. closePath,
  39659. /**
  39660. * Defines the offset between points
  39661. */
  39662. offset, canBeRegenerated, mesh,
  39663. /**
  39664. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39665. */
  39666. side) {
  39667. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39668. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39669. _this.pathArray = pathArray;
  39670. _this.closeArray = closeArray;
  39671. _this.closePath = closePath;
  39672. _this.offset = offset;
  39673. _this.side = side;
  39674. return _this;
  39675. }
  39676. /** @hidden */
  39677. RibbonGeometry.prototype._regenerateVertexData = function () {
  39678. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39679. };
  39680. RibbonGeometry.prototype.copy = function (id) {
  39681. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39682. };
  39683. return RibbonGeometry;
  39684. }(_PrimitiveGeometry));
  39685. BABYLON.RibbonGeometry = RibbonGeometry;
  39686. /**
  39687. * Creates a box geometry
  39688. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39689. */
  39690. var BoxGeometry = /** @class */ (function (_super) {
  39691. __extends(BoxGeometry, _super);
  39692. /**
  39693. * Creates a box geometry
  39694. * @param id defines the unique ID of the geometry
  39695. * @param scene defines the hosting scene
  39696. * @param size defines the zise of the box (width, height and depth are the same)
  39697. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39698. * @param mesh defines the hosting mesh (can be null)
  39699. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39700. */
  39701. function BoxGeometry(id, scene,
  39702. /**
  39703. * Defines the zise of the box (width, height and depth are the same)
  39704. */
  39705. size, canBeRegenerated, mesh,
  39706. /**
  39707. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39708. */
  39709. side) {
  39710. if (mesh === void 0) { mesh = null; }
  39711. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39712. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39713. _this.size = size;
  39714. _this.side = side;
  39715. return _this;
  39716. }
  39717. BoxGeometry.prototype._regenerateVertexData = function () {
  39718. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39719. };
  39720. BoxGeometry.prototype.copy = function (id) {
  39721. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39722. };
  39723. BoxGeometry.prototype.serialize = function () {
  39724. var serializationObject = _super.prototype.serialize.call(this);
  39725. serializationObject.size = this.size;
  39726. return serializationObject;
  39727. };
  39728. BoxGeometry.Parse = function (parsedBox, scene) {
  39729. if (scene.getGeometryByID(parsedBox.id)) {
  39730. return null; // null since geometry could be something else than a box...
  39731. }
  39732. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39733. if (BABYLON.Tags) {
  39734. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39735. }
  39736. scene.pushGeometry(box, true);
  39737. return box;
  39738. };
  39739. return BoxGeometry;
  39740. }(_PrimitiveGeometry));
  39741. BABYLON.BoxGeometry = BoxGeometry;
  39742. /**
  39743. * Creates a sphere geometry
  39744. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39745. */
  39746. var SphereGeometry = /** @class */ (function (_super) {
  39747. __extends(SphereGeometry, _super);
  39748. /**
  39749. * Create a new sphere geometry
  39750. * @param id defines the unique ID of the geometry
  39751. * @param scene defines the hosting scene
  39752. * @param segments defines the number of segments to use to create the sphere
  39753. * @param diameter defines the diameter of the sphere
  39754. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39755. * @param mesh defines the hosting mesh (can be null)
  39756. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39757. */
  39758. function SphereGeometry(id, scene,
  39759. /**
  39760. * Defines the number of segments to use to create the sphere
  39761. */
  39762. segments,
  39763. /**
  39764. * Defines the diameter of the sphere
  39765. */
  39766. diameter, canBeRegenerated, mesh,
  39767. /**
  39768. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39769. */
  39770. side) {
  39771. if (mesh === void 0) { mesh = null; }
  39772. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39773. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39774. _this.segments = segments;
  39775. _this.diameter = diameter;
  39776. _this.side = side;
  39777. return _this;
  39778. }
  39779. SphereGeometry.prototype._regenerateVertexData = function () {
  39780. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39781. };
  39782. SphereGeometry.prototype.copy = function (id) {
  39783. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39784. };
  39785. SphereGeometry.prototype.serialize = function () {
  39786. var serializationObject = _super.prototype.serialize.call(this);
  39787. serializationObject.segments = this.segments;
  39788. serializationObject.diameter = this.diameter;
  39789. return serializationObject;
  39790. };
  39791. SphereGeometry.Parse = function (parsedSphere, scene) {
  39792. if (scene.getGeometryByID(parsedSphere.id)) {
  39793. return null; // null since geometry could be something else than a sphere...
  39794. }
  39795. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39796. if (BABYLON.Tags) {
  39797. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39798. }
  39799. scene.pushGeometry(sphere, true);
  39800. return sphere;
  39801. };
  39802. return SphereGeometry;
  39803. }(_PrimitiveGeometry));
  39804. BABYLON.SphereGeometry = SphereGeometry;
  39805. /**
  39806. * Creates a disc geometry
  39807. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39808. */
  39809. var DiscGeometry = /** @class */ (function (_super) {
  39810. __extends(DiscGeometry, _super);
  39811. /**
  39812. * Creates a new disc geometry
  39813. * @param id defines the unique ID of the geometry
  39814. * @param scene defines the hosting scene
  39815. * @param radius defines the radius of the disc
  39816. * @param tessellation defines the tesselation factor to apply to the disc
  39817. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39818. * @param mesh defines the hosting mesh (can be null)
  39819. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39820. */
  39821. function DiscGeometry(id, scene,
  39822. /**
  39823. * Defines the radius of the disc
  39824. */
  39825. radius,
  39826. /**
  39827. * Defines the tesselation factor to apply to the disc
  39828. */
  39829. tessellation, canBeRegenerated, mesh,
  39830. /**
  39831. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39832. */
  39833. side) {
  39834. if (mesh === void 0) { mesh = null; }
  39835. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39836. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39837. _this.radius = radius;
  39838. _this.tessellation = tessellation;
  39839. _this.side = side;
  39840. return _this;
  39841. }
  39842. DiscGeometry.prototype._regenerateVertexData = function () {
  39843. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39844. };
  39845. DiscGeometry.prototype.copy = function (id) {
  39846. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39847. };
  39848. return DiscGeometry;
  39849. }(_PrimitiveGeometry));
  39850. BABYLON.DiscGeometry = DiscGeometry;
  39851. /**
  39852. * Creates a new cylinder geometry
  39853. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39854. */
  39855. var CylinderGeometry = /** @class */ (function (_super) {
  39856. __extends(CylinderGeometry, _super);
  39857. /**
  39858. * Creates a new cylinder geometry
  39859. * @param id defines the unique ID of the geometry
  39860. * @param scene defines the hosting scene
  39861. * @param height defines the height of the cylinder
  39862. * @param diameterTop defines the diameter of the cylinder's top cap
  39863. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39864. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39865. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39866. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39867. * @param mesh defines the hosting mesh (can be null)
  39868. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39869. */
  39870. function CylinderGeometry(id, scene,
  39871. /**
  39872. * Defines the height of the cylinder
  39873. */
  39874. height,
  39875. /**
  39876. * Defines the diameter of the cylinder's top cap
  39877. */
  39878. diameterTop,
  39879. /**
  39880. * Defines the diameter of the cylinder's bottom cap
  39881. */
  39882. diameterBottom,
  39883. /**
  39884. * Defines the tessellation factor to apply to the cylinder
  39885. */
  39886. tessellation,
  39887. /**
  39888. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39889. */
  39890. subdivisions, canBeRegenerated, mesh,
  39891. /**
  39892. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39893. */
  39894. side) {
  39895. if (subdivisions === void 0) { subdivisions = 1; }
  39896. if (mesh === void 0) { mesh = null; }
  39897. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39898. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39899. _this.height = height;
  39900. _this.diameterTop = diameterTop;
  39901. _this.diameterBottom = diameterBottom;
  39902. _this.tessellation = tessellation;
  39903. _this.subdivisions = subdivisions;
  39904. _this.side = side;
  39905. return _this;
  39906. }
  39907. CylinderGeometry.prototype._regenerateVertexData = function () {
  39908. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39909. };
  39910. CylinderGeometry.prototype.copy = function (id) {
  39911. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39912. };
  39913. CylinderGeometry.prototype.serialize = function () {
  39914. var serializationObject = _super.prototype.serialize.call(this);
  39915. serializationObject.height = this.height;
  39916. serializationObject.diameterTop = this.diameterTop;
  39917. serializationObject.diameterBottom = this.diameterBottom;
  39918. serializationObject.tessellation = this.tessellation;
  39919. return serializationObject;
  39920. };
  39921. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39922. if (scene.getGeometryByID(parsedCylinder.id)) {
  39923. return null; // null since geometry could be something else than a cylinder...
  39924. }
  39925. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39926. if (BABYLON.Tags) {
  39927. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39928. }
  39929. scene.pushGeometry(cylinder, true);
  39930. return cylinder;
  39931. };
  39932. return CylinderGeometry;
  39933. }(_PrimitiveGeometry));
  39934. BABYLON.CylinderGeometry = CylinderGeometry;
  39935. /**
  39936. * Creates a new torus geometry
  39937. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39938. */
  39939. var TorusGeometry = /** @class */ (function (_super) {
  39940. __extends(TorusGeometry, _super);
  39941. /**
  39942. * Creates a new torus geometry
  39943. * @param id defines the unique ID of the geometry
  39944. * @param scene defines the hosting scene
  39945. * @param diameter defines the diameter of the torus
  39946. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39947. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39948. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39949. * @param mesh defines the hosting mesh (can be null)
  39950. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39951. */
  39952. function TorusGeometry(id, scene,
  39953. /**
  39954. * Defines the diameter of the torus
  39955. */
  39956. diameter,
  39957. /**
  39958. * Defines the thickness of the torus (ie. internal diameter)
  39959. */
  39960. thickness,
  39961. /**
  39962. * Defines the tesselation factor to apply to the torus
  39963. */
  39964. tessellation, canBeRegenerated, mesh,
  39965. /**
  39966. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39967. */
  39968. side) {
  39969. if (mesh === void 0) { mesh = null; }
  39970. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39971. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39972. _this.diameter = diameter;
  39973. _this.thickness = thickness;
  39974. _this.tessellation = tessellation;
  39975. _this.side = side;
  39976. return _this;
  39977. }
  39978. TorusGeometry.prototype._regenerateVertexData = function () {
  39979. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39980. };
  39981. TorusGeometry.prototype.copy = function (id) {
  39982. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39983. };
  39984. TorusGeometry.prototype.serialize = function () {
  39985. var serializationObject = _super.prototype.serialize.call(this);
  39986. serializationObject.diameter = this.diameter;
  39987. serializationObject.thickness = this.thickness;
  39988. serializationObject.tessellation = this.tessellation;
  39989. return serializationObject;
  39990. };
  39991. TorusGeometry.Parse = function (parsedTorus, scene) {
  39992. if (scene.getGeometryByID(parsedTorus.id)) {
  39993. return null; // null since geometry could be something else than a torus...
  39994. }
  39995. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39996. if (BABYLON.Tags) {
  39997. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39998. }
  39999. scene.pushGeometry(torus, true);
  40000. return torus;
  40001. };
  40002. return TorusGeometry;
  40003. }(_PrimitiveGeometry));
  40004. BABYLON.TorusGeometry = TorusGeometry;
  40005. /**
  40006. * Creates a new ground geometry
  40007. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40008. */
  40009. var GroundGeometry = /** @class */ (function (_super) {
  40010. __extends(GroundGeometry, _super);
  40011. /**
  40012. * Creates a new ground geometry
  40013. * @param id defines the unique ID of the geometry
  40014. * @param scene defines the hosting scene
  40015. * @param width defines the width of the ground
  40016. * @param height defines the height of the ground
  40017. * @param subdivisions defines the subdivisions to apply to the ground
  40018. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40019. * @param mesh defines the hosting mesh (can be null)
  40020. */
  40021. function GroundGeometry(id, scene,
  40022. /**
  40023. * Defines the width of the ground
  40024. */
  40025. width,
  40026. /**
  40027. * Defines the height of the ground
  40028. */
  40029. height,
  40030. /**
  40031. * Defines the subdivisions to apply to the ground
  40032. */
  40033. subdivisions, canBeRegenerated, mesh) {
  40034. if (mesh === void 0) { mesh = null; }
  40035. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40036. _this.width = width;
  40037. _this.height = height;
  40038. _this.subdivisions = subdivisions;
  40039. return _this;
  40040. }
  40041. GroundGeometry.prototype._regenerateVertexData = function () {
  40042. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40043. };
  40044. GroundGeometry.prototype.copy = function (id) {
  40045. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40046. };
  40047. GroundGeometry.prototype.serialize = function () {
  40048. var serializationObject = _super.prototype.serialize.call(this);
  40049. serializationObject.width = this.width;
  40050. serializationObject.height = this.height;
  40051. serializationObject.subdivisions = this.subdivisions;
  40052. return serializationObject;
  40053. };
  40054. GroundGeometry.Parse = function (parsedGround, scene) {
  40055. if (scene.getGeometryByID(parsedGround.id)) {
  40056. return null; // null since geometry could be something else than a ground...
  40057. }
  40058. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40059. if (BABYLON.Tags) {
  40060. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40061. }
  40062. scene.pushGeometry(ground, true);
  40063. return ground;
  40064. };
  40065. return GroundGeometry;
  40066. }(_PrimitiveGeometry));
  40067. BABYLON.GroundGeometry = GroundGeometry;
  40068. /**
  40069. * Creates a tiled ground geometry
  40070. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40071. */
  40072. var TiledGroundGeometry = /** @class */ (function (_super) {
  40073. __extends(TiledGroundGeometry, _super);
  40074. /**
  40075. * Creates a tiled ground geometry
  40076. * @param id defines the unique ID of the geometry
  40077. * @param scene defines the hosting scene
  40078. * @param xmin defines the minimum value on X axis
  40079. * @param zmin defines the minimum value on Z axis
  40080. * @param xmax defines the maximum value on X axis
  40081. * @param zmax defines the maximum value on Z axis
  40082. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40083. * @param precision defines the precision to use when computing the tiles
  40084. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40085. * @param mesh defines the hosting mesh (can be null)
  40086. */
  40087. function TiledGroundGeometry(id, scene,
  40088. /**
  40089. * Defines the minimum value on X axis
  40090. */
  40091. xmin,
  40092. /**
  40093. * Defines the minimum value on Z axis
  40094. */
  40095. zmin,
  40096. /**
  40097. * Defines the maximum value on X axis
  40098. */
  40099. xmax,
  40100. /**
  40101. * Defines the maximum value on Z axis
  40102. */
  40103. zmax,
  40104. /**
  40105. * Defines the subdivisions to apply to the ground
  40106. */
  40107. subdivisions,
  40108. /**
  40109. * Defines the precision to use when computing the tiles
  40110. */
  40111. precision, canBeRegenerated, mesh) {
  40112. if (mesh === void 0) { mesh = null; }
  40113. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40114. _this.xmin = xmin;
  40115. _this.zmin = zmin;
  40116. _this.xmax = xmax;
  40117. _this.zmax = zmax;
  40118. _this.subdivisions = subdivisions;
  40119. _this.precision = precision;
  40120. return _this;
  40121. }
  40122. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40123. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40124. };
  40125. TiledGroundGeometry.prototype.copy = function (id) {
  40126. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40127. };
  40128. return TiledGroundGeometry;
  40129. }(_PrimitiveGeometry));
  40130. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40131. /**
  40132. * Creates a plane geometry
  40133. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40134. */
  40135. var PlaneGeometry = /** @class */ (function (_super) {
  40136. __extends(PlaneGeometry, _super);
  40137. /**
  40138. * Creates a plane geometry
  40139. * @param id defines the unique ID of the geometry
  40140. * @param scene defines the hosting scene
  40141. * @param size defines the size of the plane (width === height)
  40142. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40143. * @param mesh defines the hosting mesh (can be null)
  40144. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40145. */
  40146. function PlaneGeometry(id, scene,
  40147. /**
  40148. * Defines the size of the plane (width === height)
  40149. */
  40150. size, canBeRegenerated, mesh,
  40151. /**
  40152. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40153. */
  40154. side) {
  40155. if (mesh === void 0) { mesh = null; }
  40156. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40157. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40158. _this.size = size;
  40159. _this.side = side;
  40160. return _this;
  40161. }
  40162. PlaneGeometry.prototype._regenerateVertexData = function () {
  40163. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40164. };
  40165. PlaneGeometry.prototype.copy = function (id) {
  40166. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40167. };
  40168. PlaneGeometry.prototype.serialize = function () {
  40169. var serializationObject = _super.prototype.serialize.call(this);
  40170. serializationObject.size = this.size;
  40171. return serializationObject;
  40172. };
  40173. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40174. if (scene.getGeometryByID(parsedPlane.id)) {
  40175. return null; // null since geometry could be something else than a ground...
  40176. }
  40177. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40178. if (BABYLON.Tags) {
  40179. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40180. }
  40181. scene.pushGeometry(plane, true);
  40182. return plane;
  40183. };
  40184. return PlaneGeometry;
  40185. }(_PrimitiveGeometry));
  40186. BABYLON.PlaneGeometry = PlaneGeometry;
  40187. /**
  40188. * Creates a torus knot geometry
  40189. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40190. */
  40191. var TorusKnotGeometry = /** @class */ (function (_super) {
  40192. __extends(TorusKnotGeometry, _super);
  40193. /**
  40194. * Creates a torus knot geometry
  40195. * @param id defines the unique ID of the geometry
  40196. * @param scene defines the hosting scene
  40197. * @param radius defines the radius of the torus knot
  40198. * @param tube defines the thickness of the torus knot tube
  40199. * @param radialSegments defines the number of radial segments
  40200. * @param tubularSegments defines the number of tubular segments
  40201. * @param p defines the first number of windings
  40202. * @param q defines the second number of windings
  40203. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40204. * @param mesh defines the hosting mesh (can be null)
  40205. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40206. */
  40207. function TorusKnotGeometry(id, scene,
  40208. /**
  40209. * Defines the radius of the torus knot
  40210. */
  40211. radius,
  40212. /**
  40213. * Defines the thickness of the torus knot tube
  40214. */
  40215. tube,
  40216. /**
  40217. * Defines the number of radial segments
  40218. */
  40219. radialSegments,
  40220. /**
  40221. * Defines the number of tubular segments
  40222. */
  40223. tubularSegments,
  40224. /**
  40225. * Defines the first number of windings
  40226. */
  40227. p,
  40228. /**
  40229. * Defines the second number of windings
  40230. */
  40231. q, canBeRegenerated, mesh,
  40232. /**
  40233. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40234. */
  40235. side) {
  40236. if (mesh === void 0) { mesh = null; }
  40237. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40238. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40239. _this.radius = radius;
  40240. _this.tube = tube;
  40241. _this.radialSegments = radialSegments;
  40242. _this.tubularSegments = tubularSegments;
  40243. _this.p = p;
  40244. _this.q = q;
  40245. _this.side = side;
  40246. return _this;
  40247. }
  40248. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40249. 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 });
  40250. };
  40251. TorusKnotGeometry.prototype.copy = function (id) {
  40252. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40253. };
  40254. TorusKnotGeometry.prototype.serialize = function () {
  40255. var serializationObject = _super.prototype.serialize.call(this);
  40256. serializationObject.radius = this.radius;
  40257. serializationObject.tube = this.tube;
  40258. serializationObject.radialSegments = this.radialSegments;
  40259. serializationObject.tubularSegments = this.tubularSegments;
  40260. serializationObject.p = this.p;
  40261. serializationObject.q = this.q;
  40262. return serializationObject;
  40263. };
  40264. ;
  40265. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40266. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40267. return null; // null since geometry could be something else than a ground...
  40268. }
  40269. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40270. if (BABYLON.Tags) {
  40271. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40272. }
  40273. scene.pushGeometry(torusKnot, true);
  40274. return torusKnot;
  40275. };
  40276. return TorusKnotGeometry;
  40277. }(_PrimitiveGeometry));
  40278. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40279. //}
  40280. })(BABYLON || (BABYLON = {}));
  40281. //# sourceMappingURL=babylon.geometry.js.map
  40282. var BABYLON;
  40283. (function (BABYLON) {
  40284. /**
  40285. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40286. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40287. */
  40288. var PostProcessManager = /** @class */ (function () {
  40289. /**
  40290. * Creates a new instance PostProcess
  40291. * @param scene The scene that the post process is associated with.
  40292. */
  40293. function PostProcessManager(scene) {
  40294. this._vertexBuffers = {};
  40295. this._scene = scene;
  40296. }
  40297. PostProcessManager.prototype._prepareBuffers = function () {
  40298. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40299. return;
  40300. }
  40301. // VBO
  40302. var vertices = [];
  40303. vertices.push(1, 1);
  40304. vertices.push(-1, 1);
  40305. vertices.push(-1, -1);
  40306. vertices.push(1, -1);
  40307. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40308. this._buildIndexBuffer();
  40309. };
  40310. PostProcessManager.prototype._buildIndexBuffer = function () {
  40311. // Indices
  40312. var indices = [];
  40313. indices.push(0);
  40314. indices.push(1);
  40315. indices.push(2);
  40316. indices.push(0);
  40317. indices.push(2);
  40318. indices.push(3);
  40319. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40320. };
  40321. /**
  40322. * Rebuilds the vertex buffers of the manager.
  40323. */
  40324. PostProcessManager.prototype._rebuild = function () {
  40325. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40326. if (!vb) {
  40327. return;
  40328. }
  40329. vb._rebuild();
  40330. this._buildIndexBuffer();
  40331. };
  40332. // Methods
  40333. /**
  40334. * Prepares a frame to be run through a post process.
  40335. * @param sourceTexture The input texture to the post procesess. (default: null)
  40336. * @param postProcesses An array of post processes to be run. (default: null)
  40337. * @returns True if the post processes were able to be run.
  40338. */
  40339. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40340. if (sourceTexture === void 0) { sourceTexture = null; }
  40341. if (postProcesses === void 0) { postProcesses = null; }
  40342. var camera = this._scene.activeCamera;
  40343. if (!camera) {
  40344. return false;
  40345. }
  40346. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40347. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40348. return false;
  40349. }
  40350. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40351. return true;
  40352. };
  40353. /**
  40354. * Manually render a set of post processes to a texture.
  40355. * @param postProcesses An array of post processes to be run.
  40356. * @param targetTexture The target texture to render to.
  40357. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40358. */
  40359. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40360. if (targetTexture === void 0) { targetTexture = null; }
  40361. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40362. var engine = this._scene.getEngine();
  40363. for (var index = 0; index < postProcesses.length; index++) {
  40364. if (index < postProcesses.length - 1) {
  40365. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40366. }
  40367. else {
  40368. if (targetTexture) {
  40369. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40370. }
  40371. else {
  40372. engine.restoreDefaultFramebuffer();
  40373. }
  40374. }
  40375. var pp = postProcesses[index];
  40376. var effect = pp.apply();
  40377. if (effect) {
  40378. pp.onBeforeRenderObservable.notifyObservers(effect);
  40379. // VBOs
  40380. this._prepareBuffers();
  40381. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40382. // Draw order
  40383. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40384. pp.onAfterRenderObservable.notifyObservers(effect);
  40385. }
  40386. }
  40387. // Restore depth buffer
  40388. engine.setDepthBuffer(true);
  40389. engine.setDepthWrite(true);
  40390. };
  40391. /**
  40392. * Finalize the result of the output of the postprocesses.
  40393. * @param doNotPresent If true the result will not be displayed to the screen.
  40394. * @param targetTexture The target texture to render to.
  40395. * @param faceIndex The index of the face to bind the target texture to.
  40396. * @param postProcesses The array of post processes to render.
  40397. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40398. */
  40399. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40400. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40401. var camera = this._scene.activeCamera;
  40402. if (!camera) {
  40403. return;
  40404. }
  40405. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40406. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40407. return;
  40408. }
  40409. var engine = this._scene.getEngine();
  40410. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40411. var pp = postProcesses[index];
  40412. if (index < len - 1) {
  40413. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40414. }
  40415. else {
  40416. if (targetTexture) {
  40417. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40418. pp._outputTexture = targetTexture;
  40419. }
  40420. else {
  40421. engine.restoreDefaultFramebuffer();
  40422. pp._outputTexture = null;
  40423. }
  40424. }
  40425. if (doNotPresent) {
  40426. break;
  40427. }
  40428. var effect = pp.apply();
  40429. if (effect) {
  40430. pp.onBeforeRenderObservable.notifyObservers(effect);
  40431. // VBOs
  40432. this._prepareBuffers();
  40433. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40434. // Draw order
  40435. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40436. pp.onAfterRenderObservable.notifyObservers(effect);
  40437. }
  40438. }
  40439. // Restore states
  40440. engine.setDepthBuffer(true);
  40441. engine.setDepthWrite(true);
  40442. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40443. };
  40444. /**
  40445. * Disposes of the post process manager.
  40446. */
  40447. PostProcessManager.prototype.dispose = function () {
  40448. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40449. if (buffer) {
  40450. buffer.dispose();
  40451. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40452. }
  40453. if (this._indexBuffer) {
  40454. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40455. this._indexBuffer = null;
  40456. }
  40457. };
  40458. return PostProcessManager;
  40459. }());
  40460. BABYLON.PostProcessManager = PostProcessManager;
  40461. })(BABYLON || (BABYLON = {}));
  40462. //# sourceMappingURL=babylon.postProcessManager.js.map
  40463. var BABYLON;
  40464. (function (BABYLON) {
  40465. /**
  40466. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40467. */
  40468. var PerformanceMonitor = /** @class */ (function () {
  40469. /**
  40470. * constructor
  40471. * @param frameSampleSize The number of samples required to saturate the sliding window
  40472. */
  40473. function PerformanceMonitor(frameSampleSize) {
  40474. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40475. this._enabled = true;
  40476. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40477. }
  40478. /**
  40479. * Samples current frame
  40480. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40481. */
  40482. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40483. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40484. if (!this._enabled)
  40485. return;
  40486. if (this._lastFrameTimeMs != null) {
  40487. var dt = timeMs - this._lastFrameTimeMs;
  40488. this._rollingFrameTime.add(dt);
  40489. }
  40490. this._lastFrameTimeMs = timeMs;
  40491. };
  40492. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40493. /**
  40494. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40495. * @return Average frame time in milliseconds
  40496. */
  40497. get: function () {
  40498. return this._rollingFrameTime.average;
  40499. },
  40500. enumerable: true,
  40501. configurable: true
  40502. });
  40503. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40504. /**
  40505. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40506. * @return Frame time variance in milliseconds squared
  40507. */
  40508. get: function () {
  40509. return this._rollingFrameTime.variance;
  40510. },
  40511. enumerable: true,
  40512. configurable: true
  40513. });
  40514. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40515. /**
  40516. * Returns the frame time of the most recent frame
  40517. * @return Frame time in milliseconds
  40518. */
  40519. get: function () {
  40520. return this._rollingFrameTime.history(0);
  40521. },
  40522. enumerable: true,
  40523. configurable: true
  40524. });
  40525. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40526. /**
  40527. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40528. * @return Framerate in frames per second
  40529. */
  40530. get: function () {
  40531. return 1000.0 / this._rollingFrameTime.average;
  40532. },
  40533. enumerable: true,
  40534. configurable: true
  40535. });
  40536. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40537. /**
  40538. * Returns the average framerate in frames per second using the most recent frame time
  40539. * @return Framerate in frames per second
  40540. */
  40541. get: function () {
  40542. var history = this._rollingFrameTime.history(0);
  40543. if (history === 0) {
  40544. return 0;
  40545. }
  40546. return 1000.0 / history;
  40547. },
  40548. enumerable: true,
  40549. configurable: true
  40550. });
  40551. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40552. /**
  40553. * Returns true if enough samples have been taken to completely fill the sliding window
  40554. * @return true if saturated
  40555. */
  40556. get: function () {
  40557. return this._rollingFrameTime.isSaturated();
  40558. },
  40559. enumerable: true,
  40560. configurable: true
  40561. });
  40562. /**
  40563. * Enables contributions to the sliding window sample set
  40564. */
  40565. PerformanceMonitor.prototype.enable = function () {
  40566. this._enabled = true;
  40567. };
  40568. /**
  40569. * Disables contributions to the sliding window sample set
  40570. * Samples will not be interpolated over the disabled period
  40571. */
  40572. PerformanceMonitor.prototype.disable = function () {
  40573. this._enabled = false;
  40574. //clear last sample to avoid interpolating over the disabled period when next enabled
  40575. this._lastFrameTimeMs = null;
  40576. };
  40577. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40578. /**
  40579. * Returns true if sampling is enabled
  40580. * @return true if enabled
  40581. */
  40582. get: function () {
  40583. return this._enabled;
  40584. },
  40585. enumerable: true,
  40586. configurable: true
  40587. });
  40588. /**
  40589. * Resets performance monitor
  40590. */
  40591. PerformanceMonitor.prototype.reset = function () {
  40592. //clear last sample to avoid interpolating over the disabled period when next enabled
  40593. this._lastFrameTimeMs = null;
  40594. //wipe record
  40595. this._rollingFrameTime.reset();
  40596. };
  40597. return PerformanceMonitor;
  40598. }());
  40599. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40600. /**
  40601. * RollingAverage
  40602. *
  40603. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40604. */
  40605. var RollingAverage = /** @class */ (function () {
  40606. /**
  40607. * constructor
  40608. * @param length The number of samples required to saturate the sliding window
  40609. */
  40610. function RollingAverage(length) {
  40611. this._samples = new Array(length);
  40612. this.reset();
  40613. }
  40614. /**
  40615. * Adds a sample to the sample set
  40616. * @param v The sample value
  40617. */
  40618. RollingAverage.prototype.add = function (v) {
  40619. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40620. var delta;
  40621. //we need to check if we've already wrapped round
  40622. if (this.isSaturated()) {
  40623. //remove bottom of stack from mean
  40624. var bottomValue = this._samples[this._pos];
  40625. delta = bottomValue - this.average;
  40626. this.average -= delta / (this._sampleCount - 1);
  40627. this._m2 -= delta * (bottomValue - this.average);
  40628. }
  40629. else {
  40630. this._sampleCount++;
  40631. }
  40632. //add new value to mean
  40633. delta = v - this.average;
  40634. this.average += delta / (this._sampleCount);
  40635. this._m2 += delta * (v - this.average);
  40636. //set the new variance
  40637. this.variance = this._m2 / (this._sampleCount - 1);
  40638. this._samples[this._pos] = v;
  40639. this._pos++;
  40640. this._pos %= this._samples.length; //positive wrap around
  40641. };
  40642. /**
  40643. * Returns previously added values or null if outside of history or outside the sliding window domain
  40644. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40645. * @return Value previously recorded with add() or null if outside of range
  40646. */
  40647. RollingAverage.prototype.history = function (i) {
  40648. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40649. return 0;
  40650. }
  40651. var i0 = this._wrapPosition(this._pos - 1.0);
  40652. return this._samples[this._wrapPosition(i0 - i)];
  40653. };
  40654. /**
  40655. * Returns true if enough samples have been taken to completely fill the sliding window
  40656. * @return true if sample-set saturated
  40657. */
  40658. RollingAverage.prototype.isSaturated = function () {
  40659. return this._sampleCount >= this._samples.length;
  40660. };
  40661. /**
  40662. * Resets the rolling average (equivalent to 0 samples taken so far)
  40663. */
  40664. RollingAverage.prototype.reset = function () {
  40665. this.average = 0;
  40666. this.variance = 0;
  40667. this._sampleCount = 0;
  40668. this._pos = 0;
  40669. this._m2 = 0;
  40670. };
  40671. /**
  40672. * Wraps a value around the sample range boundaries
  40673. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40674. * @return Wrapped position in sample range
  40675. */
  40676. RollingAverage.prototype._wrapPosition = function (i) {
  40677. var max = this._samples.length;
  40678. return ((i % max) + max) % max;
  40679. };
  40680. return RollingAverage;
  40681. }());
  40682. BABYLON.RollingAverage = RollingAverage;
  40683. })(BABYLON || (BABYLON = {}));
  40684. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40685. var BABYLON;
  40686. (function (BABYLON) {
  40687. /**
  40688. * This groups together the common properties used for image processing either in direct forward pass
  40689. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40690. * or not.
  40691. */
  40692. var ImageProcessingConfiguration = /** @class */ (function () {
  40693. function ImageProcessingConfiguration() {
  40694. /**
  40695. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40696. */
  40697. this.colorCurves = new BABYLON.ColorCurves();
  40698. this._colorCurvesEnabled = false;
  40699. this._colorGradingEnabled = false;
  40700. this._colorGradingWithGreenDepth = true;
  40701. this._colorGradingBGR = true;
  40702. this._exposure = 1.0;
  40703. this._toneMappingEnabled = false;
  40704. this._contrast = 1.0;
  40705. /**
  40706. * Vignette stretch size.
  40707. */
  40708. this.vignetteStretch = 0;
  40709. /**
  40710. * Vignette centre X Offset.
  40711. */
  40712. this.vignetteCentreX = 0;
  40713. /**
  40714. * Vignette centre Y Offset.
  40715. */
  40716. this.vignetteCentreY = 0;
  40717. /**
  40718. * Vignette weight or intensity of the vignette effect.
  40719. */
  40720. this.vignetteWeight = 1.5;
  40721. /**
  40722. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40723. * if vignetteEnabled is set to true.
  40724. */
  40725. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40726. /**
  40727. * Camera field of view used by the Vignette effect.
  40728. */
  40729. this.vignetteCameraFov = 0.5;
  40730. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40731. this._vignetteEnabled = false;
  40732. this._applyByPostProcess = false;
  40733. this._isEnabled = true;
  40734. /**
  40735. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40736. */
  40737. this.onUpdateParameters = new BABYLON.Observable();
  40738. }
  40739. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40740. /**
  40741. * Gets wether the color curves effect is enabled.
  40742. */
  40743. get: function () {
  40744. return this._colorCurvesEnabled;
  40745. },
  40746. /**
  40747. * Sets wether the color curves effect is enabled.
  40748. */
  40749. set: function (value) {
  40750. if (this._colorCurvesEnabled === value) {
  40751. return;
  40752. }
  40753. this._colorCurvesEnabled = value;
  40754. this._updateParameters();
  40755. },
  40756. enumerable: true,
  40757. configurable: true
  40758. });
  40759. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40760. /**
  40761. * Gets wether the color grading effect is enabled.
  40762. */
  40763. get: function () {
  40764. return this._colorGradingEnabled;
  40765. },
  40766. /**
  40767. * Sets wether the color grading effect is enabled.
  40768. */
  40769. set: function (value) {
  40770. if (this._colorGradingEnabled === value) {
  40771. return;
  40772. }
  40773. this._colorGradingEnabled = value;
  40774. this._updateParameters();
  40775. },
  40776. enumerable: true,
  40777. configurable: true
  40778. });
  40779. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40780. /**
  40781. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40782. */
  40783. get: function () {
  40784. return this._colorGradingWithGreenDepth;
  40785. },
  40786. /**
  40787. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40788. */
  40789. set: function (value) {
  40790. if (this._colorGradingWithGreenDepth === value) {
  40791. return;
  40792. }
  40793. this._colorGradingWithGreenDepth = value;
  40794. this._updateParameters();
  40795. },
  40796. enumerable: true,
  40797. configurable: true
  40798. });
  40799. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40800. /**
  40801. * Gets wether the color grading texture contains BGR values.
  40802. */
  40803. get: function () {
  40804. return this._colorGradingBGR;
  40805. },
  40806. /**
  40807. * Sets wether the color grading texture contains BGR values.
  40808. */
  40809. set: function (value) {
  40810. if (this._colorGradingBGR === value) {
  40811. return;
  40812. }
  40813. this._colorGradingBGR = value;
  40814. this._updateParameters();
  40815. },
  40816. enumerable: true,
  40817. configurable: true
  40818. });
  40819. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40820. /**
  40821. * Gets the Exposure used in the effect.
  40822. */
  40823. get: function () {
  40824. return this._exposure;
  40825. },
  40826. /**
  40827. * Sets the Exposure used in the effect.
  40828. */
  40829. set: function (value) {
  40830. if (this._exposure === value) {
  40831. return;
  40832. }
  40833. this._exposure = value;
  40834. this._updateParameters();
  40835. },
  40836. enumerable: true,
  40837. configurable: true
  40838. });
  40839. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40840. /**
  40841. * Gets wether the tone mapping effect is enabled.
  40842. */
  40843. get: function () {
  40844. return this._toneMappingEnabled;
  40845. },
  40846. /**
  40847. * Sets wether the tone mapping effect is enabled.
  40848. */
  40849. set: function (value) {
  40850. if (this._toneMappingEnabled === value) {
  40851. return;
  40852. }
  40853. this._toneMappingEnabled = value;
  40854. this._updateParameters();
  40855. },
  40856. enumerable: true,
  40857. configurable: true
  40858. });
  40859. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40860. /**
  40861. * Gets the contrast used in the effect.
  40862. */
  40863. get: function () {
  40864. return this._contrast;
  40865. },
  40866. /**
  40867. * Sets the contrast used in the effect.
  40868. */
  40869. set: function (value) {
  40870. if (this._contrast === value) {
  40871. return;
  40872. }
  40873. this._contrast = value;
  40874. this._updateParameters();
  40875. },
  40876. enumerable: true,
  40877. configurable: true
  40878. });
  40879. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40880. /**
  40881. * Gets the vignette blend mode allowing different kind of effect.
  40882. */
  40883. get: function () {
  40884. return this._vignetteBlendMode;
  40885. },
  40886. /**
  40887. * Sets the vignette blend mode allowing different kind of effect.
  40888. */
  40889. set: function (value) {
  40890. if (this._vignetteBlendMode === value) {
  40891. return;
  40892. }
  40893. this._vignetteBlendMode = value;
  40894. this._updateParameters();
  40895. },
  40896. enumerable: true,
  40897. configurable: true
  40898. });
  40899. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40900. /**
  40901. * Gets wether the vignette effect is enabled.
  40902. */
  40903. get: function () {
  40904. return this._vignetteEnabled;
  40905. },
  40906. /**
  40907. * Sets wether the vignette effect is enabled.
  40908. */
  40909. set: function (value) {
  40910. if (this._vignetteEnabled === value) {
  40911. return;
  40912. }
  40913. this._vignetteEnabled = value;
  40914. this._updateParameters();
  40915. },
  40916. enumerable: true,
  40917. configurable: true
  40918. });
  40919. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40920. /**
  40921. * Gets wether the image processing is applied through a post process or not.
  40922. */
  40923. get: function () {
  40924. return this._applyByPostProcess;
  40925. },
  40926. /**
  40927. * Sets wether the image processing is applied through a post process or not.
  40928. */
  40929. set: function (value) {
  40930. if (this._applyByPostProcess === value) {
  40931. return;
  40932. }
  40933. this._applyByPostProcess = value;
  40934. this._updateParameters();
  40935. },
  40936. enumerable: true,
  40937. configurable: true
  40938. });
  40939. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40940. /**
  40941. * Gets wether the image processing is enabled or not.
  40942. */
  40943. get: function () {
  40944. return this._isEnabled;
  40945. },
  40946. /**
  40947. * Sets wether the image processing is enabled or not.
  40948. */
  40949. set: function (value) {
  40950. if (this._isEnabled === value) {
  40951. return;
  40952. }
  40953. this._isEnabled = value;
  40954. this._updateParameters();
  40955. },
  40956. enumerable: true,
  40957. configurable: true
  40958. });
  40959. /**
  40960. * Method called each time the image processing information changes requires to recompile the effect.
  40961. */
  40962. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40963. this.onUpdateParameters.notifyObservers(this);
  40964. };
  40965. ImageProcessingConfiguration.prototype.getClassName = function () {
  40966. return "ImageProcessingConfiguration";
  40967. };
  40968. /**
  40969. * Prepare the list of uniforms associated with the Image Processing effects.
  40970. * @param uniformsList The list of uniforms used in the effect
  40971. * @param defines the list of defines currently in use
  40972. */
  40973. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40974. if (defines.EXPOSURE) {
  40975. uniforms.push("exposureLinear");
  40976. }
  40977. if (defines.CONTRAST) {
  40978. uniforms.push("contrast");
  40979. }
  40980. if (defines.COLORGRADING) {
  40981. uniforms.push("colorTransformSettings");
  40982. }
  40983. if (defines.VIGNETTE) {
  40984. uniforms.push("vInverseScreenSize");
  40985. uniforms.push("vignetteSettings1");
  40986. uniforms.push("vignetteSettings2");
  40987. }
  40988. if (defines.COLORCURVES) {
  40989. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40990. }
  40991. };
  40992. /**
  40993. * Prepare the list of samplers associated with the Image Processing effects.
  40994. * @param uniformsList The list of uniforms used in the effect
  40995. * @param defines the list of defines currently in use
  40996. */
  40997. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40998. if (defines.COLORGRADING) {
  40999. samplersList.push("txColorTransform");
  41000. }
  41001. };
  41002. /**
  41003. * Prepare the list of defines associated to the shader.
  41004. * @param defines the list of defines to complete
  41005. */
  41006. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41007. if (forPostProcess === void 0) { forPostProcess = false; }
  41008. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41009. defines.VIGNETTE = false;
  41010. defines.TONEMAPPING = false;
  41011. defines.CONTRAST = false;
  41012. defines.EXPOSURE = false;
  41013. defines.COLORCURVES = false;
  41014. defines.COLORGRADING = false;
  41015. defines.COLORGRADING3D = false;
  41016. defines.IMAGEPROCESSING = false;
  41017. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41018. return;
  41019. }
  41020. defines.VIGNETTE = this.vignetteEnabled;
  41021. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41022. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41023. defines.TONEMAPPING = this.toneMappingEnabled;
  41024. defines.CONTRAST = (this.contrast !== 1.0);
  41025. defines.EXPOSURE = (this.exposure !== 1.0);
  41026. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41027. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41028. if (defines.COLORGRADING) {
  41029. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41030. }
  41031. else {
  41032. defines.COLORGRADING3D = false;
  41033. }
  41034. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41035. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41036. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41037. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41038. };
  41039. /**
  41040. * Returns true if all the image processing information are ready.
  41041. */
  41042. ImageProcessingConfiguration.prototype.isReady = function () {
  41043. // Color Grading texure can not be none blocking.
  41044. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41045. };
  41046. /**
  41047. * Binds the image processing to the shader.
  41048. * @param effect The effect to bind to
  41049. */
  41050. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41051. if (aspectRatio === void 0) { aspectRatio = 1; }
  41052. // Color Curves
  41053. if (this._colorCurvesEnabled && this.colorCurves) {
  41054. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41055. }
  41056. // Vignette
  41057. if (this._vignetteEnabled) {
  41058. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41059. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41060. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41061. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41062. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41063. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41064. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41065. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41066. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41067. var vignettePower = -2.0 * this.vignetteWeight;
  41068. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41069. }
  41070. // Exposure
  41071. effect.setFloat("exposureLinear", this.exposure);
  41072. // Contrast
  41073. effect.setFloat("contrast", this.contrast);
  41074. // Color transform settings
  41075. if (this.colorGradingTexture) {
  41076. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41077. var textureSize = this.colorGradingTexture.getSize().height;
  41078. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41079. 0.5 / textureSize, // textureOffset
  41080. textureSize, // textureSize
  41081. this.colorGradingTexture.level // weight
  41082. );
  41083. }
  41084. };
  41085. /**
  41086. * Clones the current image processing instance.
  41087. * @return The cloned image processing
  41088. */
  41089. ImageProcessingConfiguration.prototype.clone = function () {
  41090. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41091. };
  41092. /**
  41093. * Serializes the current image processing instance to a json representation.
  41094. * @return a JSON representation
  41095. */
  41096. ImageProcessingConfiguration.prototype.serialize = function () {
  41097. return BABYLON.SerializationHelper.Serialize(this);
  41098. };
  41099. /**
  41100. * Parses the image processing from a json representation.
  41101. * @param source the JSON source to parse
  41102. * @return The parsed image processing
  41103. */
  41104. ImageProcessingConfiguration.Parse = function (source) {
  41105. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41106. };
  41107. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41108. /**
  41109. * Used to apply the vignette as a mix with the pixel color.
  41110. */
  41111. get: function () {
  41112. return this._VIGNETTEMODE_MULTIPLY;
  41113. },
  41114. enumerable: true,
  41115. configurable: true
  41116. });
  41117. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41118. /**
  41119. * Used to apply the vignette as a replacement of the pixel color.
  41120. */
  41121. get: function () {
  41122. return this._VIGNETTEMODE_OPAQUE;
  41123. },
  41124. enumerable: true,
  41125. configurable: true
  41126. });
  41127. // Static constants associated to the image processing.
  41128. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41129. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41130. __decorate([
  41131. BABYLON.serializeAsColorCurves()
  41132. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41133. __decorate([
  41134. BABYLON.serialize()
  41135. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41136. __decorate([
  41137. BABYLON.serializeAsTexture()
  41138. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41139. __decorate([
  41140. BABYLON.serialize()
  41141. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41142. __decorate([
  41143. BABYLON.serialize()
  41144. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41145. __decorate([
  41146. BABYLON.serialize()
  41147. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41148. __decorate([
  41149. BABYLON.serialize()
  41150. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41151. __decorate([
  41152. BABYLON.serialize()
  41153. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41154. __decorate([
  41155. BABYLON.serialize()
  41156. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41157. __decorate([
  41158. BABYLON.serialize()
  41159. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41160. __decorate([
  41161. BABYLON.serialize()
  41162. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41163. __decorate([
  41164. BABYLON.serialize()
  41165. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41166. __decorate([
  41167. BABYLON.serialize()
  41168. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41169. __decorate([
  41170. BABYLON.serializeAsColor4()
  41171. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41172. __decorate([
  41173. BABYLON.serialize()
  41174. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41175. __decorate([
  41176. BABYLON.serialize()
  41177. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41178. __decorate([
  41179. BABYLON.serialize()
  41180. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41181. __decorate([
  41182. BABYLON.serialize()
  41183. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41184. __decorate([
  41185. BABYLON.serialize()
  41186. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41187. return ImageProcessingConfiguration;
  41188. }());
  41189. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41190. })(BABYLON || (BABYLON = {}));
  41191. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41192. var BABYLON;
  41193. (function (BABYLON) {
  41194. /**
  41195. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41196. * It can help converting any input color in a desired output one. This can then be used to create effects
  41197. * from sepia, black and white to sixties or futuristic rendering...
  41198. *
  41199. * The only supported format is currently 3dl.
  41200. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41201. */
  41202. var ColorGradingTexture = /** @class */ (function (_super) {
  41203. __extends(ColorGradingTexture, _super);
  41204. /**
  41205. * Instantiates a ColorGradingTexture from the following parameters.
  41206. *
  41207. * @param url The location of the color gradind data (currently only supporting 3dl)
  41208. * @param scene The scene the texture will be used in
  41209. */
  41210. function ColorGradingTexture(url, scene) {
  41211. var _this = _super.call(this, scene) || this;
  41212. if (!url) {
  41213. return _this;
  41214. }
  41215. _this._engine = scene.getEngine();
  41216. _this._textureMatrix = BABYLON.Matrix.Identity();
  41217. _this.name = url;
  41218. _this.url = url;
  41219. _this.hasAlpha = false;
  41220. _this.isCube = false;
  41221. _this.is3D = _this._engine.webGLVersion > 1;
  41222. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41223. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41224. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41225. _this.anisotropicFilteringLevel = 1;
  41226. _this._texture = _this._getFromCache(url, true);
  41227. if (!_this._texture) {
  41228. if (!scene.useDelayedTextureLoading) {
  41229. _this.loadTexture();
  41230. }
  41231. else {
  41232. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41233. }
  41234. }
  41235. return _this;
  41236. }
  41237. /**
  41238. * Returns the texture matrix used in most of the material.
  41239. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41240. */
  41241. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41242. return this._textureMatrix;
  41243. };
  41244. /**
  41245. * Occurs when the file being loaded is a .3dl LUT file.
  41246. */
  41247. ColorGradingTexture.prototype.load3dlTexture = function () {
  41248. var engine = this._engine;
  41249. var texture;
  41250. if (engine.webGLVersion === 1) {
  41251. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41252. }
  41253. else {
  41254. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41255. }
  41256. this._texture = texture;
  41257. var callback = function (text) {
  41258. if (typeof text !== "string") {
  41259. return;
  41260. }
  41261. var data = null;
  41262. var tempData = null;
  41263. var line;
  41264. var lines = text.split('\n');
  41265. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41266. var maxColor = 0;
  41267. for (var i = 0; i < lines.length; i++) {
  41268. line = lines[i];
  41269. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41270. continue;
  41271. if (line.indexOf('#') === 0)
  41272. continue;
  41273. var words = line.split(" ");
  41274. if (size === 0) {
  41275. // Number of space + one
  41276. size = words.length;
  41277. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41278. tempData = new Float32Array(size * size * size * 4);
  41279. continue;
  41280. }
  41281. if (size != 0) {
  41282. var r = Math.max(parseInt(words[0]), 0);
  41283. var g = Math.max(parseInt(words[1]), 0);
  41284. var b = Math.max(parseInt(words[2]), 0);
  41285. maxColor = Math.max(r, maxColor);
  41286. maxColor = Math.max(g, maxColor);
  41287. maxColor = Math.max(b, maxColor);
  41288. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41289. if (tempData) {
  41290. tempData[pixelStorageIndex + 0] = r;
  41291. tempData[pixelStorageIndex + 1] = g;
  41292. tempData[pixelStorageIndex + 2] = b;
  41293. }
  41294. pixelIndexSlice++;
  41295. if (pixelIndexSlice % size == 0) {
  41296. pixelIndexH++;
  41297. pixelIndexSlice = 0;
  41298. if (pixelIndexH % size == 0) {
  41299. pixelIndexW++;
  41300. pixelIndexH = 0;
  41301. }
  41302. }
  41303. }
  41304. }
  41305. if (tempData && data) {
  41306. for (var i = 0; i < tempData.length; i++) {
  41307. if (i > 0 && (i + 1) % 4 === 0) {
  41308. data[i] = 255;
  41309. }
  41310. else {
  41311. var value = tempData[i];
  41312. data[i] = (value / maxColor * 255);
  41313. }
  41314. }
  41315. }
  41316. if (texture.is3D) {
  41317. texture.updateSize(size, size, size);
  41318. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41319. }
  41320. else {
  41321. texture.updateSize(size * size, size);
  41322. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41323. }
  41324. };
  41325. var scene = this.getScene();
  41326. if (scene) {
  41327. scene._loadFile(this.url, callback);
  41328. }
  41329. else {
  41330. this._engine._loadFile(this.url, callback);
  41331. }
  41332. return this._texture;
  41333. };
  41334. /**
  41335. * Starts the loading process of the texture.
  41336. */
  41337. ColorGradingTexture.prototype.loadTexture = function () {
  41338. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41339. this.load3dlTexture();
  41340. }
  41341. };
  41342. /**
  41343. * Clones the color gradind texture.
  41344. */
  41345. ColorGradingTexture.prototype.clone = function () {
  41346. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41347. // Base texture
  41348. newTexture.level = this.level;
  41349. return newTexture;
  41350. };
  41351. /**
  41352. * Called during delayed load for textures.
  41353. */
  41354. ColorGradingTexture.prototype.delayLoad = function () {
  41355. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41356. return;
  41357. }
  41358. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41359. this._texture = this._getFromCache(this.url, true);
  41360. if (!this._texture) {
  41361. this.loadTexture();
  41362. }
  41363. };
  41364. /**
  41365. * Parses a color grading texture serialized by Babylon.
  41366. * @param parsedTexture The texture information being parsedTexture
  41367. * @param scene The scene to load the texture in
  41368. * @param rootUrl The root url of the data assets to load
  41369. * @return A color gradind texture
  41370. */
  41371. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41372. var texture = null;
  41373. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41374. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41375. texture.name = parsedTexture.name;
  41376. texture.level = parsedTexture.level;
  41377. }
  41378. return texture;
  41379. };
  41380. /**
  41381. * Serializes the LUT texture to json format.
  41382. */
  41383. ColorGradingTexture.prototype.serialize = function () {
  41384. if (!this.name) {
  41385. return null;
  41386. }
  41387. var serializationObject = {};
  41388. serializationObject.name = this.name;
  41389. serializationObject.level = this.level;
  41390. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41391. return serializationObject;
  41392. };
  41393. /**
  41394. * Empty line regex stored for GC.
  41395. */
  41396. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41397. return ColorGradingTexture;
  41398. }(BABYLON.BaseTexture));
  41399. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41400. })(BABYLON || (BABYLON = {}));
  41401. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41402. var BABYLON;
  41403. (function (BABYLON) {
  41404. /**
  41405. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41406. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41407. * 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;
  41408. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41409. */
  41410. var ColorCurves = /** @class */ (function () {
  41411. function ColorCurves() {
  41412. this._dirty = true;
  41413. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41414. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41415. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41416. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41417. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41418. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41419. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41420. this._globalHue = 30;
  41421. this._globalDensity = 0;
  41422. this._globalSaturation = 0;
  41423. this._globalExposure = 0;
  41424. this._highlightsHue = 30;
  41425. this._highlightsDensity = 0;
  41426. this._highlightsSaturation = 0;
  41427. this._highlightsExposure = 0;
  41428. this._midtonesHue = 30;
  41429. this._midtonesDensity = 0;
  41430. this._midtonesSaturation = 0;
  41431. this._midtonesExposure = 0;
  41432. this._shadowsHue = 30;
  41433. this._shadowsDensity = 0;
  41434. this._shadowsSaturation = 0;
  41435. this._shadowsExposure = 0;
  41436. }
  41437. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41438. /**
  41439. * Gets the global Hue value.
  41440. * 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).
  41441. */
  41442. get: function () {
  41443. return this._globalHue;
  41444. },
  41445. /**
  41446. * Sets the global Hue value.
  41447. * 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).
  41448. */
  41449. set: function (value) {
  41450. this._globalHue = value;
  41451. this._dirty = true;
  41452. },
  41453. enumerable: true,
  41454. configurable: true
  41455. });
  41456. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41457. /**
  41458. * Gets the global Density value.
  41459. * 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.
  41460. * Values less than zero provide a filter of opposite hue.
  41461. */
  41462. get: function () {
  41463. return this._globalDensity;
  41464. },
  41465. /**
  41466. * Sets the global Density value.
  41467. * 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.
  41468. * Values less than zero provide a filter of opposite hue.
  41469. */
  41470. set: function (value) {
  41471. this._globalDensity = value;
  41472. this._dirty = true;
  41473. },
  41474. enumerable: true,
  41475. configurable: true
  41476. });
  41477. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41478. /**
  41479. * Gets the global Saturation value.
  41480. * 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.
  41481. */
  41482. get: function () {
  41483. return this._globalSaturation;
  41484. },
  41485. /**
  41486. * Sets the global Saturation value.
  41487. * 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.
  41488. */
  41489. set: function (value) {
  41490. this._globalSaturation = value;
  41491. this._dirty = true;
  41492. },
  41493. enumerable: true,
  41494. configurable: true
  41495. });
  41496. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41497. /**
  41498. * Gets the highlights Hue value.
  41499. * 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).
  41500. */
  41501. get: function () {
  41502. return this._highlightsHue;
  41503. },
  41504. /**
  41505. * Sets the highlights Hue value.
  41506. * 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).
  41507. */
  41508. set: function (value) {
  41509. this._highlightsHue = value;
  41510. this._dirty = true;
  41511. },
  41512. enumerable: true,
  41513. configurable: true
  41514. });
  41515. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41516. /**
  41517. * Gets the highlights Density value.
  41518. * 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.
  41519. * Values less than zero provide a filter of opposite hue.
  41520. */
  41521. get: function () {
  41522. return this._highlightsDensity;
  41523. },
  41524. /**
  41525. * Sets the highlights Density value.
  41526. * 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.
  41527. * Values less than zero provide a filter of opposite hue.
  41528. */
  41529. set: function (value) {
  41530. this._highlightsDensity = value;
  41531. this._dirty = true;
  41532. },
  41533. enumerable: true,
  41534. configurable: true
  41535. });
  41536. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41537. /**
  41538. * Gets the highlights Saturation value.
  41539. * 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.
  41540. */
  41541. get: function () {
  41542. return this._highlightsSaturation;
  41543. },
  41544. /**
  41545. * Sets the highlights Saturation value.
  41546. * 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.
  41547. */
  41548. set: function (value) {
  41549. this._highlightsSaturation = value;
  41550. this._dirty = true;
  41551. },
  41552. enumerable: true,
  41553. configurable: true
  41554. });
  41555. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41556. /**
  41557. * Gets the highlights Exposure value.
  41558. * 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.
  41559. */
  41560. get: function () {
  41561. return this._highlightsExposure;
  41562. },
  41563. /**
  41564. * Sets the highlights Exposure value.
  41565. * 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.
  41566. */
  41567. set: function (value) {
  41568. this._highlightsExposure = value;
  41569. this._dirty = true;
  41570. },
  41571. enumerable: true,
  41572. configurable: true
  41573. });
  41574. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41575. /**
  41576. * Gets the midtones Hue value.
  41577. * 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).
  41578. */
  41579. get: function () {
  41580. return this._midtonesHue;
  41581. },
  41582. /**
  41583. * Sets the midtones Hue value.
  41584. * 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).
  41585. */
  41586. set: function (value) {
  41587. this._midtonesHue = value;
  41588. this._dirty = true;
  41589. },
  41590. enumerable: true,
  41591. configurable: true
  41592. });
  41593. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41594. /**
  41595. * Gets the midtones Density value.
  41596. * 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.
  41597. * Values less than zero provide a filter of opposite hue.
  41598. */
  41599. get: function () {
  41600. return this._midtonesDensity;
  41601. },
  41602. /**
  41603. * Sets the midtones Density value.
  41604. * 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.
  41605. * Values less than zero provide a filter of opposite hue.
  41606. */
  41607. set: function (value) {
  41608. this._midtonesDensity = value;
  41609. this._dirty = true;
  41610. },
  41611. enumerable: true,
  41612. configurable: true
  41613. });
  41614. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41615. /**
  41616. * Gets the midtones Saturation value.
  41617. * 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.
  41618. */
  41619. get: function () {
  41620. return this._midtonesSaturation;
  41621. },
  41622. /**
  41623. * Sets the midtones Saturation value.
  41624. * 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.
  41625. */
  41626. set: function (value) {
  41627. this._midtonesSaturation = value;
  41628. this._dirty = true;
  41629. },
  41630. enumerable: true,
  41631. configurable: true
  41632. });
  41633. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41634. /**
  41635. * Gets the midtones Exposure value.
  41636. * 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.
  41637. */
  41638. get: function () {
  41639. return this._midtonesExposure;
  41640. },
  41641. /**
  41642. * Sets the midtones Exposure value.
  41643. * 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.
  41644. */
  41645. set: function (value) {
  41646. this._midtonesExposure = value;
  41647. this._dirty = true;
  41648. },
  41649. enumerable: true,
  41650. configurable: true
  41651. });
  41652. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41653. /**
  41654. * Gets the shadows Hue value.
  41655. * 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).
  41656. */
  41657. get: function () {
  41658. return this._shadowsHue;
  41659. },
  41660. /**
  41661. * Sets the shadows Hue value.
  41662. * 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).
  41663. */
  41664. set: function (value) {
  41665. this._shadowsHue = value;
  41666. this._dirty = true;
  41667. },
  41668. enumerable: true,
  41669. configurable: true
  41670. });
  41671. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41672. /**
  41673. * Gets the shadows Density value.
  41674. * 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.
  41675. * Values less than zero provide a filter of opposite hue.
  41676. */
  41677. get: function () {
  41678. return this._shadowsDensity;
  41679. },
  41680. /**
  41681. * Sets the shadows Density value.
  41682. * 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.
  41683. * Values less than zero provide a filter of opposite hue.
  41684. */
  41685. set: function (value) {
  41686. this._shadowsDensity = value;
  41687. this._dirty = true;
  41688. },
  41689. enumerable: true,
  41690. configurable: true
  41691. });
  41692. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41693. /**
  41694. * Gets the shadows Saturation value.
  41695. * 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.
  41696. */
  41697. get: function () {
  41698. return this._shadowsSaturation;
  41699. },
  41700. /**
  41701. * Sets the shadows Saturation value.
  41702. * 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.
  41703. */
  41704. set: function (value) {
  41705. this._shadowsSaturation = value;
  41706. this._dirty = true;
  41707. },
  41708. enumerable: true,
  41709. configurable: true
  41710. });
  41711. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41712. /**
  41713. * Gets the shadows Exposure value.
  41714. * 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.
  41715. */
  41716. get: function () {
  41717. return this._shadowsExposure;
  41718. },
  41719. /**
  41720. * Sets the shadows Exposure value.
  41721. * 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.
  41722. */
  41723. set: function (value) {
  41724. this._shadowsExposure = value;
  41725. this._dirty = true;
  41726. },
  41727. enumerable: true,
  41728. configurable: true
  41729. });
  41730. ColorCurves.prototype.getClassName = function () {
  41731. return "ColorCurves";
  41732. };
  41733. /**
  41734. * Binds the color curves to the shader.
  41735. * @param colorCurves The color curve to bind
  41736. * @param effect The effect to bind to
  41737. */
  41738. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41739. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41740. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41741. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41742. if (colorCurves._dirty) {
  41743. colorCurves._dirty = false;
  41744. // Fill in global info.
  41745. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41746. // Compute highlights info.
  41747. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41748. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41749. // Compute midtones info.
  41750. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41751. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41752. // Compute shadows info.
  41753. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41754. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41755. // Compute deltas (neutral is midtones).
  41756. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41757. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41758. }
  41759. if (effect) {
  41760. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41761. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41762. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41763. }
  41764. };
  41765. /**
  41766. * Prepare the list of uniforms associated with the ColorCurves effects.
  41767. * @param uniformsList The list of uniforms used in the effect
  41768. */
  41769. ColorCurves.PrepareUniforms = function (uniformsList) {
  41770. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41771. };
  41772. /**
  41773. * Returns color grading data based on a hue, density, saturation and exposure value.
  41774. * @param filterHue The hue of the color filter.
  41775. * @param filterDensity The density of the color filter.
  41776. * @param saturation The saturation.
  41777. * @param exposure The exposure.
  41778. * @param result The result data container.
  41779. */
  41780. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41781. if (hue == null) {
  41782. return;
  41783. }
  41784. hue = ColorCurves.clamp(hue, 0, 360);
  41785. density = ColorCurves.clamp(density, -100, 100);
  41786. saturation = ColorCurves.clamp(saturation, -100, 100);
  41787. exposure = ColorCurves.clamp(exposure, -100, 100);
  41788. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41789. // so that the maximum filter density is only 50% control. This provides fine control
  41790. // for small values and reasonable range.
  41791. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41792. density *= 0.5;
  41793. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41794. if (density < 0) {
  41795. density *= -1;
  41796. hue = (hue + 180) % 360;
  41797. }
  41798. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41799. result.scaleToRef(2, result);
  41800. result.a = 1 + 0.01 * saturation;
  41801. };
  41802. /**
  41803. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41804. * @param value The input slider value in range [-100,100].
  41805. * @returns Adjusted value.
  41806. */
  41807. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41808. value /= 100;
  41809. var x = Math.abs(value);
  41810. x = Math.pow(x, 2);
  41811. if (value < 0) {
  41812. x *= -1;
  41813. }
  41814. x *= 100;
  41815. return x;
  41816. };
  41817. /**
  41818. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41819. * @param hue The hue (H) input.
  41820. * @param saturation The saturation (S) input.
  41821. * @param brightness The brightness (B) input.
  41822. * @result An RGBA color represented as Vector4.
  41823. */
  41824. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41825. var h = ColorCurves.clamp(hue, 0, 360);
  41826. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41827. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41828. if (s === 0) {
  41829. result.r = v;
  41830. result.g = v;
  41831. result.b = v;
  41832. }
  41833. else {
  41834. // sector 0 to 5
  41835. h /= 60;
  41836. var i = Math.floor(h);
  41837. // fractional part of h
  41838. var f = h - i;
  41839. var p = v * (1 - s);
  41840. var q = v * (1 - s * f);
  41841. var t = v * (1 - s * (1 - f));
  41842. switch (i) {
  41843. case 0:
  41844. result.r = v;
  41845. result.g = t;
  41846. result.b = p;
  41847. break;
  41848. case 1:
  41849. result.r = q;
  41850. result.g = v;
  41851. result.b = p;
  41852. break;
  41853. case 2:
  41854. result.r = p;
  41855. result.g = v;
  41856. result.b = t;
  41857. break;
  41858. case 3:
  41859. result.r = p;
  41860. result.g = q;
  41861. result.b = v;
  41862. break;
  41863. case 4:
  41864. result.r = t;
  41865. result.g = p;
  41866. result.b = v;
  41867. break;
  41868. default: // case 5:
  41869. result.r = v;
  41870. result.g = p;
  41871. result.b = q;
  41872. break;
  41873. }
  41874. }
  41875. result.a = 1;
  41876. };
  41877. /**
  41878. * Returns a value clamped between min and max
  41879. * @param value The value to clamp
  41880. * @param min The minimum of value
  41881. * @param max The maximum of value
  41882. * @returns The clamped value.
  41883. */
  41884. ColorCurves.clamp = function (value, min, max) {
  41885. return Math.min(Math.max(value, min), max);
  41886. };
  41887. /**
  41888. * Clones the current color curve instance.
  41889. * @return The cloned curves
  41890. */
  41891. ColorCurves.prototype.clone = function () {
  41892. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41893. };
  41894. /**
  41895. * Serializes the current color curve instance to a json representation.
  41896. * @return a JSON representation
  41897. */
  41898. ColorCurves.prototype.serialize = function () {
  41899. return BABYLON.SerializationHelper.Serialize(this);
  41900. };
  41901. /**
  41902. * Parses the color curve from a json representation.
  41903. * @param source the JSON source to parse
  41904. * @return The parsed curves
  41905. */
  41906. ColorCurves.Parse = function (source) {
  41907. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41908. };
  41909. __decorate([
  41910. BABYLON.serialize()
  41911. ], ColorCurves.prototype, "_globalHue", void 0);
  41912. __decorate([
  41913. BABYLON.serialize()
  41914. ], ColorCurves.prototype, "_globalDensity", void 0);
  41915. __decorate([
  41916. BABYLON.serialize()
  41917. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41918. __decorate([
  41919. BABYLON.serialize()
  41920. ], ColorCurves.prototype, "_globalExposure", void 0);
  41921. __decorate([
  41922. BABYLON.serialize()
  41923. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41924. __decorate([
  41925. BABYLON.serialize()
  41926. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41927. __decorate([
  41928. BABYLON.serialize()
  41929. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41930. __decorate([
  41931. BABYLON.serialize()
  41932. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41933. __decorate([
  41934. BABYLON.serialize()
  41935. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41936. __decorate([
  41937. BABYLON.serialize()
  41938. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41939. __decorate([
  41940. BABYLON.serialize()
  41941. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41942. __decorate([
  41943. BABYLON.serialize()
  41944. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41945. return ColorCurves;
  41946. }());
  41947. BABYLON.ColorCurves = ColorCurves;
  41948. })(BABYLON || (BABYLON = {}));
  41949. //# sourceMappingURL=babylon.colorCurves.js.map
  41950. //# sourceMappingURL=babylon.behavior.js.map
  41951. var BABYLON;
  41952. (function (BABYLON) {
  41953. /**
  41954. * "Static Class" containing the most commonly used helper while dealing with material for
  41955. * rendering purpose.
  41956. *
  41957. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41958. *
  41959. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41960. */
  41961. var MaterialHelper = /** @class */ (function () {
  41962. function MaterialHelper() {
  41963. }
  41964. /**
  41965. * Bind the current view position to an effect.
  41966. * @param effect The effect to be bound
  41967. * @param scene The scene the eyes position is used from
  41968. */
  41969. MaterialHelper.BindEyePosition = function (effect, scene) {
  41970. if (scene._forcedViewPosition) {
  41971. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41972. return;
  41973. }
  41974. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41975. };
  41976. /**
  41977. * Helps preparing the defines values about the UVs in used in the effect.
  41978. * UVs are shared as much as we can accross chanels in the shaders.
  41979. * @param texture The texture we are preparing the UVs for
  41980. * @param defines The defines to update
  41981. * @param key The chanel key "diffuse", "specular"... used in the shader
  41982. */
  41983. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41984. defines._needUVs = true;
  41985. defines[key] = true;
  41986. if (texture.getTextureMatrix().isIdentity(true)) {
  41987. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41988. if (texture.coordinatesIndex === 0) {
  41989. defines["MAINUV1"] = true;
  41990. }
  41991. else {
  41992. defines["MAINUV2"] = true;
  41993. }
  41994. }
  41995. else {
  41996. defines[key + "DIRECTUV"] = 0;
  41997. }
  41998. };
  41999. /**
  42000. * Binds a texture matrix value to its corrsponding uniform
  42001. * @param texture The texture to bind the matrix for
  42002. * @param uniformBuffer The uniform buffer receivin the data
  42003. * @param key The chanel key "diffuse", "specular"... used in the shader
  42004. */
  42005. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42006. var matrix = texture.getTextureMatrix();
  42007. if (!matrix.isIdentity(true)) {
  42008. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42009. }
  42010. };
  42011. /**
  42012. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42013. * @param mesh defines the current mesh
  42014. * @param scene defines the current scene
  42015. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42016. * @param pointsCloud defines if point cloud rendering has to be turned on
  42017. * @param fogEnabled defines if fog has to be turned on
  42018. * @param alphaTest defines if alpha testing has to be turned on
  42019. * @param defines defines the current list of defines
  42020. */
  42021. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42022. if (defines._areMiscDirty) {
  42023. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42024. defines["POINTSIZE"] = pointsCloud;
  42025. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42026. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42027. defines["ALPHATEST"] = alphaTest;
  42028. }
  42029. };
  42030. /**
  42031. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42032. * @param scene defines the current scene
  42033. * @param engine defines the current engine
  42034. * @param defines specifies the list of active defines
  42035. * @param useInstances defines if instances have to be turned on
  42036. * @param useClipPlane defines if clip plane have to be turned on
  42037. */
  42038. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42039. if (useClipPlane === void 0) { useClipPlane = null; }
  42040. var changed = false;
  42041. if (useClipPlane == null) {
  42042. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42043. }
  42044. if (defines["CLIPPLANE"] !== useClipPlane) {
  42045. defines["CLIPPLANE"] = useClipPlane;
  42046. changed = true;
  42047. }
  42048. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42049. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42050. changed = true;
  42051. }
  42052. if (defines["INSTANCES"] !== useInstances) {
  42053. defines["INSTANCES"] = useInstances;
  42054. changed = true;
  42055. }
  42056. if (changed) {
  42057. defines.markAsUnprocessed();
  42058. }
  42059. };
  42060. /**
  42061. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42062. * @param mesh The mesh containing the geometry data we will draw
  42063. * @param defines The defines to update
  42064. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42065. * @param useBones Precise whether bones should be used or not (override mesh info)
  42066. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42067. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42068. * @returns false if defines are considered not dirty and have not been checked
  42069. */
  42070. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42071. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42072. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42073. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42074. return false;
  42075. }
  42076. defines._normals = defines._needNormals;
  42077. defines._uvs = defines._needUVs;
  42078. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42079. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42080. defines["TANGENT"] = true;
  42081. }
  42082. if (defines._needUVs) {
  42083. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42084. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42085. }
  42086. else {
  42087. defines["UV1"] = false;
  42088. defines["UV2"] = false;
  42089. }
  42090. if (useVertexColor) {
  42091. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42092. defines["VERTEXCOLOR"] = hasVertexColors;
  42093. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42094. }
  42095. if (useBones) {
  42096. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42097. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42098. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42099. }
  42100. else {
  42101. defines["NUM_BONE_INFLUENCERS"] = 0;
  42102. defines["BonesPerMesh"] = 0;
  42103. }
  42104. }
  42105. if (useMorphTargets) {
  42106. var manager = mesh.morphTargetManager;
  42107. if (manager) {
  42108. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42109. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42110. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42111. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42112. }
  42113. else {
  42114. defines["MORPHTARGETS_TANGENT"] = false;
  42115. defines["MORPHTARGETS_NORMAL"] = false;
  42116. defines["MORPHTARGETS"] = false;
  42117. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42118. }
  42119. }
  42120. return true;
  42121. };
  42122. /**
  42123. * Prepares the defines related to the light information passed in parameter
  42124. * @param scene The scene we are intending to draw
  42125. * @param mesh The mesh the effect is compiling for
  42126. * @param defines The defines to update
  42127. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42128. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42129. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42130. * @returns true if normals will be required for the rest of the effect
  42131. */
  42132. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42133. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42134. if (disableLighting === void 0) { disableLighting = false; }
  42135. if (!defines._areLightsDirty) {
  42136. return defines._needNormals;
  42137. }
  42138. var lightIndex = 0;
  42139. var needNormals = false;
  42140. var needRebuild = false;
  42141. var lightmapMode = false;
  42142. var shadowEnabled = false;
  42143. var specularEnabled = false;
  42144. if (scene.lightsEnabled && !disableLighting) {
  42145. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42146. var light = _a[_i];
  42147. needNormals = true;
  42148. if (defines["LIGHT" + lightIndex] === undefined) {
  42149. needRebuild = true;
  42150. }
  42151. defines["LIGHT" + lightIndex] = true;
  42152. defines["SPOTLIGHT" + lightIndex] = false;
  42153. defines["HEMILIGHT" + lightIndex] = false;
  42154. defines["POINTLIGHT" + lightIndex] = false;
  42155. defines["DIRLIGHT" + lightIndex] = false;
  42156. var type;
  42157. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42158. type = "SPOTLIGHT" + lightIndex;
  42159. var spotLight = light;
  42160. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42161. }
  42162. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42163. type = "HEMILIGHT" + lightIndex;
  42164. }
  42165. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42166. type = "POINTLIGHT" + lightIndex;
  42167. }
  42168. else {
  42169. type = "DIRLIGHT" + lightIndex;
  42170. }
  42171. defines[type] = true;
  42172. // Specular
  42173. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42174. specularEnabled = true;
  42175. }
  42176. // Shadows
  42177. defines["SHADOW" + lightIndex] = false;
  42178. defines["SHADOWPCF" + lightIndex] = false;
  42179. defines["SHADOWPCSS" + lightIndex] = false;
  42180. defines["SHADOWPOISSON" + lightIndex] = false;
  42181. defines["SHADOWESM" + lightIndex] = false;
  42182. defines["SHADOWCUBE" + lightIndex] = false;
  42183. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42184. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42185. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42186. var shadowGenerator = light.getShadowGenerator();
  42187. if (shadowGenerator) {
  42188. shadowEnabled = true;
  42189. shadowGenerator.prepareDefines(defines, lightIndex);
  42190. }
  42191. }
  42192. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42193. lightmapMode = true;
  42194. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42195. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42196. }
  42197. else {
  42198. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42199. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42200. }
  42201. lightIndex++;
  42202. if (lightIndex === maxSimultaneousLights)
  42203. break;
  42204. }
  42205. }
  42206. defines["SPECULARTERM"] = specularEnabled;
  42207. defines["SHADOWS"] = shadowEnabled;
  42208. // Resetting all other lights if any
  42209. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42210. if (defines["LIGHT" + index] !== undefined) {
  42211. defines["LIGHT" + index] = false;
  42212. defines["HEMILIGHT" + lightIndex] = false;
  42213. defines["POINTLIGHT" + lightIndex] = false;
  42214. defines["DIRLIGHT" + lightIndex] = false;
  42215. defines["SPOTLIGHT" + lightIndex] = false;
  42216. defines["SHADOW" + lightIndex] = false;
  42217. }
  42218. }
  42219. var caps = scene.getEngine().getCaps();
  42220. if (defines["SHADOWFLOAT"] === undefined) {
  42221. needRebuild = true;
  42222. }
  42223. defines["SHADOWFLOAT"] = shadowEnabled &&
  42224. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42225. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42226. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42227. if (needRebuild) {
  42228. defines.rebuild();
  42229. }
  42230. return needNormals;
  42231. };
  42232. /**
  42233. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42234. * that won t be acctive due to defines being turned off.
  42235. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42236. * @param samplersList The samplers list
  42237. * @param defines The defines helping in the list generation
  42238. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42239. */
  42240. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42241. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42242. var uniformsList;
  42243. var uniformBuffersList = null;
  42244. if (uniformsListOrOptions.uniformsNames) {
  42245. var options = uniformsListOrOptions;
  42246. uniformsList = options.uniformsNames;
  42247. uniformBuffersList = options.uniformBuffersNames;
  42248. samplersList = options.samplers;
  42249. defines = options.defines;
  42250. maxSimultaneousLights = options.maxSimultaneousLights;
  42251. }
  42252. else {
  42253. uniformsList = uniformsListOrOptions;
  42254. if (!samplersList) {
  42255. samplersList = [];
  42256. }
  42257. }
  42258. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42259. if (!defines["LIGHT" + lightIndex]) {
  42260. break;
  42261. }
  42262. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42263. if (uniformBuffersList) {
  42264. uniformBuffersList.push("Light" + lightIndex);
  42265. }
  42266. samplersList.push("shadowSampler" + lightIndex);
  42267. samplersList.push("depthSampler" + lightIndex);
  42268. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42269. samplersList.push("projectionLightSampler" + lightIndex);
  42270. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42271. }
  42272. }
  42273. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42274. uniformsList.push("morphTargetInfluences");
  42275. }
  42276. };
  42277. /**
  42278. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42279. * @param defines The defines to update while falling back
  42280. * @param fallbacks The authorized effect fallbacks
  42281. * @param maxSimultaneousLights The maximum number of lights allowed
  42282. * @param rank the current rank of the Effect
  42283. * @returns The newly affected rank
  42284. */
  42285. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42286. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42287. if (rank === void 0) { rank = 0; }
  42288. var lightFallbackRank = 0;
  42289. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42290. if (!defines["LIGHT" + lightIndex]) {
  42291. break;
  42292. }
  42293. if (lightIndex > 0) {
  42294. lightFallbackRank = rank + lightIndex;
  42295. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42296. }
  42297. if (!defines["SHADOWS"]) {
  42298. if (defines["SHADOW" + lightIndex]) {
  42299. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42300. }
  42301. if (defines["SHADOWPCF" + lightIndex]) {
  42302. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42303. }
  42304. if (defines["SHADOWPCSS" + lightIndex]) {
  42305. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42306. }
  42307. if (defines["SHADOWPOISSON" + lightIndex]) {
  42308. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42309. }
  42310. if (defines["SHADOWESM" + lightIndex]) {
  42311. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42312. }
  42313. }
  42314. }
  42315. return lightFallbackRank++;
  42316. };
  42317. /**
  42318. * Prepares the list of attributes required for morph targets according to the effect defines.
  42319. * @param attribs The current list of supported attribs
  42320. * @param mesh The mesh to prepare the morph targets attributes for
  42321. * @param defines The current Defines of the effect
  42322. */
  42323. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42324. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42325. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42326. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42327. var manager = mesh.morphTargetManager;
  42328. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42329. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42330. for (var index = 0; index < influencers; index++) {
  42331. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42332. if (normal) {
  42333. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42334. }
  42335. if (tangent) {
  42336. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42337. }
  42338. if (attribs.length > maxAttributesCount) {
  42339. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42340. }
  42341. }
  42342. }
  42343. };
  42344. /**
  42345. * Prepares the list of attributes required for bones according to the effect defines.
  42346. * @param attribs The current list of supported attribs
  42347. * @param mesh The mesh to prepare the bones attributes for
  42348. * @param defines The current Defines of the effect
  42349. * @param fallbacks The current efffect fallback strategy
  42350. */
  42351. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42352. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42353. fallbacks.addCPUSkinningFallback(0, mesh);
  42354. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42355. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42356. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42357. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42358. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42359. }
  42360. }
  42361. };
  42362. /**
  42363. * Prepares the list of attributes required for instances according to the effect defines.
  42364. * @param attribs The current list of supported attribs
  42365. * @param defines The current Defines of the effect
  42366. */
  42367. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42368. if (defines["INSTANCES"]) {
  42369. attribs.push("world0");
  42370. attribs.push("world1");
  42371. attribs.push("world2");
  42372. attribs.push("world3");
  42373. }
  42374. };
  42375. /**
  42376. * Binds the light shadow information to the effect for the given mesh.
  42377. * @param light The light containing the generator
  42378. * @param scene The scene the lights belongs to
  42379. * @param mesh The mesh we are binding the information to render
  42380. * @param lightIndex The light index in the effect used to render the mesh
  42381. * @param effect The effect we are binding the data to
  42382. */
  42383. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42384. if (light.shadowEnabled && mesh.receiveShadows) {
  42385. var shadowGenerator = light.getShadowGenerator();
  42386. if (shadowGenerator) {
  42387. shadowGenerator.bindShadowLight(lightIndex, effect);
  42388. }
  42389. }
  42390. };
  42391. /**
  42392. * Binds the light information to the effect.
  42393. * @param light The light containing the generator
  42394. * @param effect The effect we are binding the data to
  42395. * @param lightIndex The light index in the effect used to render
  42396. */
  42397. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42398. light.transferToEffect(effect, lightIndex + "");
  42399. };
  42400. /**
  42401. * Binds the lights information from the scene to the effect for the given mesh.
  42402. * @param scene The scene the lights belongs to
  42403. * @param mesh The mesh we are binding the information to render
  42404. * @param effect The effect we are binding the data to
  42405. * @param defines The generated defines for the effect
  42406. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42407. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42408. */
  42409. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42410. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42411. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42412. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42413. for (var i = 0; i < len; i++) {
  42414. var light = mesh._lightSources[i];
  42415. var iAsString = i.toString();
  42416. var scaledIntensity = light.getScaledIntensity();
  42417. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42418. MaterialHelper.BindLightProperties(light, effect, i);
  42419. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42420. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42421. if (defines["SPECULARTERM"]) {
  42422. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42423. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42424. }
  42425. // Shadows
  42426. if (scene.shadowsEnabled) {
  42427. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42428. }
  42429. light._uniformBuffer.update();
  42430. }
  42431. };
  42432. /**
  42433. * Binds the fog information from the scene to the effect for the given mesh.
  42434. * @param scene The scene the lights belongs to
  42435. * @param mesh The mesh we are binding the information to render
  42436. * @param effect The effect we are binding the data to
  42437. */
  42438. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42439. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42440. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42441. effect.setColor3("vFogColor", scene.fogColor);
  42442. }
  42443. };
  42444. /**
  42445. * Binds the bones information from the mesh to the effect.
  42446. * @param mesh The mesh we are binding the information to render
  42447. * @param effect The effect we are binding the data to
  42448. */
  42449. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42450. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42451. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42452. if (matrices && effect) {
  42453. effect.setMatrices("mBones", matrices);
  42454. }
  42455. }
  42456. };
  42457. /**
  42458. * Binds the morph targets information from the mesh to the effect.
  42459. * @param abstractMesh The mesh we are binding the information to render
  42460. * @param effect The effect we are binding the data to
  42461. */
  42462. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42463. var manager = abstractMesh.morphTargetManager;
  42464. if (!abstractMesh || !manager) {
  42465. return;
  42466. }
  42467. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42468. };
  42469. /**
  42470. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42471. * @param defines The generated defines used in the effect
  42472. * @param effect The effect we are binding the data to
  42473. * @param scene The scene we are willing to render with logarithmic scale for
  42474. */
  42475. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42476. if (defines["LOGARITHMICDEPTH"]) {
  42477. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42478. }
  42479. };
  42480. /**
  42481. * Binds the clip plane information from the scene to the effect.
  42482. * @param scene The scene the clip plane information are extracted from
  42483. * @param effect The effect we are binding the data to
  42484. */
  42485. MaterialHelper.BindClipPlane = function (effect, scene) {
  42486. if (scene.clipPlane) {
  42487. var clipPlane = scene.clipPlane;
  42488. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42489. }
  42490. };
  42491. return MaterialHelper;
  42492. }());
  42493. BABYLON.MaterialHelper = MaterialHelper;
  42494. })(BABYLON || (BABYLON = {}));
  42495. //# sourceMappingURL=babylon.materialHelper.js.map
  42496. var BABYLON;
  42497. (function (BABYLON) {
  42498. var PushMaterial = /** @class */ (function (_super) {
  42499. __extends(PushMaterial, _super);
  42500. function PushMaterial(name, scene) {
  42501. var _this = _super.call(this, name, scene) || this;
  42502. _this._normalMatrix = new BABYLON.Matrix();
  42503. _this.storeEffectOnSubMeshes = true;
  42504. return _this;
  42505. }
  42506. PushMaterial.prototype.getEffect = function () {
  42507. return this._activeEffect;
  42508. };
  42509. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42510. if (!mesh) {
  42511. return false;
  42512. }
  42513. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42514. return true;
  42515. }
  42516. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42517. };
  42518. /**
  42519. * Binds the given world matrix to the active effect
  42520. *
  42521. * @param world the matrix to bind
  42522. */
  42523. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42524. this._activeEffect.setMatrix("world", world);
  42525. };
  42526. /**
  42527. * Binds the given normal matrix to the active effect
  42528. *
  42529. * @param normalMatrix the matrix to bind
  42530. */
  42531. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42532. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42533. };
  42534. PushMaterial.prototype.bind = function (world, mesh) {
  42535. if (!mesh) {
  42536. return;
  42537. }
  42538. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42539. };
  42540. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42541. if (effect === void 0) { effect = null; }
  42542. _super.prototype._afterBind.call(this, mesh);
  42543. this.getScene()._cachedEffect = effect;
  42544. };
  42545. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42546. if (visibility === void 0) { visibility = 1; }
  42547. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42548. };
  42549. return PushMaterial;
  42550. }(BABYLON.Material));
  42551. BABYLON.PushMaterial = PushMaterial;
  42552. })(BABYLON || (BABYLON = {}));
  42553. //# sourceMappingURL=babylon.pushMaterial.js.map
  42554. var BABYLON;
  42555. (function (BABYLON) {
  42556. /** @hidden */
  42557. var StandardMaterialDefines = /** @class */ (function (_super) {
  42558. __extends(StandardMaterialDefines, _super);
  42559. function StandardMaterialDefines() {
  42560. var _this = _super.call(this) || this;
  42561. _this.MAINUV1 = false;
  42562. _this.MAINUV2 = false;
  42563. _this.DIFFUSE = false;
  42564. _this.DIFFUSEDIRECTUV = 0;
  42565. _this.AMBIENT = false;
  42566. _this.AMBIENTDIRECTUV = 0;
  42567. _this.OPACITY = false;
  42568. _this.OPACITYDIRECTUV = 0;
  42569. _this.OPACITYRGB = false;
  42570. _this.REFLECTION = false;
  42571. _this.EMISSIVE = false;
  42572. _this.EMISSIVEDIRECTUV = 0;
  42573. _this.SPECULAR = false;
  42574. _this.SPECULARDIRECTUV = 0;
  42575. _this.BUMP = false;
  42576. _this.BUMPDIRECTUV = 0;
  42577. _this.PARALLAX = false;
  42578. _this.PARALLAXOCCLUSION = false;
  42579. _this.SPECULAROVERALPHA = false;
  42580. _this.CLIPPLANE = false;
  42581. _this.ALPHATEST = false;
  42582. _this.DEPTHPREPASS = false;
  42583. _this.ALPHAFROMDIFFUSE = false;
  42584. _this.POINTSIZE = false;
  42585. _this.FOG = false;
  42586. _this.SPECULARTERM = false;
  42587. _this.DIFFUSEFRESNEL = false;
  42588. _this.OPACITYFRESNEL = false;
  42589. _this.REFLECTIONFRESNEL = false;
  42590. _this.REFRACTIONFRESNEL = false;
  42591. _this.EMISSIVEFRESNEL = false;
  42592. _this.FRESNEL = false;
  42593. _this.NORMAL = false;
  42594. _this.UV1 = false;
  42595. _this.UV2 = false;
  42596. _this.VERTEXCOLOR = false;
  42597. _this.VERTEXALPHA = false;
  42598. _this.NUM_BONE_INFLUENCERS = 0;
  42599. _this.BonesPerMesh = 0;
  42600. _this.INSTANCES = false;
  42601. _this.GLOSSINESS = false;
  42602. _this.ROUGHNESS = false;
  42603. _this.EMISSIVEASILLUMINATION = false;
  42604. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42605. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42606. _this.LIGHTMAP = false;
  42607. _this.LIGHTMAPDIRECTUV = 0;
  42608. _this.OBJECTSPACE_NORMALMAP = false;
  42609. _this.USELIGHTMAPASSHADOWMAP = false;
  42610. _this.REFLECTIONMAP_3D = false;
  42611. _this.REFLECTIONMAP_SPHERICAL = false;
  42612. _this.REFLECTIONMAP_PLANAR = false;
  42613. _this.REFLECTIONMAP_CUBIC = false;
  42614. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42615. _this.REFLECTIONMAP_PROJECTION = false;
  42616. _this.REFLECTIONMAP_SKYBOX = false;
  42617. _this.REFLECTIONMAP_EXPLICIT = false;
  42618. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42619. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42620. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42621. _this.INVERTCUBICMAP = false;
  42622. _this.LOGARITHMICDEPTH = false;
  42623. _this.REFRACTION = false;
  42624. _this.REFRACTIONMAP_3D = false;
  42625. _this.REFLECTIONOVERALPHA = false;
  42626. _this.TWOSIDEDLIGHTING = false;
  42627. _this.SHADOWFLOAT = false;
  42628. _this.MORPHTARGETS = false;
  42629. _this.MORPHTARGETS_NORMAL = false;
  42630. _this.MORPHTARGETS_TANGENT = false;
  42631. _this.NUM_MORPH_INFLUENCERS = 0;
  42632. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42633. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42634. _this.IMAGEPROCESSING = false;
  42635. _this.VIGNETTE = false;
  42636. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42637. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42638. _this.TONEMAPPING = false;
  42639. _this.CONTRAST = false;
  42640. _this.COLORCURVES = false;
  42641. _this.COLORGRADING = false;
  42642. _this.COLORGRADING3D = false;
  42643. _this.SAMPLER3DGREENDEPTH = false;
  42644. _this.SAMPLER3DBGRMAP = false;
  42645. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42646. /**
  42647. * If the reflection texture on this material is in linear color space
  42648. * @hidden
  42649. */
  42650. _this.IS_REFLECTION_LINEAR = false;
  42651. /**
  42652. * If the refraction texture on this material is in linear color space
  42653. * @hidden
  42654. */
  42655. _this.IS_REFRACTION_LINEAR = false;
  42656. _this.EXPOSURE = false;
  42657. _this.rebuild();
  42658. return _this;
  42659. }
  42660. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42661. var modes = [
  42662. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42663. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42664. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42665. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42666. ];
  42667. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42668. var mode = modes_1[_i];
  42669. this[mode] = (mode === modeToEnable);
  42670. }
  42671. };
  42672. return StandardMaterialDefines;
  42673. }(BABYLON.MaterialDefines));
  42674. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42675. var StandardMaterial = /** @class */ (function (_super) {
  42676. __extends(StandardMaterial, _super);
  42677. function StandardMaterial(name, scene) {
  42678. var _this = _super.call(this, name, scene) || this;
  42679. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42680. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42681. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42682. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42683. _this.specularPower = 64;
  42684. _this._useAlphaFromDiffuseTexture = false;
  42685. _this._useEmissiveAsIllumination = false;
  42686. _this._linkEmissiveWithDiffuse = false;
  42687. _this._useSpecularOverAlpha = false;
  42688. _this._useReflectionOverAlpha = false;
  42689. _this._disableLighting = false;
  42690. _this._useObjectSpaceNormalMap = false;
  42691. _this._useParallax = false;
  42692. _this._useParallaxOcclusion = false;
  42693. _this.parallaxScaleBias = 0.05;
  42694. _this._roughness = 0;
  42695. _this.indexOfRefraction = 0.98;
  42696. _this.invertRefractionY = true;
  42697. /**
  42698. * Defines the alpha limits in alpha test mode
  42699. */
  42700. _this.alphaCutOff = 0.4;
  42701. _this._useLightmapAsShadowmap = false;
  42702. _this._useReflectionFresnelFromSpecular = false;
  42703. _this._useGlossinessFromSpecularMapAlpha = false;
  42704. _this._maxSimultaneousLights = 4;
  42705. /**
  42706. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42707. */
  42708. _this._invertNormalMapX = false;
  42709. /**
  42710. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42711. */
  42712. _this._invertNormalMapY = false;
  42713. /**
  42714. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42715. */
  42716. _this._twoSidedLighting = false;
  42717. _this._renderTargets = new BABYLON.SmartArray(16);
  42718. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42719. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42720. // Setup the default processing configuration to the scene.
  42721. _this._attachImageProcessingConfiguration(null);
  42722. _this.getRenderTargetTextures = function () {
  42723. _this._renderTargets.reset();
  42724. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42725. _this._renderTargets.push(_this._reflectionTexture);
  42726. }
  42727. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42728. _this._renderTargets.push(_this._refractionTexture);
  42729. }
  42730. return _this._renderTargets;
  42731. };
  42732. return _this;
  42733. }
  42734. ;
  42735. ;
  42736. ;
  42737. ;
  42738. ;
  42739. ;
  42740. ;
  42741. ;
  42742. ;
  42743. ;
  42744. ;
  42745. ;
  42746. ;
  42747. ;
  42748. ;
  42749. ;
  42750. ;
  42751. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42752. /**
  42753. * Gets the image processing configuration used either in this material.
  42754. */
  42755. get: function () {
  42756. return this._imageProcessingConfiguration;
  42757. },
  42758. /**
  42759. * Sets the Default image processing configuration used either in the this material.
  42760. *
  42761. * If sets to null, the scene one is in use.
  42762. */
  42763. set: function (value) {
  42764. this._attachImageProcessingConfiguration(value);
  42765. // Ensure the effect will be rebuilt.
  42766. this._markAllSubMeshesAsTexturesDirty();
  42767. },
  42768. enumerable: true,
  42769. configurable: true
  42770. });
  42771. /**
  42772. * Attaches a new image processing configuration to the Standard Material.
  42773. * @param configuration
  42774. */
  42775. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42776. var _this = this;
  42777. if (configuration === this._imageProcessingConfiguration) {
  42778. return;
  42779. }
  42780. // Detaches observer.
  42781. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42782. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42783. }
  42784. // Pick the scene configuration if needed.
  42785. if (!configuration) {
  42786. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42787. }
  42788. else {
  42789. this._imageProcessingConfiguration = configuration;
  42790. }
  42791. // Attaches observer.
  42792. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42793. _this._markAllSubMeshesAsImageProcessingDirty();
  42794. });
  42795. };
  42796. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42797. /**
  42798. * Gets wether the color curves effect is enabled.
  42799. */
  42800. get: function () {
  42801. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42802. },
  42803. /**
  42804. * Sets wether the color curves effect is enabled.
  42805. */
  42806. set: function (value) {
  42807. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42808. },
  42809. enumerable: true,
  42810. configurable: true
  42811. });
  42812. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42813. /**
  42814. * Gets wether the color grading effect is enabled.
  42815. */
  42816. get: function () {
  42817. return this.imageProcessingConfiguration.colorGradingEnabled;
  42818. },
  42819. /**
  42820. * Gets wether the color grading effect is enabled.
  42821. */
  42822. set: function (value) {
  42823. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42824. },
  42825. enumerable: true,
  42826. configurable: true
  42827. });
  42828. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42829. /**
  42830. * Gets wether tonemapping is enabled or not.
  42831. */
  42832. get: function () {
  42833. return this._imageProcessingConfiguration.toneMappingEnabled;
  42834. },
  42835. /**
  42836. * Sets wether tonemapping is enabled or not
  42837. */
  42838. set: function (value) {
  42839. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42840. },
  42841. enumerable: true,
  42842. configurable: true
  42843. });
  42844. ;
  42845. ;
  42846. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42847. /**
  42848. * The camera exposure used on this material.
  42849. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42850. * This corresponds to a photographic exposure.
  42851. */
  42852. get: function () {
  42853. return this._imageProcessingConfiguration.exposure;
  42854. },
  42855. /**
  42856. * The camera exposure used on this material.
  42857. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42858. * This corresponds to a photographic exposure.
  42859. */
  42860. set: function (value) {
  42861. this._imageProcessingConfiguration.exposure = value;
  42862. },
  42863. enumerable: true,
  42864. configurable: true
  42865. });
  42866. ;
  42867. ;
  42868. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42869. /**
  42870. * Gets The camera contrast used on this material.
  42871. */
  42872. get: function () {
  42873. return this._imageProcessingConfiguration.contrast;
  42874. },
  42875. /**
  42876. * Sets The camera contrast used on this material.
  42877. */
  42878. set: function (value) {
  42879. this._imageProcessingConfiguration.contrast = value;
  42880. },
  42881. enumerable: true,
  42882. configurable: true
  42883. });
  42884. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42885. /**
  42886. * Gets the Color Grading 2D Lookup Texture.
  42887. */
  42888. get: function () {
  42889. return this._imageProcessingConfiguration.colorGradingTexture;
  42890. },
  42891. /**
  42892. * Sets the Color Grading 2D Lookup Texture.
  42893. */
  42894. set: function (value) {
  42895. this._imageProcessingConfiguration.colorGradingTexture = value;
  42896. },
  42897. enumerable: true,
  42898. configurable: true
  42899. });
  42900. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42901. /**
  42902. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42903. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42904. * 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;
  42905. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42906. */
  42907. get: function () {
  42908. return this._imageProcessingConfiguration.colorCurves;
  42909. },
  42910. /**
  42911. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42912. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42913. * 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;
  42914. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42915. */
  42916. set: function (value) {
  42917. this._imageProcessingConfiguration.colorCurves = value;
  42918. },
  42919. enumerable: true,
  42920. configurable: true
  42921. });
  42922. StandardMaterial.prototype.getClassName = function () {
  42923. return "StandardMaterial";
  42924. };
  42925. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42926. get: function () {
  42927. return this._useLogarithmicDepth;
  42928. },
  42929. set: function (value) {
  42930. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42931. this._markAllSubMeshesAsMiscDirty();
  42932. },
  42933. enumerable: true,
  42934. configurable: true
  42935. });
  42936. StandardMaterial.prototype.needAlphaBlending = function () {
  42937. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42938. };
  42939. StandardMaterial.prototype.needAlphaTesting = function () {
  42940. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42941. };
  42942. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42943. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42944. };
  42945. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42946. return this._diffuseTexture;
  42947. };
  42948. /**
  42949. * Child classes can use it to update shaders
  42950. */
  42951. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42952. if (useInstances === void 0) { useInstances = false; }
  42953. if (subMesh.effect && this.isFrozen) {
  42954. if (this._wasPreviouslyReady && subMesh.effect) {
  42955. return true;
  42956. }
  42957. }
  42958. if (!subMesh._materialDefines) {
  42959. subMesh._materialDefines = new StandardMaterialDefines();
  42960. }
  42961. var scene = this.getScene();
  42962. var defines = subMesh._materialDefines;
  42963. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42964. if (defines._renderId === scene.getRenderId()) {
  42965. return true;
  42966. }
  42967. }
  42968. var engine = scene.getEngine();
  42969. // Lights
  42970. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42971. // Textures
  42972. if (defines._areTexturesDirty) {
  42973. defines._needUVs = false;
  42974. defines.MAINUV1 = false;
  42975. defines.MAINUV2 = false;
  42976. if (scene.texturesEnabled) {
  42977. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42978. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42979. return false;
  42980. }
  42981. else {
  42982. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42983. }
  42984. }
  42985. else {
  42986. defines.DIFFUSE = false;
  42987. }
  42988. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42989. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42990. return false;
  42991. }
  42992. else {
  42993. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42994. }
  42995. }
  42996. else {
  42997. defines.AMBIENT = false;
  42998. }
  42999. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43000. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43001. return false;
  43002. }
  43003. else {
  43004. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43005. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43006. }
  43007. }
  43008. else {
  43009. defines.OPACITY = false;
  43010. }
  43011. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43012. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43013. return false;
  43014. }
  43015. else {
  43016. defines._needNormals = true;
  43017. defines.REFLECTION = true;
  43018. defines.ROUGHNESS = (this._roughness > 0);
  43019. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43020. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43021. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43022. switch (this._reflectionTexture.coordinatesMode) {
  43023. case BABYLON.Texture.EXPLICIT_MODE:
  43024. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43025. break;
  43026. case BABYLON.Texture.PLANAR_MODE:
  43027. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43028. break;
  43029. case BABYLON.Texture.PROJECTION_MODE:
  43030. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43031. break;
  43032. case BABYLON.Texture.SKYBOX_MODE:
  43033. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43034. break;
  43035. case BABYLON.Texture.SPHERICAL_MODE:
  43036. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43037. break;
  43038. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43039. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43040. break;
  43041. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43042. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43043. break;
  43044. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43045. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43046. break;
  43047. case BABYLON.Texture.CUBIC_MODE:
  43048. case BABYLON.Texture.INVCUBIC_MODE:
  43049. default:
  43050. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43051. break;
  43052. }
  43053. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43054. }
  43055. }
  43056. else {
  43057. defines.REFLECTION = false;
  43058. }
  43059. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43060. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43061. return false;
  43062. }
  43063. else {
  43064. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43065. }
  43066. }
  43067. else {
  43068. defines.EMISSIVE = false;
  43069. }
  43070. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43071. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43072. return false;
  43073. }
  43074. else {
  43075. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43076. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43077. }
  43078. }
  43079. else {
  43080. defines.LIGHTMAP = false;
  43081. }
  43082. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43083. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43084. return false;
  43085. }
  43086. else {
  43087. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43088. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43089. }
  43090. }
  43091. else {
  43092. defines.SPECULAR = false;
  43093. }
  43094. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43095. // Bump texure can not be not blocking.
  43096. if (!this._bumpTexture.isReady()) {
  43097. return false;
  43098. }
  43099. else {
  43100. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43101. defines.PARALLAX = this._useParallax;
  43102. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43103. }
  43104. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43105. }
  43106. else {
  43107. defines.BUMP = false;
  43108. }
  43109. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43110. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43111. return false;
  43112. }
  43113. else {
  43114. defines._needUVs = true;
  43115. defines.REFRACTION = true;
  43116. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43117. }
  43118. }
  43119. else {
  43120. defines.REFRACTION = false;
  43121. }
  43122. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43123. }
  43124. else {
  43125. defines.DIFFUSE = false;
  43126. defines.AMBIENT = false;
  43127. defines.OPACITY = false;
  43128. defines.REFLECTION = false;
  43129. defines.EMISSIVE = false;
  43130. defines.LIGHTMAP = false;
  43131. defines.BUMP = false;
  43132. defines.REFRACTION = false;
  43133. }
  43134. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43135. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43136. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43137. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43138. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43139. }
  43140. if (defines._areImageProcessingDirty) {
  43141. if (!this._imageProcessingConfiguration.isReady()) {
  43142. return false;
  43143. }
  43144. this._imageProcessingConfiguration.prepareDefines(defines);
  43145. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43146. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43147. }
  43148. if (defines._areFresnelDirty) {
  43149. if (StandardMaterial.FresnelEnabled) {
  43150. // Fresnel
  43151. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43152. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43153. this._reflectionFresnelParameters) {
  43154. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43155. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43156. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43157. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43158. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43159. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43160. defines._needNormals = true;
  43161. defines.FRESNEL = true;
  43162. }
  43163. }
  43164. else {
  43165. defines.FRESNEL = false;
  43166. }
  43167. }
  43168. // Misc.
  43169. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43170. // Attribs
  43171. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43172. // Values that need to be evaluated on every frame
  43173. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43174. // Get correct effect
  43175. if (defines.isDirty) {
  43176. defines.markAsProcessed();
  43177. scene.resetCachedMaterial();
  43178. // Fallbacks
  43179. var fallbacks = new BABYLON.EffectFallbacks();
  43180. if (defines.REFLECTION) {
  43181. fallbacks.addFallback(0, "REFLECTION");
  43182. }
  43183. if (defines.SPECULAR) {
  43184. fallbacks.addFallback(0, "SPECULAR");
  43185. }
  43186. if (defines.BUMP) {
  43187. fallbacks.addFallback(0, "BUMP");
  43188. }
  43189. if (defines.PARALLAX) {
  43190. fallbacks.addFallback(1, "PARALLAX");
  43191. }
  43192. if (defines.PARALLAXOCCLUSION) {
  43193. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43194. }
  43195. if (defines.SPECULAROVERALPHA) {
  43196. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43197. }
  43198. if (defines.FOG) {
  43199. fallbacks.addFallback(1, "FOG");
  43200. }
  43201. if (defines.POINTSIZE) {
  43202. fallbacks.addFallback(0, "POINTSIZE");
  43203. }
  43204. if (defines.LOGARITHMICDEPTH) {
  43205. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43206. }
  43207. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43208. if (defines.SPECULARTERM) {
  43209. fallbacks.addFallback(0, "SPECULARTERM");
  43210. }
  43211. if (defines.DIFFUSEFRESNEL) {
  43212. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43213. }
  43214. if (defines.OPACITYFRESNEL) {
  43215. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43216. }
  43217. if (defines.REFLECTIONFRESNEL) {
  43218. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43219. }
  43220. if (defines.EMISSIVEFRESNEL) {
  43221. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43222. }
  43223. if (defines.FRESNEL) {
  43224. fallbacks.addFallback(4, "FRESNEL");
  43225. }
  43226. //Attributes
  43227. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43228. if (defines.NORMAL) {
  43229. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43230. }
  43231. if (defines.UV1) {
  43232. attribs.push(BABYLON.VertexBuffer.UVKind);
  43233. }
  43234. if (defines.UV2) {
  43235. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43236. }
  43237. if (defines.VERTEXCOLOR) {
  43238. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43239. }
  43240. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43241. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43242. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43243. var shaderName = "default";
  43244. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43245. "vFogInfos", "vFogColor", "pointSize",
  43246. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43247. "mBones",
  43248. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43249. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43250. "vReflectionPosition", "vReflectionSize",
  43251. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43252. ];
  43253. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43254. var uniformBuffers = ["Material", "Scene"];
  43255. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43256. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43257. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43258. uniformsNames: uniforms,
  43259. uniformBuffersNames: uniformBuffers,
  43260. samplers: samplers,
  43261. defines: defines,
  43262. maxSimultaneousLights: this._maxSimultaneousLights
  43263. });
  43264. if (this.customShaderNameResolve) {
  43265. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43266. }
  43267. var join = defines.toString();
  43268. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43269. attributes: attribs,
  43270. uniformsNames: uniforms,
  43271. uniformBuffersNames: uniformBuffers,
  43272. samplers: samplers,
  43273. defines: join,
  43274. fallbacks: fallbacks,
  43275. onCompiled: this.onCompiled,
  43276. onError: this.onError,
  43277. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43278. }, engine), defines);
  43279. this.buildUniformLayout();
  43280. }
  43281. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43282. return false;
  43283. }
  43284. defines._renderId = scene.getRenderId();
  43285. this._wasPreviouslyReady = true;
  43286. return true;
  43287. };
  43288. StandardMaterial.prototype.buildUniformLayout = function () {
  43289. // Order is important !
  43290. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43291. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43292. this._uniformBuffer.addUniform("opacityParts", 4);
  43293. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43294. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43295. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43296. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43297. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43298. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43299. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43300. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43301. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43302. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43303. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43304. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43305. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43306. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43307. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43308. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43309. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43310. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43311. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43312. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43313. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43314. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43315. this._uniformBuffer.addUniform("specularMatrix", 16);
  43316. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43317. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43318. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43319. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43320. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43321. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43322. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43323. this._uniformBuffer.addUniform("pointSize", 1);
  43324. this._uniformBuffer.create();
  43325. };
  43326. StandardMaterial.prototype.unbind = function () {
  43327. if (this._activeEffect) {
  43328. var needFlag = false;
  43329. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43330. this._activeEffect.setTexture("reflection2DSampler", null);
  43331. needFlag = true;
  43332. }
  43333. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43334. this._activeEffect.setTexture("refraction2DSampler", null);
  43335. needFlag = true;
  43336. }
  43337. if (needFlag) {
  43338. this._markAllSubMeshesAsTexturesDirty();
  43339. }
  43340. }
  43341. _super.prototype.unbind.call(this);
  43342. };
  43343. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43344. var scene = this.getScene();
  43345. var defines = subMesh._materialDefines;
  43346. if (!defines) {
  43347. return;
  43348. }
  43349. var effect = subMesh.effect;
  43350. if (!effect) {
  43351. return;
  43352. }
  43353. this._activeEffect = effect;
  43354. // Matrices
  43355. this.bindOnlyWorldMatrix(world);
  43356. // Normal Matrix
  43357. if (defines.OBJECTSPACE_NORMALMAP) {
  43358. world.toNormalMatrix(this._normalMatrix);
  43359. this.bindOnlyNormalMatrix(this._normalMatrix);
  43360. }
  43361. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43362. // Bones
  43363. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43364. if (mustRebind) {
  43365. this._uniformBuffer.bindToEffect(effect, "Material");
  43366. this.bindViewProjection(effect);
  43367. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43368. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43369. // Fresnel
  43370. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43371. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43372. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43373. }
  43374. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43375. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43376. }
  43377. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43378. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43379. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43380. }
  43381. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43382. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43383. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43384. }
  43385. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43386. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43387. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43388. }
  43389. }
  43390. // Textures
  43391. if (scene.texturesEnabled) {
  43392. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43393. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43394. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43395. if (this._diffuseTexture.hasAlpha) {
  43396. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43397. }
  43398. }
  43399. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43400. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43401. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43402. }
  43403. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43404. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43405. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43406. }
  43407. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43408. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43409. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43410. if (this._reflectionTexture.boundingBoxSize) {
  43411. var cubeTexture = this._reflectionTexture;
  43412. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43413. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43414. }
  43415. }
  43416. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43417. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43418. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43419. }
  43420. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43421. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43422. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43423. }
  43424. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43425. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43426. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43427. }
  43428. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43429. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43430. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43431. if (scene._mirroredCameraPosition) {
  43432. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43433. }
  43434. else {
  43435. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43436. }
  43437. }
  43438. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43439. var depth = 1.0;
  43440. if (!this._refractionTexture.isCube) {
  43441. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43442. if (this._refractionTexture.depth) {
  43443. depth = this._refractionTexture.depth;
  43444. }
  43445. }
  43446. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43447. }
  43448. }
  43449. // Point size
  43450. if (this.pointsCloud) {
  43451. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43452. }
  43453. if (defines.SPECULARTERM) {
  43454. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43455. }
  43456. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43457. // Diffuse
  43458. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43459. }
  43460. // Textures
  43461. if (scene.texturesEnabled) {
  43462. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43463. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43464. }
  43465. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43466. effect.setTexture("ambientSampler", this._ambientTexture);
  43467. }
  43468. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43469. effect.setTexture("opacitySampler", this._opacityTexture);
  43470. }
  43471. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43472. if (this._reflectionTexture.isCube) {
  43473. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43474. }
  43475. else {
  43476. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43477. }
  43478. }
  43479. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43480. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43481. }
  43482. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43483. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43484. }
  43485. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43486. effect.setTexture("specularSampler", this._specularTexture);
  43487. }
  43488. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43489. effect.setTexture("bumpSampler", this._bumpTexture);
  43490. }
  43491. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43492. var depth = 1.0;
  43493. if (this._refractionTexture.isCube) {
  43494. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43495. }
  43496. else {
  43497. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43498. }
  43499. }
  43500. }
  43501. // Clip plane
  43502. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43503. // Colors
  43504. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43505. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43506. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43507. }
  43508. if (mustRebind || !this.isFrozen) {
  43509. // Lights
  43510. if (scene.lightsEnabled && !this._disableLighting) {
  43511. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43512. }
  43513. // View
  43514. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43515. this.bindView(effect);
  43516. }
  43517. // Fog
  43518. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43519. // Morph targets
  43520. if (defines.NUM_MORPH_INFLUENCERS) {
  43521. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43522. }
  43523. // Log. depth
  43524. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43525. // image processing
  43526. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43527. this._imageProcessingConfiguration.bind(this._activeEffect);
  43528. }
  43529. }
  43530. this._uniformBuffer.update();
  43531. this._afterBind(mesh, this._activeEffect);
  43532. };
  43533. StandardMaterial.prototype.getAnimatables = function () {
  43534. var results = [];
  43535. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43536. results.push(this._diffuseTexture);
  43537. }
  43538. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43539. results.push(this._ambientTexture);
  43540. }
  43541. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43542. results.push(this._opacityTexture);
  43543. }
  43544. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43545. results.push(this._reflectionTexture);
  43546. }
  43547. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43548. results.push(this._emissiveTexture);
  43549. }
  43550. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43551. results.push(this._specularTexture);
  43552. }
  43553. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43554. results.push(this._bumpTexture);
  43555. }
  43556. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43557. results.push(this._lightmapTexture);
  43558. }
  43559. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43560. results.push(this._refractionTexture);
  43561. }
  43562. return results;
  43563. };
  43564. StandardMaterial.prototype.getActiveTextures = function () {
  43565. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43566. if (this._diffuseTexture) {
  43567. activeTextures.push(this._diffuseTexture);
  43568. }
  43569. if (this._ambientTexture) {
  43570. activeTextures.push(this._ambientTexture);
  43571. }
  43572. if (this._opacityTexture) {
  43573. activeTextures.push(this._opacityTexture);
  43574. }
  43575. if (this._reflectionTexture) {
  43576. activeTextures.push(this._reflectionTexture);
  43577. }
  43578. if (this._emissiveTexture) {
  43579. activeTextures.push(this._emissiveTexture);
  43580. }
  43581. if (this._specularTexture) {
  43582. activeTextures.push(this._specularTexture);
  43583. }
  43584. if (this._bumpTexture) {
  43585. activeTextures.push(this._bumpTexture);
  43586. }
  43587. if (this._lightmapTexture) {
  43588. activeTextures.push(this._lightmapTexture);
  43589. }
  43590. if (this._refractionTexture) {
  43591. activeTextures.push(this._refractionTexture);
  43592. }
  43593. return activeTextures;
  43594. };
  43595. StandardMaterial.prototype.hasTexture = function (texture) {
  43596. if (_super.prototype.hasTexture.call(this, texture)) {
  43597. return true;
  43598. }
  43599. if (this._diffuseTexture === texture) {
  43600. return true;
  43601. }
  43602. if (this._ambientTexture === texture) {
  43603. return true;
  43604. }
  43605. if (this._opacityTexture === texture) {
  43606. return true;
  43607. }
  43608. if (this._reflectionTexture === texture) {
  43609. return true;
  43610. }
  43611. if (this._emissiveTexture === texture) {
  43612. return true;
  43613. }
  43614. if (this._specularTexture === texture) {
  43615. return true;
  43616. }
  43617. if (this._bumpTexture === texture) {
  43618. return true;
  43619. }
  43620. if (this._lightmapTexture === texture) {
  43621. return true;
  43622. }
  43623. if (this._refractionTexture === texture) {
  43624. return true;
  43625. }
  43626. return false;
  43627. };
  43628. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43629. if (forceDisposeTextures) {
  43630. if (this._diffuseTexture) {
  43631. this._diffuseTexture.dispose();
  43632. }
  43633. if (this._ambientTexture) {
  43634. this._ambientTexture.dispose();
  43635. }
  43636. if (this._opacityTexture) {
  43637. this._opacityTexture.dispose();
  43638. }
  43639. if (this._reflectionTexture) {
  43640. this._reflectionTexture.dispose();
  43641. }
  43642. if (this._emissiveTexture) {
  43643. this._emissiveTexture.dispose();
  43644. }
  43645. if (this._specularTexture) {
  43646. this._specularTexture.dispose();
  43647. }
  43648. if (this._bumpTexture) {
  43649. this._bumpTexture.dispose();
  43650. }
  43651. if (this._lightmapTexture) {
  43652. this._lightmapTexture.dispose();
  43653. }
  43654. if (this._refractionTexture) {
  43655. this._refractionTexture.dispose();
  43656. }
  43657. }
  43658. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43659. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43660. }
  43661. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43662. };
  43663. StandardMaterial.prototype.clone = function (name) {
  43664. var _this = this;
  43665. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43666. result.name = name;
  43667. result.id = name;
  43668. return result;
  43669. };
  43670. StandardMaterial.prototype.serialize = function () {
  43671. return BABYLON.SerializationHelper.Serialize(this);
  43672. };
  43673. // Statics
  43674. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43675. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43676. };
  43677. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43678. get: function () {
  43679. return StandardMaterial._DiffuseTextureEnabled;
  43680. },
  43681. set: function (value) {
  43682. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43683. return;
  43684. }
  43685. StandardMaterial._DiffuseTextureEnabled = value;
  43686. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43687. },
  43688. enumerable: true,
  43689. configurable: true
  43690. });
  43691. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43692. get: function () {
  43693. return StandardMaterial._AmbientTextureEnabled;
  43694. },
  43695. set: function (value) {
  43696. if (StandardMaterial._AmbientTextureEnabled === value) {
  43697. return;
  43698. }
  43699. StandardMaterial._AmbientTextureEnabled = value;
  43700. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43701. },
  43702. enumerable: true,
  43703. configurable: true
  43704. });
  43705. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43706. get: function () {
  43707. return StandardMaterial._OpacityTextureEnabled;
  43708. },
  43709. set: function (value) {
  43710. if (StandardMaterial._OpacityTextureEnabled === value) {
  43711. return;
  43712. }
  43713. StandardMaterial._OpacityTextureEnabled = value;
  43714. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43715. },
  43716. enumerable: true,
  43717. configurable: true
  43718. });
  43719. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43720. get: function () {
  43721. return StandardMaterial._ReflectionTextureEnabled;
  43722. },
  43723. set: function (value) {
  43724. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43725. return;
  43726. }
  43727. StandardMaterial._ReflectionTextureEnabled = value;
  43728. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43729. },
  43730. enumerable: true,
  43731. configurable: true
  43732. });
  43733. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43734. get: function () {
  43735. return StandardMaterial._EmissiveTextureEnabled;
  43736. },
  43737. set: function (value) {
  43738. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43739. return;
  43740. }
  43741. StandardMaterial._EmissiveTextureEnabled = value;
  43742. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43743. },
  43744. enumerable: true,
  43745. configurable: true
  43746. });
  43747. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43748. get: function () {
  43749. return StandardMaterial._SpecularTextureEnabled;
  43750. },
  43751. set: function (value) {
  43752. if (StandardMaterial._SpecularTextureEnabled === value) {
  43753. return;
  43754. }
  43755. StandardMaterial._SpecularTextureEnabled = value;
  43756. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43757. },
  43758. enumerable: true,
  43759. configurable: true
  43760. });
  43761. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43762. get: function () {
  43763. return StandardMaterial._BumpTextureEnabled;
  43764. },
  43765. set: function (value) {
  43766. if (StandardMaterial._BumpTextureEnabled === value) {
  43767. return;
  43768. }
  43769. StandardMaterial._BumpTextureEnabled = value;
  43770. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43771. },
  43772. enumerable: true,
  43773. configurable: true
  43774. });
  43775. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43776. get: function () {
  43777. return StandardMaterial._LightmapTextureEnabled;
  43778. },
  43779. set: function (value) {
  43780. if (StandardMaterial._LightmapTextureEnabled === value) {
  43781. return;
  43782. }
  43783. StandardMaterial._LightmapTextureEnabled = value;
  43784. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43785. },
  43786. enumerable: true,
  43787. configurable: true
  43788. });
  43789. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43790. get: function () {
  43791. return StandardMaterial._RefractionTextureEnabled;
  43792. },
  43793. set: function (value) {
  43794. if (StandardMaterial._RefractionTextureEnabled === value) {
  43795. return;
  43796. }
  43797. StandardMaterial._RefractionTextureEnabled = value;
  43798. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43799. },
  43800. enumerable: true,
  43801. configurable: true
  43802. });
  43803. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43804. get: function () {
  43805. return StandardMaterial._ColorGradingTextureEnabled;
  43806. },
  43807. set: function (value) {
  43808. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43809. return;
  43810. }
  43811. StandardMaterial._ColorGradingTextureEnabled = value;
  43812. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43813. },
  43814. enumerable: true,
  43815. configurable: true
  43816. });
  43817. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43818. get: function () {
  43819. return StandardMaterial._FresnelEnabled;
  43820. },
  43821. set: function (value) {
  43822. if (StandardMaterial._FresnelEnabled === value) {
  43823. return;
  43824. }
  43825. StandardMaterial._FresnelEnabled = value;
  43826. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43827. },
  43828. enumerable: true,
  43829. configurable: true
  43830. });
  43831. // Flags used to enable or disable a type of texture for all Standard Materials
  43832. StandardMaterial._DiffuseTextureEnabled = true;
  43833. StandardMaterial._AmbientTextureEnabled = true;
  43834. StandardMaterial._OpacityTextureEnabled = true;
  43835. StandardMaterial._ReflectionTextureEnabled = true;
  43836. StandardMaterial._EmissiveTextureEnabled = true;
  43837. StandardMaterial._SpecularTextureEnabled = true;
  43838. StandardMaterial._BumpTextureEnabled = true;
  43839. StandardMaterial._LightmapTextureEnabled = true;
  43840. StandardMaterial._RefractionTextureEnabled = true;
  43841. StandardMaterial._ColorGradingTextureEnabled = true;
  43842. StandardMaterial._FresnelEnabled = true;
  43843. __decorate([
  43844. BABYLON.serializeAsTexture("diffuseTexture")
  43845. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43846. __decorate([
  43847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43848. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43849. __decorate([
  43850. BABYLON.serializeAsTexture("ambientTexture")
  43851. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43852. __decorate([
  43853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43854. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43855. __decorate([
  43856. BABYLON.serializeAsTexture("opacityTexture")
  43857. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43858. __decorate([
  43859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43860. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43861. __decorate([
  43862. BABYLON.serializeAsTexture("reflectionTexture")
  43863. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43864. __decorate([
  43865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43866. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43867. __decorate([
  43868. BABYLON.serializeAsTexture("emissiveTexture")
  43869. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43870. __decorate([
  43871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43872. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43873. __decorate([
  43874. BABYLON.serializeAsTexture("specularTexture")
  43875. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43876. __decorate([
  43877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43878. ], StandardMaterial.prototype, "specularTexture", void 0);
  43879. __decorate([
  43880. BABYLON.serializeAsTexture("bumpTexture")
  43881. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43882. __decorate([
  43883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43884. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43885. __decorate([
  43886. BABYLON.serializeAsTexture("lightmapTexture")
  43887. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43888. __decorate([
  43889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43890. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43891. __decorate([
  43892. BABYLON.serializeAsTexture("refractionTexture")
  43893. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43894. __decorate([
  43895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43896. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43897. __decorate([
  43898. BABYLON.serializeAsColor3("ambient")
  43899. ], StandardMaterial.prototype, "ambientColor", void 0);
  43900. __decorate([
  43901. BABYLON.serializeAsColor3("diffuse")
  43902. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43903. __decorate([
  43904. BABYLON.serializeAsColor3("specular")
  43905. ], StandardMaterial.prototype, "specularColor", void 0);
  43906. __decorate([
  43907. BABYLON.serializeAsColor3("emissive")
  43908. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43909. __decorate([
  43910. BABYLON.serialize()
  43911. ], StandardMaterial.prototype, "specularPower", void 0);
  43912. __decorate([
  43913. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43914. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43915. __decorate([
  43916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43917. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43918. __decorate([
  43919. BABYLON.serialize("useEmissiveAsIllumination")
  43920. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43921. __decorate([
  43922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43923. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43924. __decorate([
  43925. BABYLON.serialize("linkEmissiveWithDiffuse")
  43926. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43927. __decorate([
  43928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43929. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43930. __decorate([
  43931. BABYLON.serialize("useSpecularOverAlpha")
  43932. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43933. __decorate([
  43934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43935. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43936. __decorate([
  43937. BABYLON.serialize("useReflectionOverAlpha")
  43938. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43939. __decorate([
  43940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43941. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43942. __decorate([
  43943. BABYLON.serialize("disableLighting")
  43944. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43945. __decorate([
  43946. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43947. ], StandardMaterial.prototype, "disableLighting", void 0);
  43948. __decorate([
  43949. BABYLON.serialize("useObjectSpaceNormalMap")
  43950. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43951. __decorate([
  43952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43953. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43954. __decorate([
  43955. BABYLON.serialize("useParallax")
  43956. ], StandardMaterial.prototype, "_useParallax", void 0);
  43957. __decorate([
  43958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43959. ], StandardMaterial.prototype, "useParallax", void 0);
  43960. __decorate([
  43961. BABYLON.serialize("useParallaxOcclusion")
  43962. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43963. __decorate([
  43964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43965. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43966. __decorate([
  43967. BABYLON.serialize()
  43968. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43969. __decorate([
  43970. BABYLON.serialize("roughness")
  43971. ], StandardMaterial.prototype, "_roughness", void 0);
  43972. __decorate([
  43973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43974. ], StandardMaterial.prototype, "roughness", void 0);
  43975. __decorate([
  43976. BABYLON.serialize()
  43977. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43978. __decorate([
  43979. BABYLON.serialize()
  43980. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43981. __decorate([
  43982. BABYLON.serialize()
  43983. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43984. __decorate([
  43985. BABYLON.serialize("useLightmapAsShadowmap")
  43986. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43987. __decorate([
  43988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43989. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43990. __decorate([
  43991. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43992. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43993. __decorate([
  43994. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43995. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43996. __decorate([
  43997. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43998. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43999. __decorate([
  44000. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44001. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44002. __decorate([
  44003. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44004. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44005. __decorate([
  44006. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44007. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44008. __decorate([
  44009. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44010. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44011. __decorate([
  44012. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44013. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44014. __decorate([
  44015. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44016. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44017. __decorate([
  44018. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44019. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44020. __decorate([
  44021. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44022. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44023. __decorate([
  44024. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44025. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44026. __decorate([
  44027. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44028. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44029. __decorate([
  44030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44031. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44032. __decorate([
  44033. BABYLON.serialize("maxSimultaneousLights")
  44034. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44035. __decorate([
  44036. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44037. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44038. __decorate([
  44039. BABYLON.serialize("invertNormalMapX")
  44040. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44041. __decorate([
  44042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44043. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44044. __decorate([
  44045. BABYLON.serialize("invertNormalMapY")
  44046. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44047. __decorate([
  44048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44049. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44050. __decorate([
  44051. BABYLON.serialize("twoSidedLighting")
  44052. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44053. __decorate([
  44054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44055. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44056. __decorate([
  44057. BABYLON.serialize()
  44058. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44059. return StandardMaterial;
  44060. }(BABYLON.PushMaterial));
  44061. BABYLON.StandardMaterial = StandardMaterial;
  44062. })(BABYLON || (BABYLON = {}));
  44063. //# sourceMappingURL=babylon.standardMaterial.js.map
  44064. var BABYLON;
  44065. (function (BABYLON) {
  44066. /**
  44067. * Manages the defines for the PBR Material.
  44068. * @hiddenChildren
  44069. */
  44070. var PBRMaterialDefines = /** @class */ (function (_super) {
  44071. __extends(PBRMaterialDefines, _super);
  44072. /**
  44073. * Initializes the PBR Material defines.
  44074. */
  44075. function PBRMaterialDefines() {
  44076. var _this = _super.call(this) || this;
  44077. _this.PBR = true;
  44078. _this.MAINUV1 = false;
  44079. _this.MAINUV2 = false;
  44080. _this.UV1 = false;
  44081. _this.UV2 = false;
  44082. _this.ALBEDO = false;
  44083. _this.ALBEDODIRECTUV = 0;
  44084. _this.VERTEXCOLOR = false;
  44085. _this.AMBIENT = false;
  44086. _this.AMBIENTDIRECTUV = 0;
  44087. _this.AMBIENTINGRAYSCALE = false;
  44088. _this.OPACITY = false;
  44089. _this.VERTEXALPHA = false;
  44090. _this.OPACITYDIRECTUV = 0;
  44091. _this.OPACITYRGB = false;
  44092. _this.ALPHATEST = false;
  44093. _this.DEPTHPREPASS = false;
  44094. _this.ALPHABLEND = false;
  44095. _this.ALPHAFROMALBEDO = false;
  44096. _this.ALPHATESTVALUE = "0.5";
  44097. _this.SPECULAROVERALPHA = false;
  44098. _this.RADIANCEOVERALPHA = false;
  44099. _this.ALPHAFRESNEL = false;
  44100. _this.LINEARALPHAFRESNEL = false;
  44101. _this.PREMULTIPLYALPHA = false;
  44102. _this.EMISSIVE = false;
  44103. _this.EMISSIVEDIRECTUV = 0;
  44104. _this.REFLECTIVITY = false;
  44105. _this.REFLECTIVITYDIRECTUV = 0;
  44106. _this.SPECULARTERM = false;
  44107. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44108. _this.MICROSURFACEAUTOMATIC = false;
  44109. _this.LODBASEDMICROSFURACE = false;
  44110. _this.MICROSURFACEMAP = false;
  44111. _this.MICROSURFACEMAPDIRECTUV = 0;
  44112. _this.METALLICWORKFLOW = false;
  44113. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44114. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44115. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44116. _this.AOSTOREINMETALMAPRED = false;
  44117. _this.ENVIRONMENTBRDF = false;
  44118. _this.NORMAL = false;
  44119. _this.TANGENT = false;
  44120. _this.BUMP = false;
  44121. _this.BUMPDIRECTUV = 0;
  44122. _this.OBJECTSPACE_NORMALMAP = false;
  44123. _this.PARALLAX = false;
  44124. _this.PARALLAXOCCLUSION = false;
  44125. _this.NORMALXYSCALE = true;
  44126. _this.LIGHTMAP = false;
  44127. _this.LIGHTMAPDIRECTUV = 0;
  44128. _this.USELIGHTMAPASSHADOWMAP = false;
  44129. _this.GAMMALIGHTMAP = false;
  44130. _this.REFLECTION = false;
  44131. _this.REFLECTIONMAP_3D = false;
  44132. _this.REFLECTIONMAP_SPHERICAL = false;
  44133. _this.REFLECTIONMAP_PLANAR = false;
  44134. _this.REFLECTIONMAP_CUBIC = false;
  44135. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44136. _this.REFLECTIONMAP_PROJECTION = false;
  44137. _this.REFLECTIONMAP_SKYBOX = false;
  44138. _this.REFLECTIONMAP_EXPLICIT = false;
  44139. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44140. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44141. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44142. _this.INVERTCUBICMAP = false;
  44143. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44144. _this.USESPHERICALINVERTEX = false;
  44145. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44146. _this.LODINREFLECTIONALPHA = false;
  44147. _this.GAMMAREFLECTION = false;
  44148. _this.RADIANCEOCCLUSION = false;
  44149. _this.HORIZONOCCLUSION = false;
  44150. _this.REFRACTION = false;
  44151. _this.REFRACTIONMAP_3D = false;
  44152. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44153. _this.LODINREFRACTIONALPHA = false;
  44154. _this.GAMMAREFRACTION = false;
  44155. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44156. _this.INSTANCES = false;
  44157. _this.NUM_BONE_INFLUENCERS = 0;
  44158. _this.BonesPerMesh = 0;
  44159. _this.NONUNIFORMSCALING = false;
  44160. _this.MORPHTARGETS = false;
  44161. _this.MORPHTARGETS_NORMAL = false;
  44162. _this.MORPHTARGETS_TANGENT = false;
  44163. _this.NUM_MORPH_INFLUENCERS = 0;
  44164. _this.IMAGEPROCESSING = false;
  44165. _this.VIGNETTE = false;
  44166. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44167. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44168. _this.TONEMAPPING = false;
  44169. _this.CONTRAST = false;
  44170. _this.COLORCURVES = false;
  44171. _this.COLORGRADING = false;
  44172. _this.COLORGRADING3D = false;
  44173. _this.SAMPLER3DGREENDEPTH = false;
  44174. _this.SAMPLER3DBGRMAP = false;
  44175. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44176. _this.EXPOSURE = false;
  44177. _this.USEPHYSICALLIGHTFALLOFF = false;
  44178. _this.TWOSIDEDLIGHTING = false;
  44179. _this.SHADOWFLOAT = false;
  44180. _this.CLIPPLANE = false;
  44181. _this.POINTSIZE = false;
  44182. _this.FOG = false;
  44183. _this.LOGARITHMICDEPTH = false;
  44184. _this.FORCENORMALFORWARD = false;
  44185. _this.SPECULARAA = false;
  44186. _this.UNLIT = false;
  44187. _this.rebuild();
  44188. return _this;
  44189. }
  44190. /**
  44191. * Resets the PBR Material defines.
  44192. */
  44193. PBRMaterialDefines.prototype.reset = function () {
  44194. _super.prototype.reset.call(this);
  44195. this.ALPHATESTVALUE = "0.5";
  44196. this.PBR = true;
  44197. };
  44198. return PBRMaterialDefines;
  44199. }(BABYLON.MaterialDefines));
  44200. /**
  44201. * The Physically based material base class of BJS.
  44202. *
  44203. * This offers the main features of a standard PBR material.
  44204. * For more information, please refer to the documentation :
  44205. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44206. */
  44207. var PBRBaseMaterial = /** @class */ (function (_super) {
  44208. __extends(PBRBaseMaterial, _super);
  44209. /**
  44210. * Instantiates a new PBRMaterial instance.
  44211. *
  44212. * @param name The material name
  44213. * @param scene The scene the material will be use in.
  44214. */
  44215. function PBRBaseMaterial(name, scene) {
  44216. var _this = _super.call(this, name, scene) || this;
  44217. /**
  44218. * Intensity of the direct lights e.g. the four lights available in your scene.
  44219. * This impacts both the direct diffuse and specular highlights.
  44220. */
  44221. _this._directIntensity = 1.0;
  44222. /**
  44223. * Intensity of the emissive part of the material.
  44224. * This helps controlling the emissive effect without modifying the emissive color.
  44225. */
  44226. _this._emissiveIntensity = 1.0;
  44227. /**
  44228. * Intensity of the environment e.g. how much the environment will light the object
  44229. * either through harmonics for rough material or through the refelction for shiny ones.
  44230. */
  44231. _this._environmentIntensity = 1.0;
  44232. /**
  44233. * This is a special control allowing the reduction of the specular highlights coming from the
  44234. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44235. */
  44236. _this._specularIntensity = 1.0;
  44237. /**
  44238. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44239. */
  44240. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44241. /**
  44242. * Debug Control allowing disabling the bump map on this material.
  44243. */
  44244. _this._disableBumpMap = false;
  44245. /**
  44246. * AKA Occlusion Texture Intensity in other nomenclature.
  44247. */
  44248. _this._ambientTextureStrength = 1.0;
  44249. /**
  44250. * The color of a material in ambient lighting.
  44251. */
  44252. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44253. /**
  44254. * AKA Diffuse Color in other nomenclature.
  44255. */
  44256. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44257. /**
  44258. * AKA Specular Color in other nomenclature.
  44259. */
  44260. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44261. /**
  44262. * The color applied when light is reflected from a material.
  44263. */
  44264. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44265. /**
  44266. * The color applied when light is emitted from a material.
  44267. */
  44268. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44269. /**
  44270. * AKA Glossiness in other nomenclature.
  44271. */
  44272. _this._microSurface = 0.9;
  44273. /**
  44274. * source material index of refraction (IOR)' / 'destination material IOR.
  44275. */
  44276. _this._indexOfRefraction = 0.66;
  44277. /**
  44278. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44279. */
  44280. _this._invertRefractionY = false;
  44281. /**
  44282. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44283. * Materials half opaque for instance using refraction could benefit from this control.
  44284. */
  44285. _this._linkRefractionWithTransparency = false;
  44286. /**
  44287. * Specifies that the material will use the light map as a show map.
  44288. */
  44289. _this._useLightmapAsShadowmap = false;
  44290. /**
  44291. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44292. * makes the reflect vector face the model (under horizon).
  44293. */
  44294. _this._useHorizonOcclusion = true;
  44295. /**
  44296. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44297. * too much the area relying on ambient texture to define their ambient occlusion.
  44298. */
  44299. _this._useRadianceOcclusion = true;
  44300. /**
  44301. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44302. */
  44303. _this._useAlphaFromAlbedoTexture = false;
  44304. /**
  44305. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44306. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44307. */
  44308. _this._useSpecularOverAlpha = true;
  44309. /**
  44310. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44311. */
  44312. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44313. /**
  44314. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44315. */
  44316. _this._useRoughnessFromMetallicTextureAlpha = true;
  44317. /**
  44318. * Specifies if the metallic texture contains the roughness information in its green channel.
  44319. */
  44320. _this._useRoughnessFromMetallicTextureGreen = false;
  44321. /**
  44322. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44323. */
  44324. _this._useMetallnessFromMetallicTextureBlue = false;
  44325. /**
  44326. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44327. */
  44328. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44329. /**
  44330. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44331. */
  44332. _this._useAmbientInGrayScale = false;
  44333. /**
  44334. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44335. * The material will try to infer what glossiness each pixel should be.
  44336. */
  44337. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44338. /**
  44339. * BJS is using an harcoded light falloff based on a manually sets up range.
  44340. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44341. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44342. */
  44343. _this._usePhysicalLightFalloff = true;
  44344. /**
  44345. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44346. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44347. */
  44348. _this._useRadianceOverAlpha = true;
  44349. /**
  44350. * Allows using an object space normal map (instead of tangent space).
  44351. */
  44352. _this._useObjectSpaceNormalMap = false;
  44353. /**
  44354. * Allows using the bump map in parallax mode.
  44355. */
  44356. _this._useParallax = false;
  44357. /**
  44358. * Allows using the bump map in parallax occlusion mode.
  44359. */
  44360. _this._useParallaxOcclusion = false;
  44361. /**
  44362. * Controls the scale bias of the parallax mode.
  44363. */
  44364. _this._parallaxScaleBias = 0.05;
  44365. /**
  44366. * If sets to true, disables all the lights affecting the material.
  44367. */
  44368. _this._disableLighting = false;
  44369. /**
  44370. * Number of Simultaneous lights allowed on the material.
  44371. */
  44372. _this._maxSimultaneousLights = 4;
  44373. /**
  44374. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44375. */
  44376. _this._invertNormalMapX = false;
  44377. /**
  44378. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44379. */
  44380. _this._invertNormalMapY = false;
  44381. /**
  44382. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44383. */
  44384. _this._twoSidedLighting = false;
  44385. /**
  44386. * Defines the alpha limits in alpha test mode.
  44387. */
  44388. _this._alphaCutOff = 0.4;
  44389. /**
  44390. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44391. */
  44392. _this._forceAlphaTest = false;
  44393. /**
  44394. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44395. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44396. */
  44397. _this._useAlphaFresnel = false;
  44398. /**
  44399. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44400. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44401. */
  44402. _this._useLinearAlphaFresnel = false;
  44403. /**
  44404. * The transparency mode of the material.
  44405. */
  44406. _this._transparencyMode = null;
  44407. /**
  44408. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44409. * from cos thetav and roughness:
  44410. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44411. */
  44412. _this._environmentBRDFTexture = null;
  44413. /**
  44414. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44415. */
  44416. _this._forceIrradianceInFragment = false;
  44417. /**
  44418. * Force normal to face away from face.
  44419. */
  44420. _this._forceNormalForward = false;
  44421. /**
  44422. * Enables specular anti aliasing in the PBR shader.
  44423. * It will both interacts on the Geometry for analytical and IBL lighting.
  44424. * It also prefilter the roughness map based on the bump values.
  44425. */
  44426. _this._enableSpecularAntiAliasing = false;
  44427. /**
  44428. * Stores the available render targets.
  44429. */
  44430. _this._renderTargets = new BABYLON.SmartArray(16);
  44431. /**
  44432. * Sets the global ambient color for the material used in lighting calculations.
  44433. */
  44434. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44435. /**
  44436. * If set to true, no lighting calculations will be applied.
  44437. */
  44438. _this._unlit = false;
  44439. // Setup the default processing configuration to the scene.
  44440. _this._attachImageProcessingConfiguration(null);
  44441. _this.getRenderTargetTextures = function () {
  44442. _this._renderTargets.reset();
  44443. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44444. _this._renderTargets.push(_this._reflectionTexture);
  44445. }
  44446. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44447. _this._renderTargets.push(_this._refractionTexture);
  44448. }
  44449. return _this._renderTargets;
  44450. };
  44451. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44452. return _this;
  44453. }
  44454. /**
  44455. * Attaches a new image processing configuration to the PBR Material.
  44456. * @param configuration
  44457. */
  44458. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44459. var _this = this;
  44460. if (configuration === this._imageProcessingConfiguration) {
  44461. return;
  44462. }
  44463. // Detaches observer.
  44464. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44465. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44466. }
  44467. // Pick the scene configuration if needed.
  44468. if (!configuration) {
  44469. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44470. }
  44471. else {
  44472. this._imageProcessingConfiguration = configuration;
  44473. }
  44474. // Attaches observer.
  44475. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44476. _this._markAllSubMeshesAsImageProcessingDirty();
  44477. });
  44478. };
  44479. /**
  44480. * Gets the name of the material class.
  44481. */
  44482. PBRBaseMaterial.prototype.getClassName = function () {
  44483. return "PBRBaseMaterial";
  44484. };
  44485. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44486. /**
  44487. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44488. */
  44489. get: function () {
  44490. return this._useLogarithmicDepth;
  44491. },
  44492. /**
  44493. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44494. */
  44495. set: function (value) {
  44496. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44497. },
  44498. enumerable: true,
  44499. configurable: true
  44500. });
  44501. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44502. /**
  44503. * Gets the current transparency mode.
  44504. */
  44505. get: function () {
  44506. return this._transparencyMode;
  44507. },
  44508. /**
  44509. * Sets the transparency mode of the material.
  44510. */
  44511. set: function (value) {
  44512. if (this._transparencyMode === value) {
  44513. return;
  44514. }
  44515. this._transparencyMode = value;
  44516. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44517. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44518. },
  44519. enumerable: true,
  44520. configurable: true
  44521. });
  44522. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44523. /**
  44524. * Returns true if alpha blending should be disabled.
  44525. */
  44526. get: function () {
  44527. return (this._linkRefractionWithTransparency ||
  44528. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44529. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44530. },
  44531. enumerable: true,
  44532. configurable: true
  44533. });
  44534. /**
  44535. * Specifies whether or not this material should be rendered in alpha blend mode.
  44536. */
  44537. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44538. if (this._disableAlphaBlending) {
  44539. return false;
  44540. }
  44541. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44542. };
  44543. /**
  44544. * Specifies if the mesh will require alpha blending.
  44545. * @param mesh - BJS mesh.
  44546. */
  44547. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44548. if (this._disableAlphaBlending) {
  44549. return false;
  44550. }
  44551. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44552. };
  44553. /**
  44554. * Specifies whether or not this material should be rendered in alpha test mode.
  44555. */
  44556. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44557. if (this._forceAlphaTest) {
  44558. return true;
  44559. }
  44560. if (this._linkRefractionWithTransparency) {
  44561. return false;
  44562. }
  44563. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44564. };
  44565. /**
  44566. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44567. */
  44568. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44569. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44570. };
  44571. /**
  44572. * Gets the texture used for the alpha test.
  44573. */
  44574. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44575. return this._albedoTexture;
  44576. };
  44577. /**
  44578. * Specifies that the submesh is ready to be used.
  44579. * @param mesh - BJS mesh.
  44580. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44581. * @param useInstances - Specifies that instances should be used.
  44582. * @returns - boolean indicating that the submesh is ready or not.
  44583. */
  44584. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44585. if (subMesh.effect && this.isFrozen) {
  44586. if (this._wasPreviouslyReady) {
  44587. return true;
  44588. }
  44589. }
  44590. if (!subMesh._materialDefines) {
  44591. subMesh._materialDefines = new PBRMaterialDefines();
  44592. }
  44593. var defines = subMesh._materialDefines;
  44594. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44595. if (defines._renderId === this.getScene().getRenderId()) {
  44596. return true;
  44597. }
  44598. }
  44599. var scene = this.getScene();
  44600. var engine = scene.getEngine();
  44601. if (defines._areTexturesDirty) {
  44602. if (scene.texturesEnabled) {
  44603. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44604. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44605. return false;
  44606. }
  44607. }
  44608. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44609. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44610. return false;
  44611. }
  44612. }
  44613. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44614. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44615. return false;
  44616. }
  44617. }
  44618. var reflectionTexture = this._getReflectionTexture();
  44619. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44620. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44621. return false;
  44622. }
  44623. }
  44624. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44625. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44626. return false;
  44627. }
  44628. }
  44629. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44630. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44631. return false;
  44632. }
  44633. }
  44634. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44635. if (this._metallicTexture) {
  44636. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44637. return false;
  44638. }
  44639. }
  44640. else if (this._reflectivityTexture) {
  44641. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44642. return false;
  44643. }
  44644. }
  44645. if (this._microSurfaceTexture) {
  44646. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44647. return false;
  44648. }
  44649. }
  44650. }
  44651. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44652. // Bump texture cannot be not blocking.
  44653. if (!this._bumpTexture.isReady()) {
  44654. return false;
  44655. }
  44656. }
  44657. var refractionTexture = this._getRefractionTexture();
  44658. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44659. if (!refractionTexture.isReadyOrNotBlocking()) {
  44660. return false;
  44661. }
  44662. }
  44663. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44664. // This is blocking.
  44665. if (!this._environmentBRDFTexture.isReady()) {
  44666. return false;
  44667. }
  44668. }
  44669. }
  44670. }
  44671. if (defines._areImageProcessingDirty) {
  44672. if (!this._imageProcessingConfiguration.isReady()) {
  44673. return false;
  44674. }
  44675. }
  44676. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44677. mesh.createNormals(true);
  44678. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44679. }
  44680. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44681. if (effect) {
  44682. scene.resetCachedMaterial();
  44683. subMesh.setEffect(effect, defines);
  44684. this.buildUniformLayout();
  44685. }
  44686. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44687. return false;
  44688. }
  44689. defines._renderId = scene.getRenderId();
  44690. this._wasPreviouslyReady = true;
  44691. return true;
  44692. };
  44693. /**
  44694. * Specifies if the material uses metallic roughness workflow.
  44695. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44696. */
  44697. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44698. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44699. return true;
  44700. }
  44701. return false;
  44702. };
  44703. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44704. if (onCompiled === void 0) { onCompiled = null; }
  44705. if (onError === void 0) { onError = null; }
  44706. if (useInstances === void 0) { useInstances = null; }
  44707. if (useClipPlane === void 0) { useClipPlane = null; }
  44708. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44709. if (!defines.isDirty) {
  44710. return null;
  44711. }
  44712. defines.markAsProcessed();
  44713. var scene = this.getScene();
  44714. var engine = scene.getEngine();
  44715. // Fallbacks
  44716. var fallbacks = new BABYLON.EffectFallbacks();
  44717. var fallbackRank = 0;
  44718. if (defines.USESPHERICALINVERTEX) {
  44719. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44720. }
  44721. if (defines.FOG) {
  44722. fallbacks.addFallback(fallbackRank, "FOG");
  44723. }
  44724. if (defines.POINTSIZE) {
  44725. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44726. }
  44727. if (defines.LOGARITHMICDEPTH) {
  44728. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44729. }
  44730. if (defines.PARALLAX) {
  44731. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44732. }
  44733. if (defines.PARALLAXOCCLUSION) {
  44734. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44735. }
  44736. if (defines.ENVIRONMENTBRDF) {
  44737. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44738. }
  44739. if (defines.TANGENT) {
  44740. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44741. }
  44742. if (defines.BUMP) {
  44743. fallbacks.addFallback(fallbackRank++, "BUMP");
  44744. }
  44745. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44746. if (defines.SPECULARTERM) {
  44747. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44748. }
  44749. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44750. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44751. }
  44752. if (defines.LIGHTMAP) {
  44753. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44754. }
  44755. if (defines.NORMAL) {
  44756. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44757. }
  44758. if (defines.AMBIENT) {
  44759. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44760. }
  44761. if (defines.EMISSIVE) {
  44762. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44763. }
  44764. if (defines.VERTEXCOLOR) {
  44765. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44766. }
  44767. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44768. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44769. }
  44770. if (defines.MORPHTARGETS) {
  44771. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44772. }
  44773. //Attributes
  44774. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44775. if (defines.NORMAL) {
  44776. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44777. }
  44778. if (defines.TANGENT) {
  44779. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44780. }
  44781. if (defines.UV1) {
  44782. attribs.push(BABYLON.VertexBuffer.UVKind);
  44783. }
  44784. if (defines.UV2) {
  44785. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44786. }
  44787. if (defines.VERTEXCOLOR) {
  44788. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44789. }
  44790. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44791. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44792. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44793. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44794. "vFogInfos", "vFogColor", "pointSize",
  44795. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44796. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44797. "mBones",
  44798. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44799. "vLightingIntensity",
  44800. "logarithmicDepthConstant",
  44801. "vSphericalX", "vSphericalY", "vSphericalZ",
  44802. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44803. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44804. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44805. "vTangentSpaceParams"
  44806. ];
  44807. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44808. "bumpSampler", "lightmapSampler", "opacitySampler",
  44809. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44810. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44811. "microSurfaceSampler", "environmentBrdfSampler"];
  44812. var uniformBuffers = ["Material", "Scene"];
  44813. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44814. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44815. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44816. uniformsNames: uniforms,
  44817. uniformBuffersNames: uniformBuffers,
  44818. samplers: samplers,
  44819. defines: defines,
  44820. maxSimultaneousLights: this._maxSimultaneousLights
  44821. });
  44822. var join = defines.toString();
  44823. return engine.createEffect("pbr", {
  44824. attributes: attribs,
  44825. uniformsNames: uniforms,
  44826. uniformBuffersNames: uniformBuffers,
  44827. samplers: samplers,
  44828. defines: join,
  44829. fallbacks: fallbacks,
  44830. onCompiled: onCompiled,
  44831. onError: onError,
  44832. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44833. }, engine);
  44834. };
  44835. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44836. if (useInstances === void 0) { useInstances = null; }
  44837. if (useClipPlane === void 0) { useClipPlane = null; }
  44838. var scene = this.getScene();
  44839. var engine = scene.getEngine();
  44840. // Lights
  44841. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44842. defines._needNormals = true;
  44843. // Textures
  44844. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44845. if (defines._areTexturesDirty) {
  44846. defines._needUVs = false;
  44847. if (scene.texturesEnabled) {
  44848. if (scene.getEngine().getCaps().textureLOD) {
  44849. defines.LODBASEDMICROSFURACE = true;
  44850. }
  44851. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44852. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44853. }
  44854. else {
  44855. defines.ALBEDO = false;
  44856. }
  44857. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44858. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44859. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44860. }
  44861. else {
  44862. defines.AMBIENT = false;
  44863. }
  44864. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44865. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44866. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44867. }
  44868. else {
  44869. defines.OPACITY = false;
  44870. }
  44871. var reflectionTexture = this._getReflectionTexture();
  44872. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44873. defines.REFLECTION = true;
  44874. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44875. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44876. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44877. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44878. defines.INVERTCUBICMAP = true;
  44879. }
  44880. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44881. switch (reflectionTexture.coordinatesMode) {
  44882. case BABYLON.Texture.EXPLICIT_MODE:
  44883. defines.REFLECTIONMAP_EXPLICIT = true;
  44884. break;
  44885. case BABYLON.Texture.PLANAR_MODE:
  44886. defines.REFLECTIONMAP_PLANAR = true;
  44887. break;
  44888. case BABYLON.Texture.PROJECTION_MODE:
  44889. defines.REFLECTIONMAP_PROJECTION = true;
  44890. break;
  44891. case BABYLON.Texture.SKYBOX_MODE:
  44892. defines.REFLECTIONMAP_SKYBOX = true;
  44893. break;
  44894. case BABYLON.Texture.SPHERICAL_MODE:
  44895. defines.REFLECTIONMAP_SPHERICAL = true;
  44896. break;
  44897. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44898. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44899. break;
  44900. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44901. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44902. break;
  44903. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44904. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44905. break;
  44906. case BABYLON.Texture.CUBIC_MODE:
  44907. case BABYLON.Texture.INVCUBIC_MODE:
  44908. default:
  44909. defines.REFLECTIONMAP_CUBIC = true;
  44910. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44911. break;
  44912. }
  44913. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44914. if (reflectionTexture.sphericalPolynomial) {
  44915. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44916. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44917. defines.USESPHERICALINVERTEX = false;
  44918. }
  44919. else {
  44920. defines.USESPHERICALINVERTEX = true;
  44921. }
  44922. }
  44923. }
  44924. }
  44925. else {
  44926. defines.REFLECTION = false;
  44927. defines.REFLECTIONMAP_3D = false;
  44928. defines.REFLECTIONMAP_SPHERICAL = false;
  44929. defines.REFLECTIONMAP_PLANAR = false;
  44930. defines.REFLECTIONMAP_CUBIC = false;
  44931. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44932. defines.REFLECTIONMAP_PROJECTION = false;
  44933. defines.REFLECTIONMAP_SKYBOX = false;
  44934. defines.REFLECTIONMAP_EXPLICIT = false;
  44935. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44936. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44937. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44938. defines.INVERTCUBICMAP = false;
  44939. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44940. defines.USESPHERICALINVERTEX = false;
  44941. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44942. defines.LODINREFLECTIONALPHA = false;
  44943. defines.GAMMAREFLECTION = false;
  44944. }
  44945. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44946. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44947. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44948. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44949. }
  44950. else {
  44951. defines.LIGHTMAP = false;
  44952. }
  44953. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44954. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44955. }
  44956. else {
  44957. defines.EMISSIVE = false;
  44958. }
  44959. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44960. if (this._metallicTexture) {
  44961. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44962. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44963. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44964. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44965. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44966. }
  44967. else if (this._reflectivityTexture) {
  44968. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44969. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44970. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44971. }
  44972. else {
  44973. defines.REFLECTIVITY = false;
  44974. }
  44975. if (this._microSurfaceTexture) {
  44976. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44977. }
  44978. else {
  44979. defines.MICROSURFACEMAP = false;
  44980. }
  44981. }
  44982. else {
  44983. defines.REFLECTIVITY = false;
  44984. defines.MICROSURFACEMAP = false;
  44985. }
  44986. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44987. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44988. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44989. defines.PARALLAX = true;
  44990. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44991. }
  44992. else {
  44993. defines.PARALLAX = false;
  44994. }
  44995. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44996. }
  44997. else {
  44998. defines.BUMP = false;
  44999. }
  45000. var refractionTexture = this._getRefractionTexture();
  45001. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45002. defines.REFRACTION = true;
  45003. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45004. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45005. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45006. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45007. if (this._linkRefractionWithTransparency) {
  45008. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45009. }
  45010. }
  45011. else {
  45012. defines.REFRACTION = false;
  45013. }
  45014. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45015. defines.ENVIRONMENTBRDF = true;
  45016. }
  45017. else {
  45018. defines.ENVIRONMENTBRDF = false;
  45019. }
  45020. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45021. defines.ALPHAFROMALBEDO = true;
  45022. }
  45023. else {
  45024. defines.ALPHAFROMALBEDO = false;
  45025. }
  45026. }
  45027. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45028. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45029. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45030. if (!this.backFaceCulling && this._twoSidedLighting) {
  45031. defines.TWOSIDEDLIGHTING = true;
  45032. }
  45033. else {
  45034. defines.TWOSIDEDLIGHTING = false;
  45035. }
  45036. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45037. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45038. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45039. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45040. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45041. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45042. }
  45043. if (defines._areImageProcessingDirty) {
  45044. this._imageProcessingConfiguration.prepareDefines(defines);
  45045. }
  45046. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45047. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45048. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45049. // Misc.
  45050. if (defines._areMiscDirty) {
  45051. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45052. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45053. }
  45054. // Values that need to be evaluated on every frame
  45055. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45056. // Attribs
  45057. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45058. };
  45059. /**
  45060. * Force shader compilation
  45061. */
  45062. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45063. var _this = this;
  45064. var localOptions = __assign({ clipPlane: false }, options);
  45065. var defines = new PBRMaterialDefines();
  45066. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45067. if (effect.isReady()) {
  45068. if (onCompiled) {
  45069. onCompiled(this);
  45070. }
  45071. }
  45072. else {
  45073. effect.onCompileObservable.add(function () {
  45074. if (onCompiled) {
  45075. onCompiled(_this);
  45076. }
  45077. });
  45078. }
  45079. };
  45080. /**
  45081. * Initializes the uniform buffer layout for the shader.
  45082. */
  45083. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45084. // Order is important !
  45085. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45086. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45087. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45088. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45089. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45090. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45091. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45092. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45093. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45094. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45095. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45096. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45097. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45098. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45099. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45100. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45101. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45102. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45103. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45104. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45105. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45106. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45107. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45108. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45109. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45110. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45111. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45112. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45113. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45114. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45115. this._uniformBuffer.addUniform("pointSize", 1);
  45116. this._uniformBuffer.create();
  45117. };
  45118. /**
  45119. * Unbinds the textures.
  45120. */
  45121. PBRBaseMaterial.prototype.unbind = function () {
  45122. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45123. this._uniformBuffer.setTexture("reflectionSampler", null);
  45124. }
  45125. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45126. this._uniformBuffer.setTexture("refractionSampler", null);
  45127. }
  45128. _super.prototype.unbind.call(this);
  45129. };
  45130. /**
  45131. * Binds the submesh data.
  45132. * @param world - The world matrix.
  45133. * @param mesh - The BJS mesh.
  45134. * @param subMesh - A submesh of the BJS mesh.
  45135. */
  45136. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45137. var scene = this.getScene();
  45138. var defines = subMesh._materialDefines;
  45139. if (!defines) {
  45140. return;
  45141. }
  45142. var effect = subMesh.effect;
  45143. if (!effect) {
  45144. return;
  45145. }
  45146. this._activeEffect = effect;
  45147. // Matrices
  45148. this.bindOnlyWorldMatrix(world);
  45149. // Normal Matrix
  45150. if (defines.OBJECTSPACE_NORMALMAP) {
  45151. world.toNormalMatrix(this._normalMatrix);
  45152. this.bindOnlyNormalMatrix(this._normalMatrix);
  45153. }
  45154. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45155. // Bones
  45156. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45157. var reflectionTexture = null;
  45158. if (mustRebind) {
  45159. this._uniformBuffer.bindToEffect(effect, "Material");
  45160. this.bindViewProjection(effect);
  45161. reflectionTexture = this._getReflectionTexture();
  45162. var refractionTexture = this._getRefractionTexture();
  45163. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45164. // Texture uniforms
  45165. if (scene.texturesEnabled) {
  45166. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45167. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45168. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45169. }
  45170. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45171. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45172. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45173. }
  45174. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45175. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45176. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45177. }
  45178. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45179. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45180. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45181. if (reflectionTexture.boundingBoxSize) {
  45182. var cubeTexture = reflectionTexture;
  45183. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45184. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45185. }
  45186. var polynomials = reflectionTexture.sphericalPolynomial;
  45187. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45188. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45189. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45190. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45191. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45192. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45193. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45194. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45195. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45196. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45197. }
  45198. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45199. }
  45200. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45201. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45202. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45203. }
  45204. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45205. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45206. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45207. }
  45208. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45209. if (this._metallicTexture) {
  45210. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45211. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45212. }
  45213. else if (this._reflectivityTexture) {
  45214. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45215. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45216. }
  45217. if (this._microSurfaceTexture) {
  45218. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45219. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45220. }
  45221. }
  45222. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45223. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45224. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45225. if (scene._mirroredCameraPosition) {
  45226. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45227. }
  45228. else {
  45229. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45230. }
  45231. }
  45232. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45233. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45234. var depth = 1.0;
  45235. if (!refractionTexture.isCube) {
  45236. if (refractionTexture.depth) {
  45237. depth = refractionTexture.depth;
  45238. }
  45239. }
  45240. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45241. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45242. }
  45243. }
  45244. // Point size
  45245. if (this.pointsCloud) {
  45246. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45247. }
  45248. // Colors
  45249. if (defines.METALLICWORKFLOW) {
  45250. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45251. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45252. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45253. }
  45254. else {
  45255. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45256. }
  45257. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45258. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45259. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45260. // Misc
  45261. this._lightingInfos.x = this._directIntensity;
  45262. this._lightingInfos.y = this._emissiveIntensity;
  45263. this._lightingInfos.z = this._environmentIntensity;
  45264. this._lightingInfos.w = this._specularIntensity;
  45265. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45266. }
  45267. // Textures
  45268. if (scene.texturesEnabled) {
  45269. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45270. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45271. }
  45272. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45273. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45274. }
  45275. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45276. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45277. }
  45278. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45279. if (defines.LODBASEDMICROSFURACE) {
  45280. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45281. }
  45282. else {
  45283. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45284. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45285. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45286. }
  45287. }
  45288. if (defines.ENVIRONMENTBRDF) {
  45289. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45290. }
  45291. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45292. if (defines.LODBASEDMICROSFURACE) {
  45293. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45294. }
  45295. else {
  45296. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45297. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45298. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45299. }
  45300. }
  45301. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45302. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45303. }
  45304. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45305. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45306. }
  45307. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45308. if (this._metallicTexture) {
  45309. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45310. }
  45311. else if (this._reflectivityTexture) {
  45312. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45313. }
  45314. if (this._microSurfaceTexture) {
  45315. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45316. }
  45317. }
  45318. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45319. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45320. }
  45321. }
  45322. // Clip plane
  45323. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45324. // Colors
  45325. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45326. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45327. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45328. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45329. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45330. }
  45331. if (mustRebind || !this.isFrozen) {
  45332. // Lights
  45333. if (scene.lightsEnabled && !this._disableLighting) {
  45334. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45335. }
  45336. // View
  45337. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45338. this.bindView(effect);
  45339. }
  45340. // Fog
  45341. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45342. // Morph targets
  45343. if (defines.NUM_MORPH_INFLUENCERS) {
  45344. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45345. }
  45346. // image processing
  45347. this._imageProcessingConfiguration.bind(this._activeEffect);
  45348. // Log. depth
  45349. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45350. }
  45351. this._uniformBuffer.update();
  45352. this._afterBind(mesh);
  45353. };
  45354. /**
  45355. * Returns the animatable textures.
  45356. * @returns - Array of animatable textures.
  45357. */
  45358. PBRBaseMaterial.prototype.getAnimatables = function () {
  45359. var results = [];
  45360. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45361. results.push(this._albedoTexture);
  45362. }
  45363. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45364. results.push(this._ambientTexture);
  45365. }
  45366. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45367. results.push(this._opacityTexture);
  45368. }
  45369. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45370. results.push(this._reflectionTexture);
  45371. }
  45372. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45373. results.push(this._emissiveTexture);
  45374. }
  45375. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45376. results.push(this._metallicTexture);
  45377. }
  45378. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45379. results.push(this._reflectivityTexture);
  45380. }
  45381. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45382. results.push(this._bumpTexture);
  45383. }
  45384. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45385. results.push(this._lightmapTexture);
  45386. }
  45387. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45388. results.push(this._refractionTexture);
  45389. }
  45390. return results;
  45391. };
  45392. /**
  45393. * Returns the texture used for reflections.
  45394. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45395. */
  45396. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45397. if (this._reflectionTexture) {
  45398. return this._reflectionTexture;
  45399. }
  45400. return this.getScene().environmentTexture;
  45401. };
  45402. /**
  45403. * Returns the texture used for refraction or null if none is used.
  45404. * @returns - Refection texture if present. If no refraction texture and refraction
  45405. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45406. */
  45407. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45408. if (this._refractionTexture) {
  45409. return this._refractionTexture;
  45410. }
  45411. if (this._linkRefractionWithTransparency) {
  45412. return this.getScene().environmentTexture;
  45413. }
  45414. return null;
  45415. };
  45416. /**
  45417. * Disposes the resources of the material.
  45418. * @param forceDisposeEffect - Forces the disposal of effects.
  45419. * @param forceDisposeTextures - Forces the disposal of all textures.
  45420. */
  45421. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45422. if (forceDisposeTextures) {
  45423. if (this._albedoTexture) {
  45424. this._albedoTexture.dispose();
  45425. }
  45426. if (this._ambientTexture) {
  45427. this._ambientTexture.dispose();
  45428. }
  45429. if (this._opacityTexture) {
  45430. this._opacityTexture.dispose();
  45431. }
  45432. if (this._reflectionTexture) {
  45433. this._reflectionTexture.dispose();
  45434. }
  45435. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45436. this._environmentBRDFTexture.dispose();
  45437. }
  45438. if (this._emissiveTexture) {
  45439. this._emissiveTexture.dispose();
  45440. }
  45441. if (this._metallicTexture) {
  45442. this._metallicTexture.dispose();
  45443. }
  45444. if (this._reflectivityTexture) {
  45445. this._reflectivityTexture.dispose();
  45446. }
  45447. if (this._bumpTexture) {
  45448. this._bumpTexture.dispose();
  45449. }
  45450. if (this._lightmapTexture) {
  45451. this._lightmapTexture.dispose();
  45452. }
  45453. if (this._refractionTexture) {
  45454. this._refractionTexture.dispose();
  45455. }
  45456. }
  45457. this._renderTargets.dispose();
  45458. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45459. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45460. }
  45461. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45462. };
  45463. /**
  45464. * Stores the reflectivity values based on metallic roughness workflow.
  45465. */
  45466. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45467. __decorate([
  45468. BABYLON.serializeAsImageProcessingConfiguration()
  45469. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45470. __decorate([
  45471. BABYLON.serialize()
  45472. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45473. __decorate([
  45474. BABYLON.serialize()
  45475. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45476. return PBRBaseMaterial;
  45477. }(BABYLON.PushMaterial));
  45478. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45479. })(BABYLON || (BABYLON = {}));
  45480. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45481. var BABYLON;
  45482. (function (BABYLON) {
  45483. /**
  45484. * The Physically based simple base material of BJS.
  45485. *
  45486. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45487. * It is used as the base class for both the specGloss and metalRough conventions.
  45488. */
  45489. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45490. __extends(PBRBaseSimpleMaterial, _super);
  45491. /**
  45492. * Instantiates a new PBRMaterial instance.
  45493. *
  45494. * @param name The material name
  45495. * @param scene The scene the material will be use in.
  45496. */
  45497. function PBRBaseSimpleMaterial(name, scene) {
  45498. var _this = _super.call(this, name, scene) || this;
  45499. /**
  45500. * Number of Simultaneous lights allowed on the material.
  45501. */
  45502. _this.maxSimultaneousLights = 4;
  45503. /**
  45504. * If sets to true, disables all the lights affecting the material.
  45505. */
  45506. _this.disableLighting = false;
  45507. /**
  45508. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45509. */
  45510. _this.invertNormalMapX = false;
  45511. /**
  45512. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45513. */
  45514. _this.invertNormalMapY = false;
  45515. /**
  45516. * Emissivie color used to self-illuminate the model.
  45517. */
  45518. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45519. /**
  45520. * Occlusion Channel Strenght.
  45521. */
  45522. _this.occlusionStrength = 1.0;
  45523. _this.useLightmapAsShadowmap = false;
  45524. _this._useAlphaFromAlbedoTexture = true;
  45525. _this._useAmbientInGrayScale = true;
  45526. return _this;
  45527. }
  45528. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45529. /**
  45530. * Gets the current double sided mode.
  45531. */
  45532. get: function () {
  45533. return this._twoSidedLighting;
  45534. },
  45535. /**
  45536. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45537. */
  45538. set: function (value) {
  45539. if (this._twoSidedLighting === value) {
  45540. return;
  45541. }
  45542. this._twoSidedLighting = value;
  45543. this.backFaceCulling = !value;
  45544. this._markAllSubMeshesAsTexturesDirty();
  45545. },
  45546. enumerable: true,
  45547. configurable: true
  45548. });
  45549. /**
  45550. * Return the active textures of the material.
  45551. */
  45552. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45553. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45554. if (this.environmentTexture) {
  45555. activeTextures.push(this.environmentTexture);
  45556. }
  45557. if (this.normalTexture) {
  45558. activeTextures.push(this.normalTexture);
  45559. }
  45560. if (this.emissiveTexture) {
  45561. activeTextures.push(this.emissiveTexture);
  45562. }
  45563. if (this.occlusionTexture) {
  45564. activeTextures.push(this.occlusionTexture);
  45565. }
  45566. if (this.lightmapTexture) {
  45567. activeTextures.push(this.lightmapTexture);
  45568. }
  45569. return activeTextures;
  45570. };
  45571. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45572. if (_super.prototype.hasTexture.call(this, texture)) {
  45573. return true;
  45574. }
  45575. if (this.lightmapTexture === texture) {
  45576. return true;
  45577. }
  45578. return false;
  45579. };
  45580. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45581. return "PBRBaseSimpleMaterial";
  45582. };
  45583. __decorate([
  45584. BABYLON.serialize(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45586. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45590. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45591. __decorate([
  45592. BABYLON.serializeAsTexture(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45594. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45603. __decorate([
  45604. BABYLON.serializeAsTexture(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45606. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45607. __decorate([
  45608. BABYLON.serializeAsColor3("emissive"),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45611. __decorate([
  45612. BABYLON.serializeAsTexture(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45618. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45619. __decorate([
  45620. BABYLON.serializeAsTexture(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45622. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45626. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45627. __decorate([
  45628. BABYLON.serialize()
  45629. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45630. __decorate([
  45631. BABYLON.serializeAsTexture(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45633. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45637. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45638. return PBRBaseSimpleMaterial;
  45639. }(BABYLON.PBRBaseMaterial));
  45640. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45641. })(BABYLON || (BABYLON = {}));
  45642. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45643. var BABYLON;
  45644. (function (BABYLON) {
  45645. /**
  45646. * The Physically based material of BJS.
  45647. *
  45648. * This offers the main features of a standard PBR material.
  45649. * For more information, please refer to the documentation :
  45650. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45651. */
  45652. var PBRMaterial = /** @class */ (function (_super) {
  45653. __extends(PBRMaterial, _super);
  45654. /**
  45655. * Instantiates a new PBRMaterial instance.
  45656. *
  45657. * @param name The material name
  45658. * @param scene The scene the material will be use in.
  45659. */
  45660. function PBRMaterial(name, scene) {
  45661. var _this = _super.call(this, name, scene) || this;
  45662. /**
  45663. * Intensity of the direct lights e.g. the four lights available in your scene.
  45664. * This impacts both the direct diffuse and specular highlights.
  45665. */
  45666. _this.directIntensity = 1.0;
  45667. /**
  45668. * Intensity of the emissive part of the material.
  45669. * This helps controlling the emissive effect without modifying the emissive color.
  45670. */
  45671. _this.emissiveIntensity = 1.0;
  45672. /**
  45673. * Intensity of the environment e.g. how much the environment will light the object
  45674. * either through harmonics for rough material or through the refelction for shiny ones.
  45675. */
  45676. _this.environmentIntensity = 1.0;
  45677. /**
  45678. * This is a special control allowing the reduction of the specular highlights coming from the
  45679. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45680. */
  45681. _this.specularIntensity = 1.0;
  45682. /**
  45683. * Debug Control allowing disabling the bump map on this material.
  45684. */
  45685. _this.disableBumpMap = false;
  45686. /**
  45687. * AKA Occlusion Texture Intensity in other nomenclature.
  45688. */
  45689. _this.ambientTextureStrength = 1.0;
  45690. /**
  45691. * The color of a material in ambient lighting.
  45692. */
  45693. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45694. /**
  45695. * AKA Diffuse Color in other nomenclature.
  45696. */
  45697. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45698. /**
  45699. * AKA Specular Color in other nomenclature.
  45700. */
  45701. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45702. /**
  45703. * The color reflected from the material.
  45704. */
  45705. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45706. /**
  45707. * The color emitted from the material.
  45708. */
  45709. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45710. /**
  45711. * AKA Glossiness in other nomenclature.
  45712. */
  45713. _this.microSurface = 1.0;
  45714. /**
  45715. * source material index of refraction (IOR)' / 'destination material IOR.
  45716. */
  45717. _this.indexOfRefraction = 0.66;
  45718. /**
  45719. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45720. */
  45721. _this.invertRefractionY = false;
  45722. /**
  45723. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45724. * Materials half opaque for instance using refraction could benefit from this control.
  45725. */
  45726. _this.linkRefractionWithTransparency = false;
  45727. _this.useLightmapAsShadowmap = false;
  45728. /**
  45729. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45730. */
  45731. _this.useAlphaFromAlbedoTexture = false;
  45732. /**
  45733. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45734. */
  45735. _this.forceAlphaTest = false;
  45736. /**
  45737. * Defines the alpha limits in alpha test mode.
  45738. */
  45739. _this.alphaCutOff = 0.4;
  45740. /**
  45741. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45742. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45743. */
  45744. _this.useSpecularOverAlpha = true;
  45745. /**
  45746. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45747. */
  45748. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45749. /**
  45750. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45751. */
  45752. _this.useRoughnessFromMetallicTextureAlpha = true;
  45753. /**
  45754. * Specifies if the metallic texture contains the roughness information in its green channel.
  45755. */
  45756. _this.useRoughnessFromMetallicTextureGreen = false;
  45757. /**
  45758. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45759. */
  45760. _this.useMetallnessFromMetallicTextureBlue = false;
  45761. /**
  45762. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45763. */
  45764. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45765. /**
  45766. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45767. */
  45768. _this.useAmbientInGrayScale = false;
  45769. /**
  45770. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45771. * The material will try to infer what glossiness each pixel should be.
  45772. */
  45773. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45774. /**
  45775. * BJS is using an harcoded light falloff based on a manually sets up range.
  45776. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45777. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45778. */
  45779. _this.usePhysicalLightFalloff = true;
  45780. /**
  45781. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45782. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45783. */
  45784. _this.useRadianceOverAlpha = true;
  45785. /**
  45786. * Allows using an object space normal map (instead of tangent space).
  45787. */
  45788. _this.useObjectSpaceNormalMap = false;
  45789. /**
  45790. * Allows using the bump map in parallax mode.
  45791. */
  45792. _this.useParallax = false;
  45793. /**
  45794. * Allows using the bump map in parallax occlusion mode.
  45795. */
  45796. _this.useParallaxOcclusion = false;
  45797. /**
  45798. * Controls the scale bias of the parallax mode.
  45799. */
  45800. _this.parallaxScaleBias = 0.05;
  45801. /**
  45802. * If sets to true, disables all the lights affecting the material.
  45803. */
  45804. _this.disableLighting = false;
  45805. /**
  45806. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45807. */
  45808. _this.forceIrradianceInFragment = false;
  45809. /**
  45810. * Number of Simultaneous lights allowed on the material.
  45811. */
  45812. _this.maxSimultaneousLights = 4;
  45813. /**
  45814. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45815. */
  45816. _this.invertNormalMapX = false;
  45817. /**
  45818. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45819. */
  45820. _this.invertNormalMapY = false;
  45821. /**
  45822. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45823. */
  45824. _this.twoSidedLighting = false;
  45825. /**
  45826. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45827. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45828. */
  45829. _this.useAlphaFresnel = false;
  45830. /**
  45831. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45832. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45833. */
  45834. _this.useLinearAlphaFresnel = false;
  45835. /**
  45836. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45837. * And/Or occlude the blended part.
  45838. */
  45839. _this.environmentBRDFTexture = null;
  45840. /**
  45841. * Force normal to face away from face.
  45842. */
  45843. _this.forceNormalForward = false;
  45844. /**
  45845. * Enables specular anti aliasing in the PBR shader.
  45846. * It will both interacts on the Geometry for analytical and IBL lighting.
  45847. * It also prefilter the roughness map based on the bump values.
  45848. */
  45849. _this.enableSpecularAntiAliasing = false;
  45850. /**
  45851. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45852. * makes the reflect vector face the model (under horizon).
  45853. */
  45854. _this.useHorizonOcclusion = true;
  45855. /**
  45856. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45857. * too much the area relying on ambient texture to define their ambient occlusion.
  45858. */
  45859. _this.useRadianceOcclusion = true;
  45860. /**
  45861. * If set to true, no lighting calculations will be applied.
  45862. */
  45863. _this.unlit = false;
  45864. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45865. return _this;
  45866. }
  45867. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45868. /**
  45869. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45870. */
  45871. get: function () {
  45872. return this._PBRMATERIAL_OPAQUE;
  45873. },
  45874. enumerable: true,
  45875. configurable: true
  45876. });
  45877. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45878. /**
  45879. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45880. */
  45881. get: function () {
  45882. return this._PBRMATERIAL_ALPHATEST;
  45883. },
  45884. enumerable: true,
  45885. configurable: true
  45886. });
  45887. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45888. /**
  45889. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45890. */
  45891. get: function () {
  45892. return this._PBRMATERIAL_ALPHABLEND;
  45893. },
  45894. enumerable: true,
  45895. configurable: true
  45896. });
  45897. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45898. /**
  45899. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45900. * They are also discarded below the alpha cutoff threshold to improve performances.
  45901. */
  45902. get: function () {
  45903. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45904. },
  45905. enumerable: true,
  45906. configurable: true
  45907. });
  45908. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45909. /**
  45910. * Gets the image processing configuration used either in this material.
  45911. */
  45912. get: function () {
  45913. return this._imageProcessingConfiguration;
  45914. },
  45915. /**
  45916. * Sets the Default image processing configuration used either in the this material.
  45917. *
  45918. * If sets to null, the scene one is in use.
  45919. */
  45920. set: function (value) {
  45921. this._attachImageProcessingConfiguration(value);
  45922. // Ensure the effect will be rebuilt.
  45923. this._markAllSubMeshesAsTexturesDirty();
  45924. },
  45925. enumerable: true,
  45926. configurable: true
  45927. });
  45928. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45929. /**
  45930. * Gets wether the color curves effect is enabled.
  45931. */
  45932. get: function () {
  45933. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45934. },
  45935. /**
  45936. * Sets wether the color curves effect is enabled.
  45937. */
  45938. set: function (value) {
  45939. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45940. },
  45941. enumerable: true,
  45942. configurable: true
  45943. });
  45944. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45945. /**
  45946. * Gets wether the color grading effect is enabled.
  45947. */
  45948. get: function () {
  45949. return this.imageProcessingConfiguration.colorGradingEnabled;
  45950. },
  45951. /**
  45952. * Gets wether the color grading effect is enabled.
  45953. */
  45954. set: function (value) {
  45955. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45956. },
  45957. enumerable: true,
  45958. configurable: true
  45959. });
  45960. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45961. /**
  45962. * Gets wether tonemapping is enabled or not.
  45963. */
  45964. get: function () {
  45965. return this._imageProcessingConfiguration.toneMappingEnabled;
  45966. },
  45967. /**
  45968. * Sets wether tonemapping is enabled or not
  45969. */
  45970. set: function (value) {
  45971. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45972. },
  45973. enumerable: true,
  45974. configurable: true
  45975. });
  45976. ;
  45977. ;
  45978. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45979. /**
  45980. * The camera exposure used on this material.
  45981. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45982. * This corresponds to a photographic exposure.
  45983. */
  45984. get: function () {
  45985. return this._imageProcessingConfiguration.exposure;
  45986. },
  45987. /**
  45988. * The camera exposure used on this material.
  45989. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45990. * This corresponds to a photographic exposure.
  45991. */
  45992. set: function (value) {
  45993. this._imageProcessingConfiguration.exposure = value;
  45994. },
  45995. enumerable: true,
  45996. configurable: true
  45997. });
  45998. ;
  45999. ;
  46000. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46001. /**
  46002. * Gets The camera contrast used on this material.
  46003. */
  46004. get: function () {
  46005. return this._imageProcessingConfiguration.contrast;
  46006. },
  46007. /**
  46008. * Sets The camera contrast used on this material.
  46009. */
  46010. set: function (value) {
  46011. this._imageProcessingConfiguration.contrast = value;
  46012. },
  46013. enumerable: true,
  46014. configurable: true
  46015. });
  46016. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46017. /**
  46018. * Gets the Color Grading 2D Lookup Texture.
  46019. */
  46020. get: function () {
  46021. return this._imageProcessingConfiguration.colorGradingTexture;
  46022. },
  46023. /**
  46024. * Sets the Color Grading 2D Lookup Texture.
  46025. */
  46026. set: function (value) {
  46027. this._imageProcessingConfiguration.colorGradingTexture = value;
  46028. },
  46029. enumerable: true,
  46030. configurable: true
  46031. });
  46032. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46033. /**
  46034. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46035. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46036. * 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;
  46037. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46038. */
  46039. get: function () {
  46040. return this._imageProcessingConfiguration.colorCurves;
  46041. },
  46042. /**
  46043. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46044. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46045. * 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;
  46046. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46047. */
  46048. set: function (value) {
  46049. this._imageProcessingConfiguration.colorCurves = value;
  46050. },
  46051. enumerable: true,
  46052. configurable: true
  46053. });
  46054. /**
  46055. * Returns the name of this material class.
  46056. */
  46057. PBRMaterial.prototype.getClassName = function () {
  46058. return "PBRMaterial";
  46059. };
  46060. /**
  46061. * Returns an array of the actively used textures.
  46062. * @returns - Array of BaseTextures
  46063. */
  46064. PBRMaterial.prototype.getActiveTextures = function () {
  46065. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46066. if (this._albedoTexture) {
  46067. activeTextures.push(this._albedoTexture);
  46068. }
  46069. if (this._ambientTexture) {
  46070. activeTextures.push(this._ambientTexture);
  46071. }
  46072. if (this._opacityTexture) {
  46073. activeTextures.push(this._opacityTexture);
  46074. }
  46075. if (this._reflectionTexture) {
  46076. activeTextures.push(this._reflectionTexture);
  46077. }
  46078. if (this._emissiveTexture) {
  46079. activeTextures.push(this._emissiveTexture);
  46080. }
  46081. if (this._reflectivityTexture) {
  46082. activeTextures.push(this._reflectivityTexture);
  46083. }
  46084. if (this._metallicTexture) {
  46085. activeTextures.push(this._metallicTexture);
  46086. }
  46087. if (this._microSurfaceTexture) {
  46088. activeTextures.push(this._microSurfaceTexture);
  46089. }
  46090. if (this._bumpTexture) {
  46091. activeTextures.push(this._bumpTexture);
  46092. }
  46093. if (this._lightmapTexture) {
  46094. activeTextures.push(this._lightmapTexture);
  46095. }
  46096. if (this._refractionTexture) {
  46097. activeTextures.push(this._refractionTexture);
  46098. }
  46099. return activeTextures;
  46100. };
  46101. /**
  46102. * Checks to see if a texture is used in the material.
  46103. * @param texture - Base texture to use.
  46104. * @returns - Boolean specifying if a texture is used in the material.
  46105. */
  46106. PBRMaterial.prototype.hasTexture = function (texture) {
  46107. if (_super.prototype.hasTexture.call(this, texture)) {
  46108. return true;
  46109. }
  46110. if (this._albedoTexture === texture) {
  46111. return true;
  46112. }
  46113. if (this._ambientTexture === texture) {
  46114. return true;
  46115. }
  46116. if (this._opacityTexture === texture) {
  46117. return true;
  46118. }
  46119. if (this._reflectionTexture === texture) {
  46120. return true;
  46121. }
  46122. if (this._reflectivityTexture === texture) {
  46123. return true;
  46124. }
  46125. if (this._metallicTexture === texture) {
  46126. return true;
  46127. }
  46128. if (this._microSurfaceTexture === texture) {
  46129. return true;
  46130. }
  46131. if (this._bumpTexture === texture) {
  46132. return true;
  46133. }
  46134. if (this._lightmapTexture === texture) {
  46135. return true;
  46136. }
  46137. if (this._refractionTexture === texture) {
  46138. return true;
  46139. }
  46140. return false;
  46141. };
  46142. /**
  46143. * Makes a duplicate of the current material.
  46144. * @param name - name to use for the new material.
  46145. */
  46146. PBRMaterial.prototype.clone = function (name) {
  46147. var _this = this;
  46148. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46149. clone.id = name;
  46150. clone.name = name;
  46151. return clone;
  46152. };
  46153. /**
  46154. * Serializes this PBR Material.
  46155. * @returns - An object with the serialized material.
  46156. */
  46157. PBRMaterial.prototype.serialize = function () {
  46158. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46159. serializationObject.customType = "BABYLON.PBRMaterial";
  46160. return serializationObject;
  46161. };
  46162. // Statics
  46163. /**
  46164. * Parses a PBR Material from a serialized object.
  46165. * @param source - Serialized object.
  46166. * @param scene - BJS scene instance.
  46167. * @param rootUrl - url for the scene object
  46168. * @returns - PBRMaterial
  46169. */
  46170. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46171. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46172. };
  46173. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46174. /**
  46175. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46176. */
  46177. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46178. /**
  46179. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46180. */
  46181. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46182. /**
  46183. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46184. * They are also discarded below the alpha cutoff threshold to improve performances.
  46185. */
  46186. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46187. __decorate([
  46188. BABYLON.serialize(),
  46189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46190. ], PBRMaterial.prototype, "directIntensity", void 0);
  46191. __decorate([
  46192. BABYLON.serialize(),
  46193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46194. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46195. __decorate([
  46196. BABYLON.serialize(),
  46197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46198. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46199. __decorate([
  46200. BABYLON.serialize(),
  46201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46202. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46203. __decorate([
  46204. BABYLON.serialize(),
  46205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46206. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46207. __decorate([
  46208. BABYLON.serializeAsTexture(),
  46209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46210. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46211. __decorate([
  46212. BABYLON.serializeAsTexture(),
  46213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46214. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46215. __decorate([
  46216. BABYLON.serialize(),
  46217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46218. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46219. __decorate([
  46220. BABYLON.serializeAsTexture(),
  46221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46222. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46223. __decorate([
  46224. BABYLON.serializeAsTexture(),
  46225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46226. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46227. __decorate([
  46228. BABYLON.serializeAsTexture(),
  46229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46230. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46231. __decorate([
  46232. BABYLON.serializeAsTexture(),
  46233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46234. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46235. __decorate([
  46236. BABYLON.serializeAsTexture(),
  46237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46238. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46239. __decorate([
  46240. BABYLON.serialize(),
  46241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46242. ], PBRMaterial.prototype, "metallic", void 0);
  46243. __decorate([
  46244. BABYLON.serialize(),
  46245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46246. ], PBRMaterial.prototype, "roughness", void 0);
  46247. __decorate([
  46248. BABYLON.serializeAsTexture(),
  46249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46250. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46251. __decorate([
  46252. BABYLON.serializeAsTexture(),
  46253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46254. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46255. __decorate([
  46256. BABYLON.serializeAsTexture(),
  46257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46258. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46259. __decorate([
  46260. BABYLON.serializeAsTexture(),
  46261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46262. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46263. __decorate([
  46264. BABYLON.serializeAsColor3("ambient"),
  46265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46266. ], PBRMaterial.prototype, "ambientColor", void 0);
  46267. __decorate([
  46268. BABYLON.serializeAsColor3("albedo"),
  46269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46270. ], PBRMaterial.prototype, "albedoColor", void 0);
  46271. __decorate([
  46272. BABYLON.serializeAsColor3("reflectivity"),
  46273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46274. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46275. __decorate([
  46276. BABYLON.serializeAsColor3("reflection"),
  46277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46278. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46279. __decorate([
  46280. BABYLON.serializeAsColor3("emissive"),
  46281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46282. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46283. __decorate([
  46284. BABYLON.serialize(),
  46285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46286. ], PBRMaterial.prototype, "microSurface", void 0);
  46287. __decorate([
  46288. BABYLON.serialize(),
  46289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46290. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46291. __decorate([
  46292. BABYLON.serialize(),
  46293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46294. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46295. __decorate([
  46296. BABYLON.serialize(),
  46297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46298. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46299. __decorate([
  46300. BABYLON.serialize(),
  46301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46302. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46303. __decorate([
  46304. BABYLON.serialize(),
  46305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46306. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46307. __decorate([
  46308. BABYLON.serialize(),
  46309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46310. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46311. __decorate([
  46312. BABYLON.serialize(),
  46313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46314. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46315. __decorate([
  46316. BABYLON.serialize(),
  46317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46318. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46319. __decorate([
  46320. BABYLON.serialize(),
  46321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46322. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46323. __decorate([
  46324. BABYLON.serialize(),
  46325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46326. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46327. __decorate([
  46328. BABYLON.serialize(),
  46329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46330. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46331. __decorate([
  46332. BABYLON.serialize(),
  46333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46334. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46335. __decorate([
  46336. BABYLON.serialize(),
  46337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46338. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46339. __decorate([
  46340. BABYLON.serialize(),
  46341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46342. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46343. __decorate([
  46344. BABYLON.serialize(),
  46345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46346. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46347. __decorate([
  46348. BABYLON.serialize(),
  46349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46350. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46351. __decorate([
  46352. BABYLON.serialize(),
  46353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46354. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46355. __decorate([
  46356. BABYLON.serialize(),
  46357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46358. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46359. __decorate([
  46360. BABYLON.serialize(),
  46361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46362. ], PBRMaterial.prototype, "useParallax", void 0);
  46363. __decorate([
  46364. BABYLON.serialize(),
  46365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46366. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46367. __decorate([
  46368. BABYLON.serialize(),
  46369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46370. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46371. __decorate([
  46372. BABYLON.serialize(),
  46373. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46374. ], PBRMaterial.prototype, "disableLighting", void 0);
  46375. __decorate([
  46376. BABYLON.serialize(),
  46377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46378. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46379. __decorate([
  46380. BABYLON.serialize(),
  46381. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46382. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46383. __decorate([
  46384. BABYLON.serialize(),
  46385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46386. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46387. __decorate([
  46388. BABYLON.serialize(),
  46389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46390. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46391. __decorate([
  46392. BABYLON.serialize(),
  46393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46394. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46395. __decorate([
  46396. BABYLON.serialize(),
  46397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46398. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46399. __decorate([
  46400. BABYLON.serialize(),
  46401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46402. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46403. __decorate([
  46404. BABYLON.serializeAsTexture(),
  46405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46406. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46407. __decorate([
  46408. BABYLON.serialize(),
  46409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46410. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46411. __decorate([
  46412. BABYLON.serialize(),
  46413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46414. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46415. __decorate([
  46416. BABYLON.serialize(),
  46417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46418. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46419. __decorate([
  46420. BABYLON.serialize(),
  46421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46422. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46423. __decorate([
  46424. BABYLON.serialize(),
  46425. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46426. ], PBRMaterial.prototype, "unlit", void 0);
  46427. return PBRMaterial;
  46428. }(BABYLON.PBRBaseMaterial));
  46429. BABYLON.PBRMaterial = PBRMaterial;
  46430. })(BABYLON || (BABYLON = {}));
  46431. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46432. var BABYLON;
  46433. (function (BABYLON) {
  46434. /**
  46435. * The PBR material of BJS following the metal roughness convention.
  46436. *
  46437. * This fits to the PBR convention in the GLTF definition:
  46438. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46439. */
  46440. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46441. __extends(PBRMetallicRoughnessMaterial, _super);
  46442. /**
  46443. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46444. *
  46445. * @param name The material name
  46446. * @param scene The scene the material will be use in.
  46447. */
  46448. function PBRMetallicRoughnessMaterial(name, scene) {
  46449. var _this = _super.call(this, name, scene) || this;
  46450. _this._useRoughnessFromMetallicTextureAlpha = false;
  46451. _this._useRoughnessFromMetallicTextureGreen = true;
  46452. _this._useMetallnessFromMetallicTextureBlue = true;
  46453. _this.metallic = 1.0;
  46454. _this.roughness = 1.0;
  46455. return _this;
  46456. }
  46457. /**
  46458. * Return the currrent class name of the material.
  46459. */
  46460. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46461. return "PBRMetallicRoughnessMaterial";
  46462. };
  46463. /**
  46464. * Return the active textures of the material.
  46465. */
  46466. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46467. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46468. if (this.baseTexture) {
  46469. activeTextures.push(this.baseTexture);
  46470. }
  46471. if (this.metallicRoughnessTexture) {
  46472. activeTextures.push(this.metallicRoughnessTexture);
  46473. }
  46474. return activeTextures;
  46475. };
  46476. /**
  46477. * Checks to see if a texture is used in the material.
  46478. * @param texture - Base texture to use.
  46479. * @returns - Boolean specifying if a texture is used in the material.
  46480. */
  46481. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46482. if (_super.prototype.hasTexture.call(this, texture)) {
  46483. return true;
  46484. }
  46485. if (this.baseTexture === texture) {
  46486. return true;
  46487. }
  46488. if (this.metallicRoughnessTexture === texture) {
  46489. return true;
  46490. }
  46491. return false;
  46492. };
  46493. /**
  46494. * Makes a duplicate of the current material.
  46495. * @param name - name to use for the new material.
  46496. */
  46497. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46498. var _this = this;
  46499. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46500. clone.id = name;
  46501. clone.name = name;
  46502. return clone;
  46503. };
  46504. /**
  46505. * Serialize the material to a parsable JSON object.
  46506. */
  46507. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46508. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46509. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46510. return serializationObject;
  46511. };
  46512. /**
  46513. * Parses a JSON object correponding to the serialize function.
  46514. */
  46515. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46516. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46517. };
  46518. __decorate([
  46519. BABYLON.serializeAsColor3(),
  46520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46521. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46522. __decorate([
  46523. BABYLON.serializeAsTexture(),
  46524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46525. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46526. __decorate([
  46527. BABYLON.serialize(),
  46528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46529. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46530. __decorate([
  46531. BABYLON.serialize(),
  46532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46533. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46534. __decorate([
  46535. BABYLON.serializeAsTexture(),
  46536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46537. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46538. return PBRMetallicRoughnessMaterial;
  46539. }(BABYLON.PBRBaseSimpleMaterial));
  46540. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46541. })(BABYLON || (BABYLON = {}));
  46542. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46543. var BABYLON;
  46544. (function (BABYLON) {
  46545. /**
  46546. * The PBR material of BJS following the specular glossiness convention.
  46547. *
  46548. * This fits to the PBR convention in the GLTF definition:
  46549. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46550. */
  46551. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46552. __extends(PBRSpecularGlossinessMaterial, _super);
  46553. /**
  46554. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46555. *
  46556. * @param name The material name
  46557. * @param scene The scene the material will be use in.
  46558. */
  46559. function PBRSpecularGlossinessMaterial(name, scene) {
  46560. var _this = _super.call(this, name, scene) || this;
  46561. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46562. return _this;
  46563. }
  46564. /**
  46565. * Return the currrent class name of the material.
  46566. */
  46567. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46568. return "PBRSpecularGlossinessMaterial";
  46569. };
  46570. /**
  46571. * Return the active textures of the material.
  46572. */
  46573. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46574. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46575. if (this.diffuseTexture) {
  46576. activeTextures.push(this.diffuseTexture);
  46577. }
  46578. if (this.specularGlossinessTexture) {
  46579. activeTextures.push(this.specularGlossinessTexture);
  46580. }
  46581. return activeTextures;
  46582. };
  46583. /**
  46584. * Checks to see if a texture is used in the material.
  46585. * @param texture - Base texture to use.
  46586. * @returns - Boolean specifying if a texture is used in the material.
  46587. */
  46588. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46589. if (_super.prototype.hasTexture.call(this, texture)) {
  46590. return true;
  46591. }
  46592. if (this.diffuseTexture === texture) {
  46593. return true;
  46594. }
  46595. if (this.specularGlossinessTexture === texture) {
  46596. return true;
  46597. }
  46598. return false;
  46599. };
  46600. /**
  46601. * Makes a duplicate of the current material.
  46602. * @param name - name to use for the new material.
  46603. */
  46604. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46605. var _this = this;
  46606. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46607. clone.id = name;
  46608. clone.name = name;
  46609. return clone;
  46610. };
  46611. /**
  46612. * Serialize the material to a parsable JSON object.
  46613. */
  46614. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46615. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46616. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46617. return serializationObject;
  46618. };
  46619. /**
  46620. * Parses a JSON object correponding to the serialize function.
  46621. */
  46622. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46623. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46624. };
  46625. __decorate([
  46626. BABYLON.serializeAsColor3("diffuse"),
  46627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46628. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46629. __decorate([
  46630. BABYLON.serializeAsTexture(),
  46631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46632. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46633. __decorate([
  46634. BABYLON.serializeAsColor3("specular"),
  46635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46636. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46637. __decorate([
  46638. BABYLON.serialize(),
  46639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46640. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46641. __decorate([
  46642. BABYLON.serializeAsTexture(),
  46643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46644. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46645. return PBRSpecularGlossinessMaterial;
  46646. }(BABYLON.PBRBaseSimpleMaterial));
  46647. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46648. })(BABYLON || (BABYLON = {}));
  46649. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46650. var BABYLON;
  46651. (function (BABYLON) {
  46652. BABYLON.CameraInputTypes = {};
  46653. var CameraInputsManager = /** @class */ (function () {
  46654. function CameraInputsManager(camera) {
  46655. this.attached = {};
  46656. this.camera = camera;
  46657. this.checkInputs = function () { };
  46658. }
  46659. /**
  46660. * Add an input method to a camera.
  46661. * builtin inputs example: camera.inputs.addGamepad();
  46662. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46663. * @param input camera input method
  46664. */
  46665. CameraInputsManager.prototype.add = function (input) {
  46666. var type = input.getSimpleName();
  46667. if (this.attached[type]) {
  46668. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46669. return;
  46670. }
  46671. this.attached[type] = input;
  46672. input.camera = this.camera;
  46673. //for checkInputs, we are dynamically creating a function
  46674. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46675. if (input.checkInputs) {
  46676. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46677. }
  46678. if (this.attachedElement) {
  46679. input.attachControl(this.attachedElement);
  46680. }
  46681. };
  46682. /**
  46683. * Remove a specific input method from a camera
  46684. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46685. * @param inputToRemove camera input method
  46686. */
  46687. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46688. for (var cam in this.attached) {
  46689. var input = this.attached[cam];
  46690. if (input === inputToRemove) {
  46691. input.detachControl(this.attachedElement);
  46692. input.camera = null;
  46693. delete this.attached[cam];
  46694. this.rebuildInputCheck();
  46695. }
  46696. }
  46697. };
  46698. CameraInputsManager.prototype.removeByType = function (inputType) {
  46699. for (var cam in this.attached) {
  46700. var input = this.attached[cam];
  46701. if (input.getClassName() === inputType) {
  46702. input.detachControl(this.attachedElement);
  46703. input.camera = null;
  46704. delete this.attached[cam];
  46705. this.rebuildInputCheck();
  46706. }
  46707. }
  46708. };
  46709. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46710. var current = this.checkInputs;
  46711. return function () {
  46712. current();
  46713. fn();
  46714. };
  46715. };
  46716. CameraInputsManager.prototype.attachInput = function (input) {
  46717. if (this.attachedElement) {
  46718. input.attachControl(this.attachedElement, this.noPreventDefault);
  46719. }
  46720. };
  46721. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46722. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46723. if (this.attachedElement) {
  46724. return;
  46725. }
  46726. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46727. this.attachedElement = element;
  46728. this.noPreventDefault = noPreventDefault;
  46729. for (var cam in this.attached) {
  46730. this.attached[cam].attachControl(element, noPreventDefault);
  46731. }
  46732. };
  46733. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46734. if (disconnect === void 0) { disconnect = false; }
  46735. if (this.attachedElement !== element) {
  46736. return;
  46737. }
  46738. for (var cam in this.attached) {
  46739. this.attached[cam].detachControl(element);
  46740. if (disconnect) {
  46741. this.attached[cam].camera = null;
  46742. }
  46743. }
  46744. this.attachedElement = null;
  46745. };
  46746. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46747. this.checkInputs = function () { };
  46748. for (var cam in this.attached) {
  46749. var input = this.attached[cam];
  46750. if (input.checkInputs) {
  46751. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46752. }
  46753. }
  46754. };
  46755. /**
  46756. * Remove all attached input methods from a camera
  46757. */
  46758. CameraInputsManager.prototype.clear = function () {
  46759. if (this.attachedElement) {
  46760. this.detachElement(this.attachedElement, true);
  46761. }
  46762. this.attached = {};
  46763. this.attachedElement = null;
  46764. this.checkInputs = function () { };
  46765. };
  46766. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46767. var inputs = {};
  46768. for (var cam in this.attached) {
  46769. var input = this.attached[cam];
  46770. var res = BABYLON.SerializationHelper.Serialize(input);
  46771. inputs[input.getClassName()] = res;
  46772. }
  46773. serializedCamera.inputsmgr = inputs;
  46774. };
  46775. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46776. var parsedInputs = parsedCamera.inputsmgr;
  46777. if (parsedInputs) {
  46778. this.clear();
  46779. for (var n in parsedInputs) {
  46780. var construct = BABYLON.CameraInputTypes[n];
  46781. if (construct) {
  46782. var parsedinput = parsedInputs[n];
  46783. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46784. this.add(input);
  46785. }
  46786. }
  46787. }
  46788. else {
  46789. //2016-03-08 this part is for managing backward compatibility
  46790. for (var n in this.attached) {
  46791. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46792. if (construct) {
  46793. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46794. this.remove(this.attached[n]);
  46795. this.add(input);
  46796. }
  46797. }
  46798. }
  46799. };
  46800. return CameraInputsManager;
  46801. }());
  46802. BABYLON.CameraInputsManager = CameraInputsManager;
  46803. })(BABYLON || (BABYLON = {}));
  46804. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46805. var BABYLON;
  46806. (function (BABYLON) {
  46807. var TargetCamera = /** @class */ (function (_super) {
  46808. __extends(TargetCamera, _super);
  46809. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46810. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46811. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46812. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46813. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46814. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46815. _this.speed = 2.0;
  46816. _this.noRotationConstraint = false;
  46817. _this.lockedTarget = null;
  46818. _this._currentTarget = BABYLON.Vector3.Zero();
  46819. _this._viewMatrix = BABYLON.Matrix.Zero();
  46820. _this._camMatrix = BABYLON.Matrix.Zero();
  46821. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46822. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46823. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46824. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46825. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46826. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46827. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46828. return _this;
  46829. }
  46830. TargetCamera.prototype.getFrontPosition = function (distance) {
  46831. this.getWorldMatrix();
  46832. var direction = this.getTarget().subtract(this.position);
  46833. direction.normalize();
  46834. direction.scaleInPlace(distance);
  46835. return this.globalPosition.add(direction);
  46836. };
  46837. TargetCamera.prototype._getLockedTargetPosition = function () {
  46838. if (!this.lockedTarget) {
  46839. return null;
  46840. }
  46841. if (this.lockedTarget.absolutePosition) {
  46842. this.lockedTarget.computeWorldMatrix();
  46843. }
  46844. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46845. };
  46846. TargetCamera.prototype.storeState = function () {
  46847. this._storedPosition = this.position.clone();
  46848. this._storedRotation = this.rotation.clone();
  46849. if (this.rotationQuaternion) {
  46850. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46851. }
  46852. return _super.prototype.storeState.call(this);
  46853. };
  46854. /**
  46855. * Restored camera state. You must call storeState() first
  46856. */
  46857. TargetCamera.prototype._restoreStateValues = function () {
  46858. if (!_super.prototype._restoreStateValues.call(this)) {
  46859. return false;
  46860. }
  46861. this.position = this._storedPosition.clone();
  46862. this.rotation = this._storedRotation.clone();
  46863. if (this.rotationQuaternion) {
  46864. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46865. }
  46866. this.cameraDirection.copyFromFloats(0, 0, 0);
  46867. this.cameraRotation.copyFromFloats(0, 0);
  46868. return true;
  46869. };
  46870. // Cache
  46871. TargetCamera.prototype._initCache = function () {
  46872. _super.prototype._initCache.call(this);
  46873. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46874. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46875. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46876. };
  46877. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46878. if (!ignoreParentClass) {
  46879. _super.prototype._updateCache.call(this);
  46880. }
  46881. var lockedTargetPosition = this._getLockedTargetPosition();
  46882. if (!lockedTargetPosition) {
  46883. this._cache.lockedTarget = null;
  46884. }
  46885. else {
  46886. if (!this._cache.lockedTarget) {
  46887. this._cache.lockedTarget = lockedTargetPosition.clone();
  46888. }
  46889. else {
  46890. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46891. }
  46892. }
  46893. this._cache.rotation.copyFrom(this.rotation);
  46894. if (this.rotationQuaternion)
  46895. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46896. };
  46897. // Synchronized
  46898. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46899. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46900. return false;
  46901. }
  46902. var lockedTargetPosition = this._getLockedTargetPosition();
  46903. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46904. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46905. };
  46906. // Methods
  46907. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46908. var engine = this.getEngine();
  46909. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46910. };
  46911. // Target
  46912. TargetCamera.prototype.setTarget = function (target) {
  46913. this.upVector.normalize();
  46914. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46915. this._camMatrix.invert();
  46916. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46917. var vDir = target.subtract(this.position);
  46918. if (vDir.x >= 0.0) {
  46919. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46920. }
  46921. else {
  46922. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46923. }
  46924. this.rotation.z = 0;
  46925. if (isNaN(this.rotation.x)) {
  46926. this.rotation.x = 0;
  46927. }
  46928. if (isNaN(this.rotation.y)) {
  46929. this.rotation.y = 0;
  46930. }
  46931. if (isNaN(this.rotation.z)) {
  46932. this.rotation.z = 0;
  46933. }
  46934. if (this.rotationQuaternion) {
  46935. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46936. }
  46937. };
  46938. /**
  46939. * Return the current target position of the camera. This value is expressed in local space.
  46940. */
  46941. TargetCamera.prototype.getTarget = function () {
  46942. return this._currentTarget;
  46943. };
  46944. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46945. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46946. };
  46947. TargetCamera.prototype._updatePosition = function () {
  46948. if (this.parent) {
  46949. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46950. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46951. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46952. return;
  46953. }
  46954. this.position.addInPlace(this.cameraDirection);
  46955. };
  46956. TargetCamera.prototype._checkInputs = function () {
  46957. var needToMove = this._decideIfNeedsToMove();
  46958. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46959. // Move
  46960. if (needToMove) {
  46961. this._updatePosition();
  46962. }
  46963. // Rotate
  46964. if (needToRotate) {
  46965. this.rotation.x += this.cameraRotation.x;
  46966. this.rotation.y += this.cameraRotation.y;
  46967. //rotate, if quaternion is set and rotation was used
  46968. if (this.rotationQuaternion) {
  46969. var len = this.rotation.lengthSquared();
  46970. if (len) {
  46971. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46972. }
  46973. }
  46974. if (!this.noRotationConstraint) {
  46975. var limit = (Math.PI / 2) * 0.95;
  46976. if (this.rotation.x > limit)
  46977. this.rotation.x = limit;
  46978. if (this.rotation.x < -limit)
  46979. this.rotation.x = -limit;
  46980. }
  46981. }
  46982. // Inertia
  46983. if (needToMove) {
  46984. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46985. this.cameraDirection.x = 0;
  46986. }
  46987. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46988. this.cameraDirection.y = 0;
  46989. }
  46990. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46991. this.cameraDirection.z = 0;
  46992. }
  46993. this.cameraDirection.scaleInPlace(this.inertia);
  46994. }
  46995. if (needToRotate) {
  46996. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46997. this.cameraRotation.x = 0;
  46998. }
  46999. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47000. this.cameraRotation.y = 0;
  47001. }
  47002. this.cameraRotation.scaleInPlace(this.inertia);
  47003. }
  47004. _super.prototype._checkInputs.call(this);
  47005. };
  47006. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47007. if (this.rotationQuaternion) {
  47008. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47009. }
  47010. else {
  47011. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47012. }
  47013. //update the up vector!
  47014. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47015. };
  47016. TargetCamera.prototype._getViewMatrix = function () {
  47017. if (this.lockedTarget) {
  47018. this.setTarget(this._getLockedTargetPosition());
  47019. }
  47020. // Compute
  47021. this._updateCameraRotationMatrix();
  47022. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47023. // Computing target and final matrix
  47024. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47025. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47026. return this._viewMatrix;
  47027. };
  47028. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47029. if (this.parent) {
  47030. var parentWorldMatrix = this.parent.getWorldMatrix();
  47031. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47032. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47033. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47034. this._markSyncedWithParent();
  47035. }
  47036. else {
  47037. this._globalPosition.copyFrom(this.position);
  47038. this._globalCurrentTarget.copyFrom(target);
  47039. this._globalCurrentUpVector.copyFrom(up);
  47040. }
  47041. if (this.getScene().useRightHandedSystem) {
  47042. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47043. }
  47044. else {
  47045. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47046. }
  47047. };
  47048. /**
  47049. * @override
  47050. * Override Camera.createRigCamera
  47051. */
  47052. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47053. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47054. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47055. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47056. if (!this.rotationQuaternion) {
  47057. this.rotationQuaternion = new BABYLON.Quaternion();
  47058. }
  47059. rigCamera._cameraRigParams = {};
  47060. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47061. }
  47062. return rigCamera;
  47063. }
  47064. return null;
  47065. };
  47066. /**
  47067. * @override
  47068. * Override Camera._updateRigCameras
  47069. */
  47070. TargetCamera.prototype._updateRigCameras = function () {
  47071. var camLeft = this._rigCameras[0];
  47072. var camRight = this._rigCameras[1];
  47073. switch (this.cameraRigMode) {
  47074. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47075. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47076. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47077. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47078. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47079. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47080. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47081. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47082. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47083. camLeft.setTarget(this.getTarget());
  47084. camRight.setTarget(this.getTarget());
  47085. break;
  47086. case BABYLON.Camera.RIG_MODE_VR:
  47087. if (camLeft.rotationQuaternion) {
  47088. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47089. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47090. }
  47091. else {
  47092. camLeft.rotation.copyFrom(this.rotation);
  47093. camRight.rotation.copyFrom(this.rotation);
  47094. }
  47095. camLeft.position.copyFrom(this.position);
  47096. camRight.position.copyFrom(this.position);
  47097. break;
  47098. }
  47099. _super.prototype._updateRigCameras.call(this);
  47100. };
  47101. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47102. if (!this._rigCamTransformMatrix) {
  47103. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47104. }
  47105. var target = this.getTarget();
  47106. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47107. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47108. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47109. };
  47110. TargetCamera.prototype.getClassName = function () {
  47111. return "TargetCamera";
  47112. };
  47113. __decorate([
  47114. BABYLON.serializeAsVector3()
  47115. ], TargetCamera.prototype, "rotation", void 0);
  47116. __decorate([
  47117. BABYLON.serialize()
  47118. ], TargetCamera.prototype, "speed", void 0);
  47119. __decorate([
  47120. BABYLON.serializeAsMeshReference("lockedTargetId")
  47121. ], TargetCamera.prototype, "lockedTarget", void 0);
  47122. return TargetCamera;
  47123. }(BABYLON.Camera));
  47124. BABYLON.TargetCamera = TargetCamera;
  47125. })(BABYLON || (BABYLON = {}));
  47126. //# sourceMappingURL=babylon.targetCamera.js.map
  47127. var BABYLON;
  47128. (function (BABYLON) {
  47129. var FreeCameraMouseInput = /** @class */ (function () {
  47130. function FreeCameraMouseInput(touchEnabled) {
  47131. if (touchEnabled === void 0) { touchEnabled = true; }
  47132. this.touchEnabled = touchEnabled;
  47133. this.buttons = [0, 1, 2];
  47134. this.angularSensibility = 2000.0;
  47135. this.previousPosition = null;
  47136. }
  47137. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47138. var _this = this;
  47139. var engine = this.camera.getEngine();
  47140. if (!this._pointerInput) {
  47141. this._pointerInput = function (p, s) {
  47142. var evt = p.event;
  47143. if (engine.isInVRExclusivePointerMode) {
  47144. return;
  47145. }
  47146. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47147. return;
  47148. }
  47149. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47150. return;
  47151. }
  47152. var srcElement = (evt.srcElement || evt.target);
  47153. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47154. try {
  47155. srcElement.setPointerCapture(evt.pointerId);
  47156. }
  47157. catch (e) {
  47158. //Nothing to do with the error. Execution will continue.
  47159. }
  47160. _this.previousPosition = {
  47161. x: evt.clientX,
  47162. y: evt.clientY
  47163. };
  47164. if (!noPreventDefault) {
  47165. evt.preventDefault();
  47166. element.focus();
  47167. }
  47168. }
  47169. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47170. try {
  47171. srcElement.releasePointerCapture(evt.pointerId);
  47172. }
  47173. catch (e) {
  47174. //Nothing to do with the error.
  47175. }
  47176. _this.previousPosition = null;
  47177. if (!noPreventDefault) {
  47178. evt.preventDefault();
  47179. }
  47180. }
  47181. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47182. if (!_this.previousPosition || engine.isPointerLock) {
  47183. return;
  47184. }
  47185. var offsetX = evt.clientX - _this.previousPosition.x;
  47186. if (_this.camera.getScene().useRightHandedSystem)
  47187. offsetX *= -1;
  47188. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47189. offsetX *= -1;
  47190. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47191. var offsetY = evt.clientY - _this.previousPosition.y;
  47192. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47193. _this.previousPosition = {
  47194. x: evt.clientX,
  47195. y: evt.clientY
  47196. };
  47197. if (!noPreventDefault) {
  47198. evt.preventDefault();
  47199. }
  47200. }
  47201. };
  47202. }
  47203. this._onMouseMove = function (evt) {
  47204. if (!engine.isPointerLock) {
  47205. return;
  47206. }
  47207. if (engine.isInVRExclusivePointerMode) {
  47208. return;
  47209. }
  47210. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47211. if (_this.camera.getScene().useRightHandedSystem)
  47212. offsetX *= -1;
  47213. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47214. offsetX *= -1;
  47215. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47216. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47217. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47218. _this.previousPosition = null;
  47219. if (!noPreventDefault) {
  47220. evt.preventDefault();
  47221. }
  47222. };
  47223. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47224. element.addEventListener("mousemove", this._onMouseMove, false);
  47225. };
  47226. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47227. if (this._observer && element) {
  47228. this.camera.getScene().onPointerObservable.remove(this._observer);
  47229. if (this._onMouseMove) {
  47230. element.removeEventListener("mousemove", this._onMouseMove);
  47231. }
  47232. this._observer = null;
  47233. this._onMouseMove = null;
  47234. this.previousPosition = null;
  47235. }
  47236. };
  47237. FreeCameraMouseInput.prototype.getClassName = function () {
  47238. return "FreeCameraMouseInput";
  47239. };
  47240. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47241. return "mouse";
  47242. };
  47243. __decorate([
  47244. BABYLON.serialize()
  47245. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47246. __decorate([
  47247. BABYLON.serialize()
  47248. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47249. return FreeCameraMouseInput;
  47250. }());
  47251. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47252. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47253. })(BABYLON || (BABYLON = {}));
  47254. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47255. var BABYLON;
  47256. (function (BABYLON) {
  47257. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47258. function FreeCameraKeyboardMoveInput() {
  47259. this._keys = new Array();
  47260. this.keysUp = [38];
  47261. this.keysDown = [40];
  47262. this.keysLeft = [37];
  47263. this.keysRight = [39];
  47264. }
  47265. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47266. var _this = this;
  47267. if (this._onCanvasBlurObserver) {
  47268. return;
  47269. }
  47270. this._scene = this.camera.getScene();
  47271. this._engine = this._scene.getEngine();
  47272. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47273. _this._keys = [];
  47274. });
  47275. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47276. var evt = info.event;
  47277. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47278. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47279. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47280. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47281. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47282. var index = _this._keys.indexOf(evt.keyCode);
  47283. if (index === -1) {
  47284. _this._keys.push(evt.keyCode);
  47285. }
  47286. if (!noPreventDefault) {
  47287. evt.preventDefault();
  47288. }
  47289. }
  47290. }
  47291. else {
  47292. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47293. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47294. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47295. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47296. var index = _this._keys.indexOf(evt.keyCode);
  47297. if (index >= 0) {
  47298. _this._keys.splice(index, 1);
  47299. }
  47300. if (!noPreventDefault) {
  47301. evt.preventDefault();
  47302. }
  47303. }
  47304. }
  47305. });
  47306. };
  47307. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47308. if (this._scene) {
  47309. if (this._onKeyboardObserver) {
  47310. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47311. }
  47312. if (this._onCanvasBlurObserver) {
  47313. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47314. }
  47315. this._onKeyboardObserver = null;
  47316. this._onCanvasBlurObserver = null;
  47317. }
  47318. this._keys = [];
  47319. };
  47320. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47321. if (this._onKeyboardObserver) {
  47322. var camera = this.camera;
  47323. // Keyboard
  47324. for (var index = 0; index < this._keys.length; index++) {
  47325. var keyCode = this._keys[index];
  47326. var speed = camera._computeLocalCameraSpeed();
  47327. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47328. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47329. }
  47330. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47331. camera._localDirection.copyFromFloats(0, 0, speed);
  47332. }
  47333. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47334. camera._localDirection.copyFromFloats(speed, 0, 0);
  47335. }
  47336. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47337. camera._localDirection.copyFromFloats(0, 0, -speed);
  47338. }
  47339. if (camera.getScene().useRightHandedSystem) {
  47340. camera._localDirection.z *= -1;
  47341. }
  47342. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47343. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47344. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47345. }
  47346. }
  47347. };
  47348. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47349. return "FreeCameraKeyboardMoveInput";
  47350. };
  47351. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47352. this._keys = [];
  47353. };
  47354. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47355. return "keyboard";
  47356. };
  47357. __decorate([
  47358. BABYLON.serialize()
  47359. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47360. __decorate([
  47361. BABYLON.serialize()
  47362. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47363. __decorate([
  47364. BABYLON.serialize()
  47365. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47366. __decorate([
  47367. BABYLON.serialize()
  47368. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47369. return FreeCameraKeyboardMoveInput;
  47370. }());
  47371. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47372. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47373. })(BABYLON || (BABYLON = {}));
  47374. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47375. var BABYLON;
  47376. (function (BABYLON) {
  47377. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47378. __extends(FreeCameraInputsManager, _super);
  47379. function FreeCameraInputsManager(camera) {
  47380. return _super.call(this, camera) || this;
  47381. }
  47382. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47383. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47384. return this;
  47385. };
  47386. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47387. if (touchEnabled === void 0) { touchEnabled = true; }
  47388. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47389. return this;
  47390. };
  47391. FreeCameraInputsManager.prototype.addGamepad = function () {
  47392. this.add(new BABYLON.FreeCameraGamepadInput());
  47393. return this;
  47394. };
  47395. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47396. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47397. return this;
  47398. };
  47399. FreeCameraInputsManager.prototype.addTouch = function () {
  47400. this.add(new BABYLON.FreeCameraTouchInput());
  47401. return this;
  47402. };
  47403. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47404. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47405. return this;
  47406. };
  47407. return FreeCameraInputsManager;
  47408. }(BABYLON.CameraInputsManager));
  47409. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47410. })(BABYLON || (BABYLON = {}));
  47411. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47412. var BABYLON;
  47413. (function (BABYLON) {
  47414. var FreeCamera = /** @class */ (function (_super) {
  47415. __extends(FreeCamera, _super);
  47416. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47417. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47418. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47419. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47420. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47421. _this.checkCollisions = false;
  47422. _this.applyGravity = false;
  47423. _this._needMoveForGravity = false;
  47424. _this._oldPosition = BABYLON.Vector3.Zero();
  47425. _this._diffPosition = BABYLON.Vector3.Zero();
  47426. _this._newPosition = BABYLON.Vector3.Zero();
  47427. // Collisions
  47428. _this._collisionMask = -1;
  47429. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47430. if (collidedMesh === void 0) { collidedMesh = null; }
  47431. //TODO move this to the collision coordinator!
  47432. if (_this.getScene().workerCollisions)
  47433. newPosition.multiplyInPlace(_this._collider._radius);
  47434. var updatePosition = function (newPos) {
  47435. _this._newPosition.copyFrom(newPos);
  47436. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47437. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47438. _this.position.addInPlace(_this._diffPosition);
  47439. if (_this.onCollide && collidedMesh) {
  47440. _this.onCollide(collidedMesh);
  47441. }
  47442. }
  47443. };
  47444. updatePosition(newPosition);
  47445. };
  47446. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47447. _this.inputs.addKeyboard().addMouse();
  47448. return _this;
  47449. }
  47450. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47451. //-- begin properties for backward compatibility for inputs
  47452. /**
  47453. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47454. * Higher values reduce sensitivity.
  47455. */
  47456. get: function () {
  47457. var mouse = this.inputs.attached["mouse"];
  47458. if (mouse)
  47459. return mouse.angularSensibility;
  47460. return 0;
  47461. },
  47462. /**
  47463. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47464. * Higher values reduce sensitivity.
  47465. */
  47466. set: function (value) {
  47467. var mouse = this.inputs.attached["mouse"];
  47468. if (mouse)
  47469. mouse.angularSensibility = value;
  47470. },
  47471. enumerable: true,
  47472. configurable: true
  47473. });
  47474. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47475. get: function () {
  47476. var keyboard = this.inputs.attached["keyboard"];
  47477. if (keyboard)
  47478. return keyboard.keysUp;
  47479. return [];
  47480. },
  47481. set: function (value) {
  47482. var keyboard = this.inputs.attached["keyboard"];
  47483. if (keyboard)
  47484. keyboard.keysUp = value;
  47485. },
  47486. enumerable: true,
  47487. configurable: true
  47488. });
  47489. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47490. get: function () {
  47491. var keyboard = this.inputs.attached["keyboard"];
  47492. if (keyboard)
  47493. return keyboard.keysDown;
  47494. return [];
  47495. },
  47496. set: function (value) {
  47497. var keyboard = this.inputs.attached["keyboard"];
  47498. if (keyboard)
  47499. keyboard.keysDown = value;
  47500. },
  47501. enumerable: true,
  47502. configurable: true
  47503. });
  47504. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47505. get: function () {
  47506. var keyboard = this.inputs.attached["keyboard"];
  47507. if (keyboard)
  47508. return keyboard.keysLeft;
  47509. return [];
  47510. },
  47511. set: function (value) {
  47512. var keyboard = this.inputs.attached["keyboard"];
  47513. if (keyboard)
  47514. keyboard.keysLeft = value;
  47515. },
  47516. enumerable: true,
  47517. configurable: true
  47518. });
  47519. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47520. get: function () {
  47521. var keyboard = this.inputs.attached["keyboard"];
  47522. if (keyboard)
  47523. return keyboard.keysRight;
  47524. return [];
  47525. },
  47526. set: function (value) {
  47527. var keyboard = this.inputs.attached["keyboard"];
  47528. if (keyboard)
  47529. keyboard.keysRight = value;
  47530. },
  47531. enumerable: true,
  47532. configurable: true
  47533. });
  47534. // Controls
  47535. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47536. this.inputs.attachElement(element, noPreventDefault);
  47537. };
  47538. FreeCamera.prototype.detachControl = function (element) {
  47539. this.inputs.detachElement(element);
  47540. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47541. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47542. };
  47543. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47544. get: function () {
  47545. return this._collisionMask;
  47546. },
  47547. set: function (mask) {
  47548. this._collisionMask = !isNaN(mask) ? mask : -1;
  47549. },
  47550. enumerable: true,
  47551. configurable: true
  47552. });
  47553. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47554. var globalPosition;
  47555. if (this.parent) {
  47556. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47557. }
  47558. else {
  47559. globalPosition = this.position;
  47560. }
  47561. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47562. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47563. if (!this._collider) {
  47564. this._collider = new BABYLON.Collider();
  47565. }
  47566. this._collider._radius = this.ellipsoid;
  47567. this._collider.collisionMask = this._collisionMask;
  47568. //no need for clone, as long as gravity is not on.
  47569. var actualDisplacement = displacement;
  47570. //add gravity to the direction to prevent the dual-collision checking
  47571. if (this.applyGravity) {
  47572. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47573. actualDisplacement = displacement.add(this.getScene().gravity);
  47574. }
  47575. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47576. };
  47577. FreeCamera.prototype._checkInputs = function () {
  47578. if (!this._localDirection) {
  47579. this._localDirection = BABYLON.Vector3.Zero();
  47580. this._transformedDirection = BABYLON.Vector3.Zero();
  47581. }
  47582. this.inputs.checkInputs();
  47583. _super.prototype._checkInputs.call(this);
  47584. };
  47585. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47586. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47587. };
  47588. FreeCamera.prototype._updatePosition = function () {
  47589. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47590. this._collideWithWorld(this.cameraDirection);
  47591. }
  47592. else {
  47593. _super.prototype._updatePosition.call(this);
  47594. }
  47595. };
  47596. FreeCamera.prototype.dispose = function () {
  47597. this.inputs.clear();
  47598. _super.prototype.dispose.call(this);
  47599. };
  47600. FreeCamera.prototype.getClassName = function () {
  47601. return "FreeCamera";
  47602. };
  47603. __decorate([
  47604. BABYLON.serializeAsVector3()
  47605. ], FreeCamera.prototype, "ellipsoid", void 0);
  47606. __decorate([
  47607. BABYLON.serializeAsVector3()
  47608. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47609. __decorate([
  47610. BABYLON.serialize()
  47611. ], FreeCamera.prototype, "checkCollisions", void 0);
  47612. __decorate([
  47613. BABYLON.serialize()
  47614. ], FreeCamera.prototype, "applyGravity", void 0);
  47615. return FreeCamera;
  47616. }(BABYLON.TargetCamera));
  47617. BABYLON.FreeCamera = FreeCamera;
  47618. })(BABYLON || (BABYLON = {}));
  47619. //# sourceMappingURL=babylon.freeCamera.js.map
  47620. var BABYLON;
  47621. (function (BABYLON) {
  47622. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47623. function ArcRotateCameraKeyboardMoveInput() {
  47624. this._keys = new Array();
  47625. this.keysUp = [38];
  47626. this.keysDown = [40];
  47627. this.keysLeft = [37];
  47628. this.keysRight = [39];
  47629. this.keysReset = [220];
  47630. this.panningSensibility = 50.0;
  47631. this.zoomingSensibility = 25.0;
  47632. this.useAltToZoom = true;
  47633. }
  47634. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47635. var _this = this;
  47636. if (this._onCanvasBlurObserver) {
  47637. return;
  47638. }
  47639. this._scene = this.camera.getScene();
  47640. this._engine = this._scene.getEngine();
  47641. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47642. _this._keys = [];
  47643. });
  47644. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47645. var evt = info.event;
  47646. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47647. _this._ctrlPressed = evt.ctrlKey;
  47648. _this._altPressed = evt.altKey;
  47649. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47650. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47651. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47652. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47653. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47654. var index = _this._keys.indexOf(evt.keyCode);
  47655. if (index === -1) {
  47656. _this._keys.push(evt.keyCode);
  47657. }
  47658. if (evt.preventDefault) {
  47659. if (!noPreventDefault) {
  47660. evt.preventDefault();
  47661. }
  47662. }
  47663. }
  47664. }
  47665. else {
  47666. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47667. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47668. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47669. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47670. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47671. var index = _this._keys.indexOf(evt.keyCode);
  47672. if (index >= 0) {
  47673. _this._keys.splice(index, 1);
  47674. }
  47675. if (evt.preventDefault) {
  47676. if (!noPreventDefault) {
  47677. evt.preventDefault();
  47678. }
  47679. }
  47680. }
  47681. }
  47682. });
  47683. };
  47684. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47685. if (this._scene) {
  47686. if (this._onKeyboardObserver) {
  47687. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47688. }
  47689. if (this._onCanvasBlurObserver) {
  47690. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47691. }
  47692. this._onKeyboardObserver = null;
  47693. this._onCanvasBlurObserver = null;
  47694. }
  47695. this._keys = [];
  47696. };
  47697. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47698. if (this._onKeyboardObserver) {
  47699. var camera = this.camera;
  47700. for (var index = 0; index < this._keys.length; index++) {
  47701. var keyCode = this._keys[index];
  47702. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47703. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47704. camera.inertialPanningX -= 1 / this.panningSensibility;
  47705. }
  47706. else {
  47707. camera.inertialAlphaOffset -= 0.01;
  47708. }
  47709. }
  47710. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47711. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47712. camera.inertialPanningY += 1 / this.panningSensibility;
  47713. }
  47714. else if (this._altPressed && this.useAltToZoom) {
  47715. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47716. }
  47717. else {
  47718. camera.inertialBetaOffset -= 0.01;
  47719. }
  47720. }
  47721. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47722. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47723. camera.inertialPanningX += 1 / this.panningSensibility;
  47724. }
  47725. else {
  47726. camera.inertialAlphaOffset += 0.01;
  47727. }
  47728. }
  47729. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47730. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47731. camera.inertialPanningY -= 1 / this.panningSensibility;
  47732. }
  47733. else if (this._altPressed && this.useAltToZoom) {
  47734. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47735. }
  47736. else {
  47737. camera.inertialBetaOffset += 0.01;
  47738. }
  47739. }
  47740. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47741. camera.restoreState();
  47742. }
  47743. }
  47744. }
  47745. };
  47746. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47747. return "ArcRotateCameraKeyboardMoveInput";
  47748. };
  47749. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47750. return "keyboard";
  47751. };
  47752. __decorate([
  47753. BABYLON.serialize()
  47754. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47755. __decorate([
  47756. BABYLON.serialize()
  47757. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47758. __decorate([
  47759. BABYLON.serialize()
  47760. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47761. __decorate([
  47762. BABYLON.serialize()
  47763. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47764. __decorate([
  47765. BABYLON.serialize()
  47766. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47767. __decorate([
  47768. BABYLON.serialize()
  47769. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47770. __decorate([
  47771. BABYLON.serialize()
  47772. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47773. __decorate([
  47774. BABYLON.serialize()
  47775. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47776. return ArcRotateCameraKeyboardMoveInput;
  47777. }());
  47778. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47779. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47780. })(BABYLON || (BABYLON = {}));
  47781. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47782. var BABYLON;
  47783. (function (BABYLON) {
  47784. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47785. function ArcRotateCameraMouseWheelInput() {
  47786. this.wheelPrecision = 3.0;
  47787. /**
  47788. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47789. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47790. */
  47791. this.wheelDeltaPercentage = 0;
  47792. }
  47793. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47794. var _this = this;
  47795. this._wheel = function (p, s) {
  47796. //sanity check - this should be a PointerWheel event.
  47797. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47798. return;
  47799. var event = p.event;
  47800. var delta = 0;
  47801. if (event.wheelDelta) {
  47802. if (_this.wheelDeltaPercentage) {
  47803. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47804. if (event.wheelDelta > 0) {
  47805. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47806. }
  47807. else {
  47808. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47809. }
  47810. }
  47811. else {
  47812. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47813. }
  47814. }
  47815. else if (event.detail) {
  47816. delta = -event.detail / _this.wheelPrecision;
  47817. }
  47818. if (delta)
  47819. _this.camera.inertialRadiusOffset += delta;
  47820. if (event.preventDefault) {
  47821. if (!noPreventDefault) {
  47822. event.preventDefault();
  47823. }
  47824. }
  47825. };
  47826. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47827. };
  47828. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47829. if (this._observer && element) {
  47830. this.camera.getScene().onPointerObservable.remove(this._observer);
  47831. this._observer = null;
  47832. this._wheel = null;
  47833. }
  47834. };
  47835. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47836. return "ArcRotateCameraMouseWheelInput";
  47837. };
  47838. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47839. return "mousewheel";
  47840. };
  47841. __decorate([
  47842. BABYLON.serialize()
  47843. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47844. __decorate([
  47845. BABYLON.serialize()
  47846. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47847. return ArcRotateCameraMouseWheelInput;
  47848. }());
  47849. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47850. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47851. })(BABYLON || (BABYLON = {}));
  47852. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47853. var BABYLON;
  47854. (function (BABYLON) {
  47855. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47856. function ArcRotateCameraPointersInput() {
  47857. this.buttons = [0, 1, 2];
  47858. this.angularSensibilityX = 1000.0;
  47859. this.angularSensibilityY = 1000.0;
  47860. this.pinchPrecision = 12.0;
  47861. /**
  47862. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47863. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47864. */
  47865. this.pinchDeltaPercentage = 0;
  47866. this.panningSensibility = 1000.0;
  47867. this.multiTouchPanning = true;
  47868. this.multiTouchPanAndZoom = true;
  47869. this._isPanClick = false;
  47870. this.pinchInwards = true;
  47871. }
  47872. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47873. var _this = this;
  47874. var engine = this.camera.getEngine();
  47875. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47876. var pointA = null;
  47877. var pointB = null;
  47878. var previousPinchSquaredDistance = 0;
  47879. var initialDistance = 0;
  47880. var twoFingerActivityCount = 0;
  47881. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47882. this._pointerInput = function (p, s) {
  47883. var evt = p.event;
  47884. var isTouch = p.event.pointerType === "touch";
  47885. if (engine.isInVRExclusivePointerMode) {
  47886. return;
  47887. }
  47888. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47889. return;
  47890. }
  47891. var srcElement = (evt.srcElement || evt.target);
  47892. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47893. try {
  47894. srcElement.setPointerCapture(evt.pointerId);
  47895. }
  47896. catch (e) {
  47897. //Nothing to do with the error. Execution will continue.
  47898. }
  47899. // Manage panning with pan button click
  47900. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47901. // manage pointers
  47902. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47903. if (pointA === null) {
  47904. pointA = cacheSoloPointer;
  47905. }
  47906. else if (pointB === null) {
  47907. pointB = cacheSoloPointer;
  47908. }
  47909. if (!noPreventDefault) {
  47910. evt.preventDefault();
  47911. element.focus();
  47912. }
  47913. }
  47914. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47915. _this.camera.restoreState();
  47916. }
  47917. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47918. try {
  47919. srcElement.releasePointerCapture(evt.pointerId);
  47920. }
  47921. catch (e) {
  47922. //Nothing to do with the error.
  47923. }
  47924. cacheSoloPointer = null;
  47925. previousPinchSquaredDistance = 0;
  47926. previousMultiTouchPanPosition.isPaning = false;
  47927. previousMultiTouchPanPosition.isPinching = false;
  47928. twoFingerActivityCount = 0;
  47929. initialDistance = 0;
  47930. if (!isTouch) {
  47931. pointB = null; // Mouse and pen are mono pointer
  47932. }
  47933. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47934. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47935. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47936. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47937. if (engine._badOS) {
  47938. pointA = pointB = null;
  47939. }
  47940. else {
  47941. //only remove the impacted pointer in case of multitouch allowing on most
  47942. //platforms switching from rotate to zoom and pan seamlessly.
  47943. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47944. pointA = pointB;
  47945. pointB = null;
  47946. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47947. }
  47948. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47949. pointB = null;
  47950. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47951. }
  47952. else {
  47953. pointA = pointB = null;
  47954. }
  47955. }
  47956. if (!noPreventDefault) {
  47957. evt.preventDefault();
  47958. }
  47959. }
  47960. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47961. if (!noPreventDefault) {
  47962. evt.preventDefault();
  47963. }
  47964. // One button down
  47965. if (pointA && pointB === null && cacheSoloPointer) {
  47966. if (_this.panningSensibility !== 0 &&
  47967. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47968. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47969. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47970. }
  47971. else {
  47972. var offsetX = evt.clientX - cacheSoloPointer.x;
  47973. var offsetY = evt.clientY - cacheSoloPointer.y;
  47974. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47975. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47976. }
  47977. cacheSoloPointer.x = evt.clientX;
  47978. cacheSoloPointer.y = evt.clientY;
  47979. }
  47980. // Two buttons down: pinch/pan
  47981. else if (pointA && pointB) {
  47982. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47983. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47984. ed.x = evt.clientX;
  47985. ed.y = evt.clientY;
  47986. var direction = _this.pinchInwards ? 1 : -1;
  47987. var distX = pointA.x - pointB.x;
  47988. var distY = pointA.y - pointB.y;
  47989. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47990. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47991. if (previousPinchSquaredDistance === 0) {
  47992. initialDistance = pinchDistance;
  47993. previousPinchSquaredDistance = pinchSquaredDistance;
  47994. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47995. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47996. return;
  47997. }
  47998. if (_this.multiTouchPanAndZoom) {
  47999. if (_this.pinchDeltaPercentage) {
  48000. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48001. }
  48002. else {
  48003. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48004. (_this.pinchPrecision *
  48005. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48006. direction);
  48007. }
  48008. if (_this.panningSensibility !== 0) {
  48009. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48010. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48011. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48012. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48013. previousMultiTouchPanPosition.x = pointersCenterX;
  48014. previousMultiTouchPanPosition.y = pointersCenterY;
  48015. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48016. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48017. }
  48018. }
  48019. else {
  48020. twoFingerActivityCount++;
  48021. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48022. if (_this.pinchDeltaPercentage) {
  48023. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48024. }
  48025. else {
  48026. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48027. (_this.pinchPrecision *
  48028. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48029. direction);
  48030. }
  48031. previousMultiTouchPanPosition.isPaning = false;
  48032. previousMultiTouchPanPosition.isPinching = true;
  48033. }
  48034. else {
  48035. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48036. if (!previousMultiTouchPanPosition.isPaning) {
  48037. previousMultiTouchPanPosition.isPaning = true;
  48038. previousMultiTouchPanPosition.isPinching = false;
  48039. previousMultiTouchPanPosition.x = ed.x;
  48040. previousMultiTouchPanPosition.y = ed.y;
  48041. return;
  48042. }
  48043. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48044. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48045. }
  48046. }
  48047. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48048. previousMultiTouchPanPosition.x = ed.x;
  48049. previousMultiTouchPanPosition.y = ed.y;
  48050. }
  48051. }
  48052. previousPinchSquaredDistance = pinchSquaredDistance;
  48053. }
  48054. }
  48055. };
  48056. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48057. this._onContextMenu = function (evt) {
  48058. evt.preventDefault();
  48059. };
  48060. if (!this.camera._useCtrlForPanning) {
  48061. element.addEventListener("contextmenu", this._onContextMenu, false);
  48062. }
  48063. this._onLostFocus = function () {
  48064. //this._keys = [];
  48065. pointA = pointB = null;
  48066. previousPinchSquaredDistance = 0;
  48067. previousMultiTouchPanPosition.isPaning = false;
  48068. previousMultiTouchPanPosition.isPinching = false;
  48069. twoFingerActivityCount = 0;
  48070. cacheSoloPointer = null;
  48071. initialDistance = 0;
  48072. };
  48073. this._onMouseMove = function (evt) {
  48074. if (!engine.isPointerLock) {
  48075. return;
  48076. }
  48077. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48078. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48079. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48080. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48081. if (!noPreventDefault) {
  48082. evt.preventDefault();
  48083. }
  48084. };
  48085. this._onGestureStart = function (e) {
  48086. if (window.MSGesture === undefined) {
  48087. return;
  48088. }
  48089. if (!_this._MSGestureHandler) {
  48090. _this._MSGestureHandler = new MSGesture();
  48091. _this._MSGestureHandler.target = element;
  48092. }
  48093. _this._MSGestureHandler.addPointer(e.pointerId);
  48094. };
  48095. this._onGesture = function (e) {
  48096. _this.camera.radius *= e.scale;
  48097. if (e.preventDefault) {
  48098. if (!noPreventDefault) {
  48099. e.stopPropagation();
  48100. e.preventDefault();
  48101. }
  48102. }
  48103. };
  48104. element.addEventListener("mousemove", this._onMouseMove, false);
  48105. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48106. element.addEventListener("MSGestureChange", this._onGesture, false);
  48107. BABYLON.Tools.RegisterTopRootEvents([
  48108. { name: "blur", handler: this._onLostFocus }
  48109. ]);
  48110. };
  48111. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48112. if (this._onLostFocus) {
  48113. BABYLON.Tools.UnregisterTopRootEvents([
  48114. { name: "blur", handler: this._onLostFocus }
  48115. ]);
  48116. }
  48117. if (element && this._observer) {
  48118. this.camera.getScene().onPointerObservable.remove(this._observer);
  48119. this._observer = null;
  48120. if (this._onContextMenu) {
  48121. element.removeEventListener("contextmenu", this._onContextMenu);
  48122. }
  48123. if (this._onMouseMove) {
  48124. element.removeEventListener("mousemove", this._onMouseMove);
  48125. }
  48126. if (this._onGestureStart) {
  48127. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48128. }
  48129. if (this._onGesture) {
  48130. element.removeEventListener("MSGestureChange", this._onGesture);
  48131. }
  48132. this._isPanClick = false;
  48133. this.pinchInwards = true;
  48134. this._onMouseMove = null;
  48135. this._onGestureStart = null;
  48136. this._onGesture = null;
  48137. this._MSGestureHandler = null;
  48138. this._onLostFocus = null;
  48139. this._onContextMenu = null;
  48140. }
  48141. };
  48142. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48143. return "ArcRotateCameraPointersInput";
  48144. };
  48145. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48146. return "pointers";
  48147. };
  48148. __decorate([
  48149. BABYLON.serialize()
  48150. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48151. __decorate([
  48152. BABYLON.serialize()
  48153. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48154. __decorate([
  48155. BABYLON.serialize()
  48156. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48157. __decorate([
  48158. BABYLON.serialize()
  48159. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48160. __decorate([
  48161. BABYLON.serialize()
  48162. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48163. __decorate([
  48164. BABYLON.serialize()
  48165. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48166. __decorate([
  48167. BABYLON.serialize()
  48168. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48169. __decorate([
  48170. BABYLON.serialize()
  48171. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48172. return ArcRotateCameraPointersInput;
  48173. }());
  48174. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48175. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48176. })(BABYLON || (BABYLON = {}));
  48177. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48178. var BABYLON;
  48179. (function (BABYLON) {
  48180. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48181. __extends(ArcRotateCameraInputsManager, _super);
  48182. function ArcRotateCameraInputsManager(camera) {
  48183. return _super.call(this, camera) || this;
  48184. }
  48185. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48186. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48187. return this;
  48188. };
  48189. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48190. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48191. return this;
  48192. };
  48193. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48194. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48195. return this;
  48196. };
  48197. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48198. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48199. return this;
  48200. };
  48201. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48202. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48203. return this;
  48204. };
  48205. return ArcRotateCameraInputsManager;
  48206. }(BABYLON.CameraInputsManager));
  48207. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48208. })(BABYLON || (BABYLON = {}));
  48209. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48210. var BABYLON;
  48211. (function (BABYLON) {
  48212. var ArcRotateCamera = /** @class */ (function (_super) {
  48213. __extends(ArcRotateCamera, _super);
  48214. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48215. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48216. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48217. _this.inertialAlphaOffset = 0;
  48218. _this.inertialBetaOffset = 0;
  48219. _this.inertialRadiusOffset = 0;
  48220. _this.lowerAlphaLimit = null;
  48221. _this.upperAlphaLimit = null;
  48222. _this.lowerBetaLimit = 0.01;
  48223. _this.upperBetaLimit = Math.PI;
  48224. _this.lowerRadiusLimit = null;
  48225. _this.upperRadiusLimit = null;
  48226. _this.inertialPanningX = 0;
  48227. _this.inertialPanningY = 0;
  48228. _this.pinchToPanMaxDistance = 20;
  48229. _this.panningDistanceLimit = null;
  48230. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48231. _this.panningInertia = 0.9;
  48232. //-- end properties for backward compatibility for inputs
  48233. _this.zoomOnFactor = 1;
  48234. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48235. _this.allowUpsideDown = true;
  48236. _this._viewMatrix = new BABYLON.Matrix();
  48237. // Panning
  48238. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48239. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48240. _this.checkCollisions = false;
  48241. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48242. _this._previousPosition = BABYLON.Vector3.Zero();
  48243. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48244. _this._newPosition = BABYLON.Vector3.Zero();
  48245. _this._computationVector = BABYLON.Vector3.Zero();
  48246. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48247. if (collidedMesh === void 0) { collidedMesh = null; }
  48248. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48249. newPosition.multiplyInPlace(_this._collider._radius);
  48250. }
  48251. if (!collidedMesh) {
  48252. _this._previousPosition.copyFrom(_this.position);
  48253. }
  48254. else {
  48255. _this.setPosition(newPosition);
  48256. if (_this.onCollide) {
  48257. _this.onCollide(collidedMesh);
  48258. }
  48259. }
  48260. // Recompute because of constraints
  48261. var cosa = Math.cos(_this.alpha);
  48262. var sina = Math.sin(_this.alpha);
  48263. var cosb = Math.cos(_this.beta);
  48264. var sinb = Math.sin(_this.beta);
  48265. if (sinb === 0) {
  48266. sinb = 0.0001;
  48267. }
  48268. var target = _this._getTargetPosition();
  48269. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48270. target.addToRef(_this._computationVector, _this._newPosition);
  48271. _this.position.copyFrom(_this._newPosition);
  48272. var up = _this.upVector;
  48273. if (_this.allowUpsideDown && _this.beta < 0) {
  48274. up = up.clone();
  48275. up = up.negate();
  48276. }
  48277. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48278. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48279. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48280. _this._collisionTriggered = false;
  48281. };
  48282. _this._target = BABYLON.Vector3.Zero();
  48283. if (target) {
  48284. _this.setTarget(target);
  48285. }
  48286. _this.alpha = alpha;
  48287. _this.beta = beta;
  48288. _this.radius = radius;
  48289. _this.getViewMatrix();
  48290. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48291. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48292. return _this;
  48293. }
  48294. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48295. get: function () {
  48296. return this._target;
  48297. },
  48298. set: function (value) {
  48299. this.setTarget(value);
  48300. },
  48301. enumerable: true,
  48302. configurable: true
  48303. });
  48304. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48305. //-- begin properties for backward compatibility for inputs
  48306. get: function () {
  48307. var pointers = this.inputs.attached["pointers"];
  48308. if (pointers)
  48309. return pointers.angularSensibilityX;
  48310. return 0;
  48311. },
  48312. set: function (value) {
  48313. var pointers = this.inputs.attached["pointers"];
  48314. if (pointers) {
  48315. pointers.angularSensibilityX = value;
  48316. }
  48317. },
  48318. enumerable: true,
  48319. configurable: true
  48320. });
  48321. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48322. get: function () {
  48323. var pointers = this.inputs.attached["pointers"];
  48324. if (pointers)
  48325. return pointers.angularSensibilityY;
  48326. return 0;
  48327. },
  48328. set: function (value) {
  48329. var pointers = this.inputs.attached["pointers"];
  48330. if (pointers) {
  48331. pointers.angularSensibilityY = value;
  48332. }
  48333. },
  48334. enumerable: true,
  48335. configurable: true
  48336. });
  48337. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48338. get: function () {
  48339. var pointers = this.inputs.attached["pointers"];
  48340. if (pointers)
  48341. return pointers.pinchPrecision;
  48342. return 0;
  48343. },
  48344. set: function (value) {
  48345. var pointers = this.inputs.attached["pointers"];
  48346. if (pointers) {
  48347. pointers.pinchPrecision = value;
  48348. }
  48349. },
  48350. enumerable: true,
  48351. configurable: true
  48352. });
  48353. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48354. get: function () {
  48355. var pointers = this.inputs.attached["pointers"];
  48356. if (pointers)
  48357. return pointers.pinchDeltaPercentage;
  48358. return 0;
  48359. },
  48360. set: function (value) {
  48361. var pointers = this.inputs.attached["pointers"];
  48362. if (pointers) {
  48363. pointers.pinchDeltaPercentage = value;
  48364. }
  48365. },
  48366. enumerable: true,
  48367. configurable: true
  48368. });
  48369. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48370. get: function () {
  48371. var pointers = this.inputs.attached["pointers"];
  48372. if (pointers)
  48373. return pointers.panningSensibility;
  48374. return 0;
  48375. },
  48376. set: function (value) {
  48377. var pointers = this.inputs.attached["pointers"];
  48378. if (pointers) {
  48379. pointers.panningSensibility = value;
  48380. }
  48381. },
  48382. enumerable: true,
  48383. configurable: true
  48384. });
  48385. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48386. get: function () {
  48387. var keyboard = this.inputs.attached["keyboard"];
  48388. if (keyboard)
  48389. return keyboard.keysUp;
  48390. return [];
  48391. },
  48392. set: function (value) {
  48393. var keyboard = this.inputs.attached["keyboard"];
  48394. if (keyboard)
  48395. keyboard.keysUp = value;
  48396. },
  48397. enumerable: true,
  48398. configurable: true
  48399. });
  48400. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48401. get: function () {
  48402. var keyboard = this.inputs.attached["keyboard"];
  48403. if (keyboard)
  48404. return keyboard.keysDown;
  48405. return [];
  48406. },
  48407. set: function (value) {
  48408. var keyboard = this.inputs.attached["keyboard"];
  48409. if (keyboard)
  48410. keyboard.keysDown = value;
  48411. },
  48412. enumerable: true,
  48413. configurable: true
  48414. });
  48415. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  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. get: function () {
  48432. var keyboard = this.inputs.attached["keyboard"];
  48433. if (keyboard)
  48434. return keyboard.keysRight;
  48435. return [];
  48436. },
  48437. set: function (value) {
  48438. var keyboard = this.inputs.attached["keyboard"];
  48439. if (keyboard)
  48440. keyboard.keysRight = value;
  48441. },
  48442. enumerable: true,
  48443. configurable: true
  48444. });
  48445. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48446. get: function () {
  48447. var mousewheel = this.inputs.attached["mousewheel"];
  48448. if (mousewheel)
  48449. return mousewheel.wheelPrecision;
  48450. return 0;
  48451. },
  48452. set: function (value) {
  48453. var mousewheel = this.inputs.attached["mousewheel"];
  48454. if (mousewheel)
  48455. mousewheel.wheelPrecision = value;
  48456. },
  48457. enumerable: true,
  48458. configurable: true
  48459. });
  48460. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48461. get: function () {
  48462. var mousewheel = this.inputs.attached["mousewheel"];
  48463. if (mousewheel)
  48464. return mousewheel.wheelDeltaPercentage;
  48465. return 0;
  48466. },
  48467. set: function (value) {
  48468. var mousewheel = this.inputs.attached["mousewheel"];
  48469. if (mousewheel)
  48470. mousewheel.wheelDeltaPercentage = value;
  48471. },
  48472. enumerable: true,
  48473. configurable: true
  48474. });
  48475. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48476. get: function () {
  48477. return this._bouncingBehavior;
  48478. },
  48479. enumerable: true,
  48480. configurable: true
  48481. });
  48482. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48483. get: function () {
  48484. return this._bouncingBehavior != null;
  48485. },
  48486. set: function (value) {
  48487. if (value === this.useBouncingBehavior) {
  48488. return;
  48489. }
  48490. if (value) {
  48491. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48492. this.addBehavior(this._bouncingBehavior);
  48493. }
  48494. else if (this._bouncingBehavior) {
  48495. this.removeBehavior(this._bouncingBehavior);
  48496. this._bouncingBehavior = null;
  48497. }
  48498. },
  48499. enumerable: true,
  48500. configurable: true
  48501. });
  48502. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48503. get: function () {
  48504. return this._framingBehavior;
  48505. },
  48506. enumerable: true,
  48507. configurable: true
  48508. });
  48509. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48510. get: function () {
  48511. return this._framingBehavior != null;
  48512. },
  48513. set: function (value) {
  48514. if (value === this.useFramingBehavior) {
  48515. return;
  48516. }
  48517. if (value) {
  48518. this._framingBehavior = new BABYLON.FramingBehavior();
  48519. this.addBehavior(this._framingBehavior);
  48520. }
  48521. else if (this._framingBehavior) {
  48522. this.removeBehavior(this._framingBehavior);
  48523. this._framingBehavior = null;
  48524. }
  48525. },
  48526. enumerable: true,
  48527. configurable: true
  48528. });
  48529. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48530. get: function () {
  48531. return this._autoRotationBehavior;
  48532. },
  48533. enumerable: true,
  48534. configurable: true
  48535. });
  48536. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48537. get: function () {
  48538. return this._autoRotationBehavior != null;
  48539. },
  48540. set: function (value) {
  48541. if (value === this.useAutoRotationBehavior) {
  48542. return;
  48543. }
  48544. if (value) {
  48545. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48546. this.addBehavior(this._autoRotationBehavior);
  48547. }
  48548. else if (this._autoRotationBehavior) {
  48549. this.removeBehavior(this._autoRotationBehavior);
  48550. this._autoRotationBehavior = null;
  48551. }
  48552. },
  48553. enumerable: true,
  48554. configurable: true
  48555. });
  48556. // Cache
  48557. ArcRotateCamera.prototype._initCache = function () {
  48558. _super.prototype._initCache.call(this);
  48559. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48560. this._cache.alpha = undefined;
  48561. this._cache.beta = undefined;
  48562. this._cache.radius = undefined;
  48563. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48564. };
  48565. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48566. if (!ignoreParentClass) {
  48567. _super.prototype._updateCache.call(this);
  48568. }
  48569. this._cache._target.copyFrom(this._getTargetPosition());
  48570. this._cache.alpha = this.alpha;
  48571. this._cache.beta = this.beta;
  48572. this._cache.radius = this.radius;
  48573. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48574. };
  48575. ArcRotateCamera.prototype._getTargetPosition = function () {
  48576. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48577. var pos = this._targetHost.getAbsolutePosition();
  48578. if (this._targetBoundingCenter) {
  48579. pos.addToRef(this._targetBoundingCenter, this._target);
  48580. }
  48581. else {
  48582. this._target.copyFrom(pos);
  48583. }
  48584. }
  48585. var lockedTargetPosition = this._getLockedTargetPosition();
  48586. if (lockedTargetPosition) {
  48587. return lockedTargetPosition;
  48588. }
  48589. return this._target;
  48590. };
  48591. ArcRotateCamera.prototype.storeState = function () {
  48592. this._storedAlpha = this.alpha;
  48593. this._storedBeta = this.beta;
  48594. this._storedRadius = this.radius;
  48595. this._storedTarget = this._getTargetPosition().clone();
  48596. return _super.prototype.storeState.call(this);
  48597. };
  48598. /**
  48599. * Restored camera state. You must call storeState() first
  48600. */
  48601. ArcRotateCamera.prototype._restoreStateValues = function () {
  48602. if (!_super.prototype._restoreStateValues.call(this)) {
  48603. return false;
  48604. }
  48605. this.alpha = this._storedAlpha;
  48606. this.beta = this._storedBeta;
  48607. this.radius = this._storedRadius;
  48608. this.setTarget(this._storedTarget.clone());
  48609. this.inertialAlphaOffset = 0;
  48610. this.inertialBetaOffset = 0;
  48611. this.inertialRadiusOffset = 0;
  48612. this.inertialPanningX = 0;
  48613. this.inertialPanningY = 0;
  48614. return true;
  48615. };
  48616. // Synchronized
  48617. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48618. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48619. return false;
  48620. return this._cache._target.equals(this._getTargetPosition())
  48621. && this._cache.alpha === this.alpha
  48622. && this._cache.beta === this.beta
  48623. && this._cache.radius === this.radius
  48624. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48625. };
  48626. // Methods
  48627. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48628. var _this = this;
  48629. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48630. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48631. this._useCtrlForPanning = useCtrlForPanning;
  48632. this._panningMouseButton = panningMouseButton;
  48633. this.inputs.attachElement(element, noPreventDefault);
  48634. this._reset = function () {
  48635. _this.inertialAlphaOffset = 0;
  48636. _this.inertialBetaOffset = 0;
  48637. _this.inertialRadiusOffset = 0;
  48638. _this.inertialPanningX = 0;
  48639. _this.inertialPanningY = 0;
  48640. };
  48641. };
  48642. ArcRotateCamera.prototype.detachControl = function (element) {
  48643. this.inputs.detachElement(element);
  48644. if (this._reset) {
  48645. this._reset();
  48646. }
  48647. };
  48648. ArcRotateCamera.prototype._checkInputs = function () {
  48649. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48650. if (this._collisionTriggered) {
  48651. return;
  48652. }
  48653. this.inputs.checkInputs();
  48654. // Inertia
  48655. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48656. var inertialAlphaOffset = this.inertialAlphaOffset;
  48657. if (this.beta <= 0)
  48658. inertialAlphaOffset *= -1;
  48659. if (this.getScene().useRightHandedSystem)
  48660. inertialAlphaOffset *= -1;
  48661. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48662. inertialAlphaOffset *= -1;
  48663. this.alpha += inertialAlphaOffset;
  48664. this.beta += this.inertialBetaOffset;
  48665. this.radius -= this.inertialRadiusOffset;
  48666. this.inertialAlphaOffset *= this.inertia;
  48667. this.inertialBetaOffset *= this.inertia;
  48668. this.inertialRadiusOffset *= this.inertia;
  48669. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48670. this.inertialAlphaOffset = 0;
  48671. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48672. this.inertialBetaOffset = 0;
  48673. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48674. this.inertialRadiusOffset = 0;
  48675. }
  48676. // Panning inertia
  48677. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48678. if (!this._localDirection) {
  48679. this._localDirection = BABYLON.Vector3.Zero();
  48680. this._transformedDirection = BABYLON.Vector3.Zero();
  48681. }
  48682. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48683. this._localDirection.multiplyInPlace(this.panningAxis);
  48684. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48685. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48686. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48687. if (!this.panningAxis.y) {
  48688. this._transformedDirection.y = 0;
  48689. }
  48690. if (!this._targetHost) {
  48691. if (this.panningDistanceLimit) {
  48692. this._transformedDirection.addInPlace(this._target);
  48693. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48694. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48695. this._target.copyFrom(this._transformedDirection);
  48696. }
  48697. }
  48698. else {
  48699. this._target.addInPlace(this._transformedDirection);
  48700. }
  48701. }
  48702. this.inertialPanningX *= this.panningInertia;
  48703. this.inertialPanningY *= this.panningInertia;
  48704. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48705. this.inertialPanningX = 0;
  48706. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48707. this.inertialPanningY = 0;
  48708. }
  48709. // Limits
  48710. this._checkLimits();
  48711. _super.prototype._checkInputs.call(this);
  48712. };
  48713. ArcRotateCamera.prototype._checkLimits = function () {
  48714. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48715. if (this.allowUpsideDown && this.beta > Math.PI) {
  48716. this.beta = this.beta - (2 * Math.PI);
  48717. }
  48718. }
  48719. else {
  48720. if (this.beta < this.lowerBetaLimit) {
  48721. this.beta = this.lowerBetaLimit;
  48722. }
  48723. }
  48724. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48725. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48726. this.beta = this.beta + (2 * Math.PI);
  48727. }
  48728. }
  48729. else {
  48730. if (this.beta > this.upperBetaLimit) {
  48731. this.beta = this.upperBetaLimit;
  48732. }
  48733. }
  48734. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48735. this.alpha = this.lowerAlphaLimit;
  48736. }
  48737. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48738. this.alpha = this.upperAlphaLimit;
  48739. }
  48740. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48741. this.radius = this.lowerRadiusLimit;
  48742. }
  48743. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48744. this.radius = this.upperRadiusLimit;
  48745. }
  48746. };
  48747. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48748. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48749. this.radius = this._computationVector.length();
  48750. if (this.radius === 0) {
  48751. this.radius = 0.0001; // Just to avoid division by zero
  48752. }
  48753. // Alpha
  48754. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48755. if (this._computationVector.z < 0) {
  48756. this.alpha = 2 * Math.PI - this.alpha;
  48757. }
  48758. // Beta
  48759. this.beta = Math.acos(this._computationVector.y / this.radius);
  48760. this._checkLimits();
  48761. };
  48762. ArcRotateCamera.prototype.setPosition = function (position) {
  48763. if (this.position.equals(position)) {
  48764. return;
  48765. }
  48766. this.position.copyFrom(position);
  48767. this.rebuildAnglesAndRadius();
  48768. };
  48769. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48770. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48771. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48772. if (target.getBoundingInfo) {
  48773. if (toBoundingCenter) {
  48774. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48775. }
  48776. else {
  48777. this._targetBoundingCenter = null;
  48778. }
  48779. this._targetHost = target;
  48780. this._target = this._getTargetPosition();
  48781. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48782. }
  48783. else {
  48784. var newTarget = target;
  48785. var currentTarget = this._getTargetPosition();
  48786. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48787. return;
  48788. }
  48789. this._targetHost = null;
  48790. this._target = newTarget;
  48791. this._targetBoundingCenter = null;
  48792. this.onMeshTargetChangedObservable.notifyObservers(null);
  48793. }
  48794. this.rebuildAnglesAndRadius();
  48795. };
  48796. ArcRotateCamera.prototype._getViewMatrix = function () {
  48797. // Compute
  48798. var cosa = Math.cos(this.alpha);
  48799. var sina = Math.sin(this.alpha);
  48800. var cosb = Math.cos(this.beta);
  48801. var sinb = Math.sin(this.beta);
  48802. if (sinb === 0) {
  48803. sinb = 0.0001;
  48804. }
  48805. var target = this._getTargetPosition();
  48806. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48807. target.addToRef(this._computationVector, this._newPosition);
  48808. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48809. if (!this._collider) {
  48810. this._collider = new BABYLON.Collider();
  48811. }
  48812. this._collider._radius = this.collisionRadius;
  48813. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48814. this._collisionTriggered = true;
  48815. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48816. }
  48817. else {
  48818. this.position.copyFrom(this._newPosition);
  48819. var up = this.upVector;
  48820. if (this.allowUpsideDown && sinb < 0) {
  48821. up = up.clone();
  48822. up = up.negate();
  48823. }
  48824. this._computeViewMatrix(this.position, target, up);
  48825. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48826. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48827. }
  48828. this._currentTarget = target;
  48829. return this._viewMatrix;
  48830. };
  48831. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48832. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48833. meshes = meshes || this.getScene().meshes;
  48834. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48835. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48836. this.radius = distance * this.zoomOnFactor;
  48837. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48838. };
  48839. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48840. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48841. var meshesOrMinMaxVector;
  48842. var distance;
  48843. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48844. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48845. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48846. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48847. }
  48848. else { //minMaxVector and distance
  48849. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48850. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48851. distance = minMaxVectorAndDistance.distance;
  48852. }
  48853. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48854. if (!doNotUpdateMaxZ) {
  48855. this.maxZ = distance * 2;
  48856. }
  48857. };
  48858. /**
  48859. * @override
  48860. * Override Camera.createRigCamera
  48861. */
  48862. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48863. var alphaShift = 0;
  48864. switch (this.cameraRigMode) {
  48865. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48866. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48867. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48868. case BABYLON.Camera.RIG_MODE_VR:
  48869. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48870. break;
  48871. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48872. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48873. break;
  48874. }
  48875. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48876. rigCam._cameraRigParams = {};
  48877. return rigCam;
  48878. };
  48879. /**
  48880. * @override
  48881. * Override Camera._updateRigCameras
  48882. */
  48883. ArcRotateCamera.prototype._updateRigCameras = function () {
  48884. var camLeft = this._rigCameras[0];
  48885. var camRight = this._rigCameras[1];
  48886. camLeft.beta = camRight.beta = this.beta;
  48887. camLeft.radius = camRight.radius = this.radius;
  48888. switch (this.cameraRigMode) {
  48889. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48890. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48891. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48892. case BABYLON.Camera.RIG_MODE_VR:
  48893. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48894. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48895. break;
  48896. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48897. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48898. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48899. break;
  48900. }
  48901. _super.prototype._updateRigCameras.call(this);
  48902. };
  48903. ArcRotateCamera.prototype.dispose = function () {
  48904. this.inputs.clear();
  48905. _super.prototype.dispose.call(this);
  48906. };
  48907. ArcRotateCamera.prototype.getClassName = function () {
  48908. return "ArcRotateCamera";
  48909. };
  48910. __decorate([
  48911. BABYLON.serialize()
  48912. ], ArcRotateCamera.prototype, "alpha", void 0);
  48913. __decorate([
  48914. BABYLON.serialize()
  48915. ], ArcRotateCamera.prototype, "beta", void 0);
  48916. __decorate([
  48917. BABYLON.serialize()
  48918. ], ArcRotateCamera.prototype, "radius", void 0);
  48919. __decorate([
  48920. BABYLON.serializeAsVector3("target")
  48921. ], ArcRotateCamera.prototype, "_target", void 0);
  48922. __decorate([
  48923. BABYLON.serialize()
  48924. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48925. __decorate([
  48926. BABYLON.serialize()
  48927. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48928. __decorate([
  48929. BABYLON.serialize()
  48930. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48931. __decorate([
  48932. BABYLON.serialize()
  48933. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48934. __decorate([
  48935. BABYLON.serialize()
  48936. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48937. __decorate([
  48938. BABYLON.serialize()
  48939. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48940. __decorate([
  48941. BABYLON.serialize()
  48942. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48943. __decorate([
  48944. BABYLON.serialize()
  48945. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48946. __decorate([
  48947. BABYLON.serialize()
  48948. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48949. __decorate([
  48950. BABYLON.serialize()
  48951. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48952. __decorate([
  48953. BABYLON.serialize()
  48954. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48955. __decorate([
  48956. BABYLON.serialize()
  48957. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48958. __decorate([
  48959. BABYLON.serialize()
  48960. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48961. __decorate([
  48962. BABYLON.serializeAsVector3()
  48963. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48964. __decorate([
  48965. BABYLON.serialize()
  48966. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48967. __decorate([
  48968. BABYLON.serialize()
  48969. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48970. __decorate([
  48971. BABYLON.serialize()
  48972. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48973. return ArcRotateCamera;
  48974. }(BABYLON.TargetCamera));
  48975. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48976. })(BABYLON || (BABYLON = {}));
  48977. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48978. var BABYLON;
  48979. (function (BABYLON) {
  48980. /**
  48981. * The HemisphericLight simulates the ambient environment light,
  48982. * so the passed direction is the light reflection direction, not the incoming direction.
  48983. */
  48984. var HemisphericLight = /** @class */ (function (_super) {
  48985. __extends(HemisphericLight, _super);
  48986. /**
  48987. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48988. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48989. * The HemisphericLight can't cast shadows.
  48990. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48991. * @param name The friendly name of the light
  48992. * @param direction The direction of the light reflection
  48993. * @param scene The scene the light belongs to
  48994. */
  48995. function HemisphericLight(name, direction, scene) {
  48996. var _this = _super.call(this, name, scene) || this;
  48997. /**
  48998. * The groundColor is the light in the opposite direction to the one specified during creation.
  48999. * 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.
  49000. */
  49001. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49002. _this.direction = direction || BABYLON.Vector3.Up();
  49003. return _this;
  49004. }
  49005. HemisphericLight.prototype._buildUniformLayout = function () {
  49006. this._uniformBuffer.addUniform("vLightData", 4);
  49007. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49008. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49009. this._uniformBuffer.addUniform("vLightGround", 3);
  49010. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49011. this._uniformBuffer.addUniform("depthValues", 2);
  49012. this._uniformBuffer.create();
  49013. };
  49014. /**
  49015. * Returns the string "HemisphericLight".
  49016. * @return The class name
  49017. */
  49018. HemisphericLight.prototype.getClassName = function () {
  49019. return "HemisphericLight";
  49020. };
  49021. /**
  49022. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49023. * Returns the updated direction.
  49024. * @param target The target the direction should point to
  49025. * @return The computed direction
  49026. */
  49027. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49028. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49029. return this.direction;
  49030. };
  49031. /**
  49032. * Returns the shadow generator associated to the light.
  49033. * @returns Always null for hemispheric lights because it does not support shadows.
  49034. */
  49035. HemisphericLight.prototype.getShadowGenerator = function () {
  49036. return null;
  49037. };
  49038. /**
  49039. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49040. * @param effect The effect to update
  49041. * @param lightIndex The index of the light in the effect to update
  49042. * @returns The hemispheric light
  49043. */
  49044. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49045. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49046. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49047. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49048. return this;
  49049. };
  49050. /**
  49051. * @hidden internal use only.
  49052. */
  49053. HemisphericLight.prototype._getWorldMatrix = function () {
  49054. if (!this._worldMatrix) {
  49055. this._worldMatrix = BABYLON.Matrix.Identity();
  49056. }
  49057. return this._worldMatrix;
  49058. };
  49059. /**
  49060. * Returns the integer 3.
  49061. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49062. */
  49063. HemisphericLight.prototype.getTypeID = function () {
  49064. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49065. };
  49066. __decorate([
  49067. BABYLON.serializeAsColor3()
  49068. ], HemisphericLight.prototype, "groundColor", void 0);
  49069. __decorate([
  49070. BABYLON.serializeAsVector3()
  49071. ], HemisphericLight.prototype, "direction", void 0);
  49072. return HemisphericLight;
  49073. }(BABYLON.Light));
  49074. BABYLON.HemisphericLight = HemisphericLight;
  49075. })(BABYLON || (BABYLON = {}));
  49076. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49077. var BABYLON;
  49078. (function (BABYLON) {
  49079. /**
  49080. * Base implementation IShadowLight
  49081. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49082. */
  49083. var ShadowLight = /** @class */ (function (_super) {
  49084. __extends(ShadowLight, _super);
  49085. function ShadowLight() {
  49086. var _this = _super !== null && _super.apply(this, arguments) || this;
  49087. _this._needProjectionMatrixCompute = true;
  49088. return _this;
  49089. }
  49090. ShadowLight.prototype._setPosition = function (value) {
  49091. this._position = value;
  49092. };
  49093. Object.defineProperty(ShadowLight.prototype, "position", {
  49094. /**
  49095. * Sets the position the shadow will be casted from. Also use as the light position for both
  49096. * point and spot lights.
  49097. */
  49098. get: function () {
  49099. return this._position;
  49100. },
  49101. /**
  49102. * Sets the position the shadow will be casted from. Also use as the light position for both
  49103. * point and spot lights.
  49104. */
  49105. set: function (value) {
  49106. this._setPosition(value);
  49107. },
  49108. enumerable: true,
  49109. configurable: true
  49110. });
  49111. ShadowLight.prototype._setDirection = function (value) {
  49112. this._direction = value;
  49113. };
  49114. Object.defineProperty(ShadowLight.prototype, "direction", {
  49115. /**
  49116. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49117. * Also use as the light direction on spot and directional lights.
  49118. */
  49119. get: function () {
  49120. return this._direction;
  49121. },
  49122. /**
  49123. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49124. * Also use as the light direction on spot and directional lights.
  49125. */
  49126. set: function (value) {
  49127. this._setDirection(value);
  49128. },
  49129. enumerable: true,
  49130. configurable: true
  49131. });
  49132. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49133. /**
  49134. * Gets the shadow projection clipping minimum z value.
  49135. */
  49136. get: function () {
  49137. return this._shadowMinZ;
  49138. },
  49139. /**
  49140. * Sets the shadow projection clipping minimum z value.
  49141. */
  49142. set: function (value) {
  49143. this._shadowMinZ = value;
  49144. this.forceProjectionMatrixCompute();
  49145. },
  49146. enumerable: true,
  49147. configurable: true
  49148. });
  49149. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49150. /**
  49151. * Sets the shadow projection clipping maximum z value.
  49152. */
  49153. get: function () {
  49154. return this._shadowMaxZ;
  49155. },
  49156. /**
  49157. * Gets the shadow projection clipping maximum z value.
  49158. */
  49159. set: function (value) {
  49160. this._shadowMaxZ = value;
  49161. this.forceProjectionMatrixCompute();
  49162. },
  49163. enumerable: true,
  49164. configurable: true
  49165. });
  49166. /**
  49167. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49168. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49169. */
  49170. ShadowLight.prototype.computeTransformedInformation = function () {
  49171. if (this.parent && this.parent.getWorldMatrix) {
  49172. if (!this.transformedPosition) {
  49173. this.transformedPosition = BABYLON.Vector3.Zero();
  49174. }
  49175. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49176. // In case the direction is present.
  49177. if (this.direction) {
  49178. if (!this.transformedDirection) {
  49179. this.transformedDirection = BABYLON.Vector3.Zero();
  49180. }
  49181. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49182. }
  49183. return true;
  49184. }
  49185. return false;
  49186. };
  49187. /**
  49188. * Return the depth scale used for the shadow map.
  49189. * @returns the depth scale.
  49190. */
  49191. ShadowLight.prototype.getDepthScale = function () {
  49192. return 50.0;
  49193. };
  49194. /**
  49195. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49196. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49197. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49198. */
  49199. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49200. return this.transformedDirection ? this.transformedDirection : this.direction;
  49201. };
  49202. /**
  49203. * Returns the ShadowLight absolute position in the World.
  49204. * @returns the position vector in world space
  49205. */
  49206. ShadowLight.prototype.getAbsolutePosition = function () {
  49207. return this.transformedPosition ? this.transformedPosition : this.position;
  49208. };
  49209. /**
  49210. * Sets the ShadowLight direction toward the passed target.
  49211. * @param target The point tot target in local space
  49212. * @returns the updated ShadowLight direction
  49213. */
  49214. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49215. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49216. return this.direction;
  49217. };
  49218. /**
  49219. * Returns the light rotation in euler definition.
  49220. * @returns the x y z rotation in local space.
  49221. */
  49222. ShadowLight.prototype.getRotation = function () {
  49223. this.direction.normalize();
  49224. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49225. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49226. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49227. };
  49228. /**
  49229. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49230. * @returns true if a cube texture needs to be use
  49231. */
  49232. ShadowLight.prototype.needCube = function () {
  49233. return false;
  49234. };
  49235. /**
  49236. * Detects if the projection matrix requires to be recomputed this frame.
  49237. * @returns true if it requires to be recomputed otherwise, false.
  49238. */
  49239. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49240. return this._needProjectionMatrixCompute;
  49241. };
  49242. /**
  49243. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49244. */
  49245. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49246. this._needProjectionMatrixCompute = true;
  49247. };
  49248. /**
  49249. * Get the world matrix of the sahdow lights.
  49250. * @hidden Internal Use Only
  49251. */
  49252. ShadowLight.prototype._getWorldMatrix = function () {
  49253. if (!this._worldMatrix) {
  49254. this._worldMatrix = BABYLON.Matrix.Identity();
  49255. }
  49256. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49257. return this._worldMatrix;
  49258. };
  49259. /**
  49260. * Gets the minZ used for shadow according to both the scene and the light.
  49261. * @param activeCamera The camera we are returning the min for
  49262. * @returns the depth min z
  49263. */
  49264. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49265. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49266. };
  49267. /**
  49268. * Gets the maxZ used for shadow according to both the scene and the light.
  49269. * @param activeCamera The camera we are returning the max for
  49270. * @returns the depth max z
  49271. */
  49272. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49273. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49274. };
  49275. /**
  49276. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49277. * @param matrix The materix to updated with the projection information
  49278. * @param viewMatrix The transform matrix of the light
  49279. * @param renderList The list of mesh to render in the map
  49280. * @returns The current light
  49281. */
  49282. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49283. if (this.customProjectionMatrixBuilder) {
  49284. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49285. }
  49286. else {
  49287. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49288. }
  49289. return this;
  49290. };
  49291. __decorate([
  49292. BABYLON.serializeAsVector3()
  49293. ], ShadowLight.prototype, "position", null);
  49294. __decorate([
  49295. BABYLON.serializeAsVector3()
  49296. ], ShadowLight.prototype, "direction", null);
  49297. __decorate([
  49298. BABYLON.serialize()
  49299. ], ShadowLight.prototype, "shadowMinZ", null);
  49300. __decorate([
  49301. BABYLON.serialize()
  49302. ], ShadowLight.prototype, "shadowMaxZ", null);
  49303. return ShadowLight;
  49304. }(BABYLON.Light));
  49305. BABYLON.ShadowLight = ShadowLight;
  49306. })(BABYLON || (BABYLON = {}));
  49307. //# sourceMappingURL=babylon.shadowLight.js.map
  49308. var BABYLON;
  49309. (function (BABYLON) {
  49310. /**
  49311. * A point light is a light defined by an unique point in world space.
  49312. * The light is emitted in every direction from this point.
  49313. * A good example of a point light is a standard light bulb.
  49314. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49315. */
  49316. var PointLight = /** @class */ (function (_super) {
  49317. __extends(PointLight, _super);
  49318. /**
  49319. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49320. * A PointLight emits the light in every direction.
  49321. * It can cast shadows.
  49322. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49323. * ```javascript
  49324. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49325. * ```
  49326. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49327. * @param name The light friendly name
  49328. * @param position The position of the point light in the scene
  49329. * @param scene The scene the lights belongs to
  49330. */
  49331. function PointLight(name, position, scene) {
  49332. var _this = _super.call(this, name, scene) || this;
  49333. _this._shadowAngle = Math.PI / 2;
  49334. _this.position = position;
  49335. return _this;
  49336. }
  49337. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49338. /**
  49339. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49340. * This specifies what angle the shadow will use to be created.
  49341. *
  49342. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49343. */
  49344. get: function () {
  49345. return this._shadowAngle;
  49346. },
  49347. /**
  49348. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49349. * This specifies what angle the shadow will use to be created.
  49350. *
  49351. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49352. */
  49353. set: function (value) {
  49354. this._shadowAngle = value;
  49355. this.forceProjectionMatrixCompute();
  49356. },
  49357. enumerable: true,
  49358. configurable: true
  49359. });
  49360. Object.defineProperty(PointLight.prototype, "direction", {
  49361. /**
  49362. * Gets the direction if it has been set.
  49363. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49364. */
  49365. get: function () {
  49366. return this._direction;
  49367. },
  49368. /**
  49369. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49370. */
  49371. set: function (value) {
  49372. var previousNeedCube = this.needCube();
  49373. this._direction = value;
  49374. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49375. this._shadowGenerator.recreateShadowMap();
  49376. }
  49377. },
  49378. enumerable: true,
  49379. configurable: true
  49380. });
  49381. /**
  49382. * Returns the string "PointLight"
  49383. * @returns the class name
  49384. */
  49385. PointLight.prototype.getClassName = function () {
  49386. return "PointLight";
  49387. };
  49388. /**
  49389. * Returns the integer 0.
  49390. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49391. */
  49392. PointLight.prototype.getTypeID = function () {
  49393. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49394. };
  49395. /**
  49396. * Specifies wether or not the shadowmap should be a cube texture.
  49397. * @returns true if the shadowmap needs to be a cube texture.
  49398. */
  49399. PointLight.prototype.needCube = function () {
  49400. return !this.direction;
  49401. };
  49402. /**
  49403. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49404. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49405. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49406. */
  49407. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49408. if (this.direction) {
  49409. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49410. }
  49411. else {
  49412. switch (faceIndex) {
  49413. case 0:
  49414. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49415. case 1:
  49416. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49417. case 2:
  49418. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49419. case 3:
  49420. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49421. case 4:
  49422. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49423. case 5:
  49424. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49425. }
  49426. }
  49427. return BABYLON.Vector3.Zero();
  49428. };
  49429. /**
  49430. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49431. * - fov = PI / 2
  49432. * - aspect ratio : 1.0
  49433. * - z-near and far equal to the active camera minZ and maxZ.
  49434. * Returns the PointLight.
  49435. */
  49436. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49437. var activeCamera = this.getScene().activeCamera;
  49438. if (!activeCamera) {
  49439. return;
  49440. }
  49441. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49442. };
  49443. PointLight.prototype._buildUniformLayout = function () {
  49444. this._uniformBuffer.addUniform("vLightData", 4);
  49445. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49446. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49447. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49448. this._uniformBuffer.addUniform("depthValues", 2);
  49449. this._uniformBuffer.create();
  49450. };
  49451. /**
  49452. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49453. * @param effect The effect to update
  49454. * @param lightIndex The index of the light in the effect to update
  49455. * @returns The point light
  49456. */
  49457. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49458. if (this.computeTransformedInformation()) {
  49459. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49460. return this;
  49461. }
  49462. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49463. return this;
  49464. };
  49465. __decorate([
  49466. BABYLON.serialize()
  49467. ], PointLight.prototype, "shadowAngle", null);
  49468. return PointLight;
  49469. }(BABYLON.ShadowLight));
  49470. BABYLON.PointLight = PointLight;
  49471. })(BABYLON || (BABYLON = {}));
  49472. //# sourceMappingURL=babylon.pointLight.js.map
  49473. var BABYLON;
  49474. (function (BABYLON) {
  49475. /**
  49476. * A directional light is defined by a direction (what a surprise!).
  49477. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49478. * 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.
  49479. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49480. */
  49481. var DirectionalLight = /** @class */ (function (_super) {
  49482. __extends(DirectionalLight, _super);
  49483. /**
  49484. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49485. * The directional light is emitted from everywhere in the given direction.
  49486. * It can cast shawdows.
  49487. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49488. * @param name The friendly name of the light
  49489. * @param direction The direction of the light
  49490. * @param scene The scene the light belongs to
  49491. */
  49492. function DirectionalLight(name, direction, scene) {
  49493. var _this = _super.call(this, name, scene) || this;
  49494. _this._shadowFrustumSize = 0;
  49495. _this._shadowOrthoScale = 0.1;
  49496. /**
  49497. * Automatically compute the projection matrix to best fit (including all the casters)
  49498. * on each frame.
  49499. */
  49500. _this.autoUpdateExtends = true;
  49501. // Cache
  49502. _this._orthoLeft = Number.MAX_VALUE;
  49503. _this._orthoRight = Number.MIN_VALUE;
  49504. _this._orthoTop = Number.MIN_VALUE;
  49505. _this._orthoBottom = Number.MAX_VALUE;
  49506. _this.position = direction.scale(-1.0);
  49507. _this.direction = direction;
  49508. return _this;
  49509. }
  49510. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49511. /**
  49512. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49513. */
  49514. get: function () {
  49515. return this._shadowFrustumSize;
  49516. },
  49517. /**
  49518. * Specifies a fix frustum size for the shadow generation.
  49519. */
  49520. set: function (value) {
  49521. this._shadowFrustumSize = value;
  49522. this.forceProjectionMatrixCompute();
  49523. },
  49524. enumerable: true,
  49525. configurable: true
  49526. });
  49527. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49528. /**
  49529. * Gets the shadow projection scale against the optimal computed one.
  49530. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49531. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49532. */
  49533. get: function () {
  49534. return this._shadowOrthoScale;
  49535. },
  49536. /**
  49537. * Sets the shadow projection scale against the optimal computed one.
  49538. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49539. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49540. */
  49541. set: function (value) {
  49542. this._shadowOrthoScale = value;
  49543. this.forceProjectionMatrixCompute();
  49544. },
  49545. enumerable: true,
  49546. configurable: true
  49547. });
  49548. /**
  49549. * Returns the string "DirectionalLight".
  49550. * @return The class name
  49551. */
  49552. DirectionalLight.prototype.getClassName = function () {
  49553. return "DirectionalLight";
  49554. };
  49555. /**
  49556. * Returns the integer 1.
  49557. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49558. */
  49559. DirectionalLight.prototype.getTypeID = function () {
  49560. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49561. };
  49562. /**
  49563. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49564. * Returns the DirectionalLight Shadow projection matrix.
  49565. */
  49566. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49567. if (this.shadowFrustumSize > 0) {
  49568. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49569. }
  49570. else {
  49571. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49572. }
  49573. };
  49574. /**
  49575. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49576. * Returns the DirectionalLight Shadow projection matrix.
  49577. */
  49578. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49579. var activeCamera = this.getScene().activeCamera;
  49580. if (!activeCamera) {
  49581. return;
  49582. }
  49583. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49584. };
  49585. /**
  49586. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49587. * Returns the DirectionalLight Shadow projection matrix.
  49588. */
  49589. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49590. var activeCamera = this.getScene().activeCamera;
  49591. if (!activeCamera) {
  49592. return;
  49593. }
  49594. // Check extends
  49595. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49596. var tempVector3 = BABYLON.Vector3.Zero();
  49597. this._orthoLeft = Number.MAX_VALUE;
  49598. this._orthoRight = Number.MIN_VALUE;
  49599. this._orthoTop = Number.MIN_VALUE;
  49600. this._orthoBottom = Number.MAX_VALUE;
  49601. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49602. var mesh = renderList[meshIndex];
  49603. if (!mesh) {
  49604. continue;
  49605. }
  49606. var boundingInfo = mesh.getBoundingInfo();
  49607. var boundingBox = boundingInfo.boundingBox;
  49608. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49609. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49610. if (tempVector3.x < this._orthoLeft)
  49611. this._orthoLeft = tempVector3.x;
  49612. if (tempVector3.y < this._orthoBottom)
  49613. this._orthoBottom = tempVector3.y;
  49614. if (tempVector3.x > this._orthoRight)
  49615. this._orthoRight = tempVector3.x;
  49616. if (tempVector3.y > this._orthoTop)
  49617. this._orthoTop = tempVector3.y;
  49618. }
  49619. }
  49620. }
  49621. var xOffset = this._orthoRight - this._orthoLeft;
  49622. var yOffset = this._orthoTop - this._orthoBottom;
  49623. 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);
  49624. };
  49625. DirectionalLight.prototype._buildUniformLayout = function () {
  49626. this._uniformBuffer.addUniform("vLightData", 4);
  49627. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49628. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49629. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49630. this._uniformBuffer.addUniform("depthValues", 2);
  49631. this._uniformBuffer.create();
  49632. };
  49633. /**
  49634. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49635. * @param effect The effect to update
  49636. * @param lightIndex The index of the light in the effect to update
  49637. * @returns The directional light
  49638. */
  49639. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49640. if (this.computeTransformedInformation()) {
  49641. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49642. return this;
  49643. }
  49644. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49645. return this;
  49646. };
  49647. /**
  49648. * Gets the minZ used for shadow according to both the scene and the light.
  49649. *
  49650. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49651. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49652. * @param activeCamera The camera we are returning the min for
  49653. * @returns the depth min z
  49654. */
  49655. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49656. return 1;
  49657. };
  49658. /**
  49659. * Gets the maxZ used for shadow according to both the scene and the light.
  49660. *
  49661. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49662. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49663. * @param activeCamera The camera we are returning the max for
  49664. * @returns the depth max z
  49665. */
  49666. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49667. return 1;
  49668. };
  49669. __decorate([
  49670. BABYLON.serialize()
  49671. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49672. __decorate([
  49673. BABYLON.serialize()
  49674. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49675. __decorate([
  49676. BABYLON.serialize()
  49677. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49678. return DirectionalLight;
  49679. }(BABYLON.ShadowLight));
  49680. BABYLON.DirectionalLight = DirectionalLight;
  49681. })(BABYLON || (BABYLON = {}));
  49682. //# sourceMappingURL=babylon.directionalLight.js.map
  49683. var BABYLON;
  49684. (function (BABYLON) {
  49685. /**
  49686. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49687. * These values define a cone of light starting from the position, emitting toward the direction.
  49688. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49689. * and the exponent defines the speed of the decay of the light with distance (reach).
  49690. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49691. */
  49692. var SpotLight = /** @class */ (function (_super) {
  49693. __extends(SpotLight, _super);
  49694. /**
  49695. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49696. * It can cast shadows.
  49697. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49698. * @param name The light friendly name
  49699. * @param position The position of the spot light in the scene
  49700. * @param direction The direction of the light in the scene
  49701. * @param angle The cone angle of the light in Radians
  49702. * @param exponent The light decay speed with the distance from the emission spot
  49703. * @param scene The scene the lights belongs to
  49704. */
  49705. function SpotLight(name, position, direction, angle, exponent, scene) {
  49706. var _this = _super.call(this, name, scene) || this;
  49707. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49708. _this._projectionTextureLightNear = 1e-6;
  49709. _this._projectionTextureLightFar = 1000.0;
  49710. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49711. _this._projectionTextureViewLightDirty = true;
  49712. _this._projectionTextureProjectionLightDirty = true;
  49713. _this._projectionTextureDirty = true;
  49714. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49715. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49716. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49717. _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);
  49718. _this.position = position;
  49719. _this.direction = direction;
  49720. _this.angle = angle;
  49721. _this.exponent = exponent;
  49722. return _this;
  49723. }
  49724. Object.defineProperty(SpotLight.prototype, "angle", {
  49725. /**
  49726. * Gets the cone angle of the spot light in Radians.
  49727. */
  49728. get: function () {
  49729. return this._angle;
  49730. },
  49731. /**
  49732. * Sets the cone angle of the spot light in Radians.
  49733. */
  49734. set: function (value) {
  49735. this._angle = value;
  49736. this._projectionTextureProjectionLightDirty = true;
  49737. this.forceProjectionMatrixCompute();
  49738. },
  49739. enumerable: true,
  49740. configurable: true
  49741. });
  49742. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49743. /**
  49744. * Allows scaling the angle of the light for shadow generation only.
  49745. */
  49746. get: function () {
  49747. return this._shadowAngleScale;
  49748. },
  49749. /**
  49750. * Allows scaling the angle of the light for shadow generation only.
  49751. */
  49752. set: function (value) {
  49753. this._shadowAngleScale = value;
  49754. this.forceProjectionMatrixCompute();
  49755. },
  49756. enumerable: true,
  49757. configurable: true
  49758. });
  49759. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49760. /**
  49761. * Allows reading the projecton texture
  49762. */
  49763. get: function () {
  49764. return this._projectionTextureMatrix;
  49765. },
  49766. enumerable: true,
  49767. configurable: true
  49768. });
  49769. ;
  49770. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49771. /**
  49772. * Gets the near clip of the Spotlight for texture projection.
  49773. */
  49774. get: function () {
  49775. return this._projectionTextureLightNear;
  49776. },
  49777. /**
  49778. * Sets the near clip of the Spotlight for texture projection.
  49779. */
  49780. set: function (value) {
  49781. this._projectionTextureLightNear = value;
  49782. this._projectionTextureProjectionLightDirty = true;
  49783. },
  49784. enumerable: true,
  49785. configurable: true
  49786. });
  49787. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49788. /**
  49789. * Gets the far clip of the Spotlight for texture projection.
  49790. */
  49791. get: function () {
  49792. return this._projectionTextureLightFar;
  49793. },
  49794. /**
  49795. * Sets the far clip of the Spotlight for texture projection.
  49796. */
  49797. set: function (value) {
  49798. this._projectionTextureLightFar = value;
  49799. this._projectionTextureProjectionLightDirty = true;
  49800. },
  49801. enumerable: true,
  49802. configurable: true
  49803. });
  49804. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49805. /**
  49806. * Gets the Up vector of the Spotlight for texture projection.
  49807. */
  49808. get: function () {
  49809. return this._projectionTextureUpDirection;
  49810. },
  49811. /**
  49812. * Sets the Up vector of the Spotlight for texture projection.
  49813. */
  49814. set: function (value) {
  49815. this._projectionTextureUpDirection = value;
  49816. this._projectionTextureProjectionLightDirty = true;
  49817. },
  49818. enumerable: true,
  49819. configurable: true
  49820. });
  49821. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49822. /**
  49823. * Gets the projection texture of the light.
  49824. */
  49825. get: function () {
  49826. return this._projectionTexture;
  49827. },
  49828. /**
  49829. * Sets the projection texture of the light.
  49830. */
  49831. set: function (value) {
  49832. this._projectionTexture = value;
  49833. this._projectionTextureDirty = true;
  49834. },
  49835. enumerable: true,
  49836. configurable: true
  49837. });
  49838. /**
  49839. * Returns the string "SpotLight".
  49840. * @returns the class name
  49841. */
  49842. SpotLight.prototype.getClassName = function () {
  49843. return "SpotLight";
  49844. };
  49845. /**
  49846. * Returns the integer 2.
  49847. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49848. */
  49849. SpotLight.prototype.getTypeID = function () {
  49850. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49851. };
  49852. /**
  49853. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49854. */
  49855. SpotLight.prototype._setDirection = function (value) {
  49856. _super.prototype._setDirection.call(this, value);
  49857. this._projectionTextureViewLightDirty = true;
  49858. };
  49859. /**
  49860. * Overrides the position setter to recompute the projection texture view light Matrix.
  49861. */
  49862. SpotLight.prototype._setPosition = function (value) {
  49863. _super.prototype._setPosition.call(this, value);
  49864. this._projectionTextureViewLightDirty = true;
  49865. };
  49866. /**
  49867. * 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.
  49868. * Returns the SpotLight.
  49869. */
  49870. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49871. var activeCamera = this.getScene().activeCamera;
  49872. if (!activeCamera) {
  49873. return;
  49874. }
  49875. this._shadowAngleScale = this._shadowAngleScale || 1;
  49876. var angle = this._shadowAngleScale * this._angle;
  49877. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49878. };
  49879. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49880. this._projectionTextureViewLightDirty = false;
  49881. this._projectionTextureDirty = true;
  49882. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49883. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49884. };
  49885. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49886. this._projectionTextureProjectionLightDirty = false;
  49887. this._projectionTextureDirty = true;
  49888. var light_far = this.projectionTextureLightFar;
  49889. var light_near = this.projectionTextureLightNear;
  49890. var P = light_far / (light_far - light_near);
  49891. var Q = -P * light_near;
  49892. var S = 1.0 / Math.tan(this._angle / 2.0);
  49893. var A = 1.0;
  49894. 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);
  49895. };
  49896. /**
  49897. * Main function for light texture projection matrix computing.
  49898. */
  49899. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49900. this._projectionTextureDirty = false;
  49901. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49902. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49903. };
  49904. SpotLight.prototype._buildUniformLayout = function () {
  49905. this._uniformBuffer.addUniform("vLightData", 4);
  49906. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49907. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49908. this._uniformBuffer.addUniform("vLightDirection", 3);
  49909. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49910. this._uniformBuffer.addUniform("depthValues", 2);
  49911. this._uniformBuffer.create();
  49912. };
  49913. /**
  49914. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49915. * @param effect The effect to update
  49916. * @param lightIndex The index of the light in the effect to update
  49917. * @returns The spot light
  49918. */
  49919. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49920. var normalizeDirection;
  49921. if (this.computeTransformedInformation()) {
  49922. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49923. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49924. }
  49925. else {
  49926. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49927. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49928. }
  49929. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49930. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49931. if (this._projectionTextureViewLightDirty) {
  49932. this._computeProjectionTextureViewLightMatrix();
  49933. }
  49934. if (this._projectionTextureProjectionLightDirty) {
  49935. this._computeProjectionTextureProjectionLightMatrix();
  49936. }
  49937. if (this._projectionTextureDirty) {
  49938. this._computeProjectionTextureMatrix();
  49939. }
  49940. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49941. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49942. }
  49943. return this;
  49944. };
  49945. /**
  49946. * Disposes the light and the associated resources.
  49947. */
  49948. SpotLight.prototype.dispose = function () {
  49949. _super.prototype.dispose.call(this);
  49950. if (this._projectionTexture) {
  49951. this._projectionTexture.dispose();
  49952. }
  49953. };
  49954. __decorate([
  49955. BABYLON.serialize()
  49956. ], SpotLight.prototype, "angle", null);
  49957. __decorate([
  49958. BABYLON.serialize()
  49959. ], SpotLight.prototype, "shadowAngleScale", null);
  49960. __decorate([
  49961. BABYLON.serialize()
  49962. ], SpotLight.prototype, "exponent", void 0);
  49963. __decorate([
  49964. BABYLON.serialize()
  49965. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49966. __decorate([
  49967. BABYLON.serialize()
  49968. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49969. __decorate([
  49970. BABYLON.serialize()
  49971. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49972. __decorate([
  49973. BABYLON.serializeAsTexture("projectedLightTexture")
  49974. ], SpotLight.prototype, "_projectionTexture", void 0);
  49975. return SpotLight;
  49976. }(BABYLON.ShadowLight));
  49977. BABYLON.SpotLight = SpotLight;
  49978. })(BABYLON || (BABYLON = {}));
  49979. //# sourceMappingURL=babylon.spotLight.js.map
  49980. var BABYLON;
  49981. (function (BABYLON) {
  49982. /**
  49983. * Class used to override all child animations of a given target
  49984. */
  49985. var AnimationPropertiesOverride = /** @class */ (function () {
  49986. function AnimationPropertiesOverride() {
  49987. /**
  49988. * Gets or sets a value indicating if animation blending must be used
  49989. */
  49990. this.enableBlending = false;
  49991. /**
  49992. * Gets or sets the blending speed to use when enableBlending is true
  49993. */
  49994. this.blendingSpeed = 0.01;
  49995. /**
  49996. * Gets or sets the default loop mode to use
  49997. */
  49998. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49999. }
  50000. return AnimationPropertiesOverride;
  50001. }());
  50002. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50003. })(BABYLON || (BABYLON = {}));
  50004. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50005. var BABYLON;
  50006. (function (BABYLON) {
  50007. /**
  50008. * Represents the range of an animation
  50009. */
  50010. var AnimationRange = /** @class */ (function () {
  50011. /**
  50012. * Initializes the range of an animation
  50013. * @param name The name of the animation range
  50014. * @param from The starting frame of the animation
  50015. * @param to The ending frame of the animation
  50016. */
  50017. function AnimationRange(
  50018. /**The name of the animation range**/
  50019. name,
  50020. /**The starting frame of the animation */
  50021. from,
  50022. /**The ending frame of the animation*/
  50023. to) {
  50024. this.name = name;
  50025. this.from = from;
  50026. this.to = to;
  50027. }
  50028. /**
  50029. * Makes a copy of the animation range
  50030. * @returns A copy of the animation range
  50031. */
  50032. AnimationRange.prototype.clone = function () {
  50033. return new AnimationRange(this.name, this.from, this.to);
  50034. };
  50035. return AnimationRange;
  50036. }());
  50037. BABYLON.AnimationRange = AnimationRange;
  50038. /**
  50039. * Composed of a frame, and an action function
  50040. */
  50041. var AnimationEvent = /** @class */ (function () {
  50042. /**
  50043. * Initializes the animation event
  50044. * @param frame The frame for which the event is triggered
  50045. * @param action The event to perform when triggered
  50046. * @param onlyOnce Specifies if the event should be triggered only once
  50047. */
  50048. function AnimationEvent(
  50049. /** The frame for which the event is triggered **/
  50050. frame,
  50051. /** The event to perform when triggered **/
  50052. action,
  50053. /** Specifies if the event should be triggered only once**/
  50054. onlyOnce) {
  50055. this.frame = frame;
  50056. this.action = action;
  50057. this.onlyOnce = onlyOnce;
  50058. /**
  50059. * Specifies if the animation event is done
  50060. */
  50061. this.isDone = false;
  50062. }
  50063. return AnimationEvent;
  50064. }());
  50065. BABYLON.AnimationEvent = AnimationEvent;
  50066. /**
  50067. * A cursor which tracks a point on a path
  50068. */
  50069. var PathCursor = /** @class */ (function () {
  50070. /**
  50071. * Initializes the path cursor
  50072. * @param path The path to track
  50073. */
  50074. function PathCursor(path) {
  50075. this.path = path;
  50076. /**
  50077. * Stores path cursor callbacks for when an onchange event is triggered
  50078. */
  50079. this._onchange = new Array();
  50080. /**
  50081. * The value of the path cursor
  50082. */
  50083. this.value = 0;
  50084. /**
  50085. * The animation array of the path cursor
  50086. */
  50087. this.animations = new Array();
  50088. }
  50089. /**
  50090. * Gets the cursor point on the path
  50091. * @returns A point on the path cursor at the cursor location
  50092. */
  50093. PathCursor.prototype.getPoint = function () {
  50094. var point = this.path.getPointAtLengthPosition(this.value);
  50095. return new BABYLON.Vector3(point.x, 0, point.y);
  50096. };
  50097. /**
  50098. * Moves the cursor ahead by the step amount
  50099. * @param step The amount to move the cursor forward
  50100. * @returns This path cursor
  50101. */
  50102. PathCursor.prototype.moveAhead = function (step) {
  50103. if (step === void 0) { step = 0.002; }
  50104. this.move(step);
  50105. return this;
  50106. };
  50107. /**
  50108. * Moves the cursor behind by the step amount
  50109. * @param step The amount to move the cursor back
  50110. * @returns This path cursor
  50111. */
  50112. PathCursor.prototype.moveBack = function (step) {
  50113. if (step === void 0) { step = 0.002; }
  50114. this.move(-step);
  50115. return this;
  50116. };
  50117. /**
  50118. * Moves the cursor by the step amount
  50119. * If the step amount is greater than one, an exception is thrown
  50120. * @param step The amount to move the cursor
  50121. * @returns This path cursor
  50122. */
  50123. PathCursor.prototype.move = function (step) {
  50124. if (Math.abs(step) > 1) {
  50125. throw "step size should be less than 1.";
  50126. }
  50127. this.value += step;
  50128. this.ensureLimits();
  50129. this.raiseOnChange();
  50130. return this;
  50131. };
  50132. /**
  50133. * Ensures that the value is limited between zero and one
  50134. * @returns This path cursor
  50135. */
  50136. PathCursor.prototype.ensureLimits = function () {
  50137. while (this.value > 1) {
  50138. this.value -= 1;
  50139. }
  50140. while (this.value < 0) {
  50141. this.value += 1;
  50142. }
  50143. return this;
  50144. };
  50145. /**
  50146. * Runs onchange callbacks on change (used by the animation engine)
  50147. * @returns This path cursor
  50148. */
  50149. PathCursor.prototype.raiseOnChange = function () {
  50150. var _this = this;
  50151. this._onchange.forEach(function (f) { return f(_this); });
  50152. return this;
  50153. };
  50154. /**
  50155. * Executes a function on change
  50156. * @param f A path cursor onchange callback
  50157. * @returns This path cursor
  50158. */
  50159. PathCursor.prototype.onchange = function (f) {
  50160. this._onchange.push(f);
  50161. return this;
  50162. };
  50163. return PathCursor;
  50164. }());
  50165. BABYLON.PathCursor = PathCursor;
  50166. /**
  50167. * Enum for the animation key frame interpolation type
  50168. */
  50169. var AnimationKeyInterpolation;
  50170. (function (AnimationKeyInterpolation) {
  50171. /**
  50172. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50173. */
  50174. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50175. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50176. /**
  50177. * Class used to store any kind of animation
  50178. */
  50179. var Animation = /** @class */ (function () {
  50180. /**
  50181. * Initializes the animation
  50182. * @param name Name of the animation
  50183. * @param targetProperty Property to animate
  50184. * @param framePerSecond The frames per second of the animation
  50185. * @param dataType The data type of the animation
  50186. * @param loopMode The loop mode of the animation
  50187. * @param enableBlendings Specifies if blending should be enabled
  50188. */
  50189. function Animation(
  50190. /**Name of the animation */
  50191. name,
  50192. /**Property to animate */
  50193. targetProperty,
  50194. /**The frames per second of the animation */
  50195. framePerSecond,
  50196. /**The data type of the animation */
  50197. dataType,
  50198. /**The loop mode of the animation */
  50199. loopMode,
  50200. /**Specifies if blending should be enabled */
  50201. enableBlending) {
  50202. this.name = name;
  50203. this.targetProperty = targetProperty;
  50204. this.framePerSecond = framePerSecond;
  50205. this.dataType = dataType;
  50206. this.loopMode = loopMode;
  50207. this.enableBlending = enableBlending;
  50208. /**
  50209. * @hidden Internal use only
  50210. */
  50211. this._runtimeAnimations = new Array();
  50212. /**
  50213. * The set of event that will be linked to this animation
  50214. */
  50215. this._events = new Array();
  50216. /**
  50217. * Stores the blending speed of the animation
  50218. */
  50219. this.blendingSpeed = 0.01;
  50220. /**
  50221. * Stores the animation ranges for the animation
  50222. */
  50223. this._ranges = {};
  50224. this.targetPropertyPath = targetProperty.split(".");
  50225. this.dataType = dataType;
  50226. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50227. }
  50228. /**
  50229. * @hidden Internal use
  50230. */
  50231. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50232. var dataType = undefined;
  50233. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50234. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50235. }
  50236. else if (from instanceof BABYLON.Quaternion) {
  50237. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50238. }
  50239. else if (from instanceof BABYLON.Vector3) {
  50240. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50241. }
  50242. else if (from instanceof BABYLON.Vector2) {
  50243. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50244. }
  50245. else if (from instanceof BABYLON.Color3) {
  50246. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50247. }
  50248. else if (from instanceof BABYLON.Size) {
  50249. dataType = Animation.ANIMATIONTYPE_SIZE;
  50250. }
  50251. if (dataType == undefined) {
  50252. return null;
  50253. }
  50254. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50255. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50256. animation.setKeys(keys);
  50257. if (easingFunction !== undefined) {
  50258. animation.setEasingFunction(easingFunction);
  50259. }
  50260. return animation;
  50261. };
  50262. /**
  50263. * Sets up an animation
  50264. * @param property The property to animate
  50265. * @param animationType The animation type to apply
  50266. * @param framePerSecond The frames per second of the animation
  50267. * @param easingFunction The easing function used in the animation
  50268. * @returns The created animation
  50269. */
  50270. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50271. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50272. animation.setEasingFunction(easingFunction);
  50273. return animation;
  50274. };
  50275. /**
  50276. * Create and start an animation on a node
  50277. * @param name defines the name of the global animation that will be run on all nodes
  50278. * @param node defines the root node where the animation will take place
  50279. * @param targetProperty defines property to animate
  50280. * @param framePerSecond defines the number of frame per second yo use
  50281. * @param totalFrame defines the number of frames in total
  50282. * @param from defines the initial value
  50283. * @param to defines the final value
  50284. * @param loopMode defines which loop mode you want to use (off by default)
  50285. * @param easingFunction defines the easing function to use (linear by default)
  50286. * @param onAnimationEnd defines the callback to call when animation end
  50287. * @returns the animatable created for this animation
  50288. */
  50289. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50290. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50291. if (!animation) {
  50292. return null;
  50293. }
  50294. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50295. };
  50296. /**
  50297. * Create and start an animation on a node and its descendants
  50298. * @param name defines the name of the global animation that will be run on all nodes
  50299. * @param node defines the root node where the animation will take place
  50300. * @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
  50301. * @param targetProperty defines property to animate
  50302. * @param framePerSecond defines the number of frame per second to use
  50303. * @param totalFrame defines the number of frames in total
  50304. * @param from defines the initial value
  50305. * @param to defines the final value
  50306. * @param loopMode defines which loop mode you want to use (off by default)
  50307. * @param easingFunction defines the easing function to use (linear by default)
  50308. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50309. * @returns the list of animatables created for all nodes
  50310. * @example https://www.babylonjs-playground.com/#MH0VLI
  50311. */
  50312. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50313. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50314. if (!animation) {
  50315. return null;
  50316. }
  50317. var scene = node.getScene();
  50318. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50319. };
  50320. /**
  50321. * Creates a new animation, merges it with the existing animations and starts it
  50322. * @param name Name of the animation
  50323. * @param node Node which contains the scene that begins the animations
  50324. * @param targetProperty Specifies which property to animate
  50325. * @param framePerSecond The frames per second of the animation
  50326. * @param totalFrame The total number of frames
  50327. * @param from The frame at the beginning of the animation
  50328. * @param to The frame at the end of the animation
  50329. * @param loopMode Specifies the loop mode of the animation
  50330. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50331. * @param onAnimationEnd Callback to run once the animation is complete
  50332. * @returns Nullable animation
  50333. */
  50334. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50335. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50336. if (!animation) {
  50337. return null;
  50338. }
  50339. node.animations.push(animation);
  50340. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50341. };
  50342. /**
  50343. * Transition property of the Camera to the target Value
  50344. * @param property The property to transition
  50345. * @param targetValue The target Value of the property
  50346. * @param host The object where the property to animate belongs
  50347. * @param scene Scene used to run the animation
  50348. * @param frameRate Framerate (in frame/s) to use
  50349. * @param transition The transition type we want to use
  50350. * @param duration The duration of the animation, in milliseconds
  50351. * @param onAnimationEnd Callback trigger at the end of the animation
  50352. * @returns Nullable animation
  50353. */
  50354. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50355. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50356. if (duration <= 0) {
  50357. host[property] = targetValue;
  50358. if (onAnimationEnd) {
  50359. onAnimationEnd();
  50360. }
  50361. return null;
  50362. }
  50363. var endFrame = frameRate * (duration / 1000);
  50364. transition.setKeys([{
  50365. frame: 0,
  50366. value: host[property].clone ? host[property].clone() : host[property]
  50367. },
  50368. {
  50369. frame: endFrame,
  50370. value: targetValue
  50371. }]);
  50372. if (!host.animations) {
  50373. host.animations = [];
  50374. }
  50375. host.animations.push(transition);
  50376. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50377. animation.onAnimationEnd = onAnimationEnd;
  50378. return animation;
  50379. };
  50380. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50381. /**
  50382. * Return the array of runtime animations currently using this animation
  50383. */
  50384. get: function () {
  50385. return this._runtimeAnimations;
  50386. },
  50387. enumerable: true,
  50388. configurable: true
  50389. });
  50390. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50391. /**
  50392. * Specifies if any of the runtime animations are currently running
  50393. */
  50394. get: function () {
  50395. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50396. var runtimeAnimation = _a[_i];
  50397. if (!runtimeAnimation.isStopped) {
  50398. return true;
  50399. }
  50400. }
  50401. return false;
  50402. },
  50403. enumerable: true,
  50404. configurable: true
  50405. });
  50406. // Methods
  50407. /**
  50408. * Converts the animation to a string
  50409. * @param fullDetails support for multiple levels of logging within scene loading
  50410. * @returns String form of the animation
  50411. */
  50412. Animation.prototype.toString = function (fullDetails) {
  50413. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50414. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50415. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50416. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50417. if (fullDetails) {
  50418. ret += ", Ranges: {";
  50419. var first = true;
  50420. for (var name in this._ranges) {
  50421. if (first) {
  50422. ret += ", ";
  50423. first = false;
  50424. }
  50425. ret += name;
  50426. }
  50427. ret += "}";
  50428. }
  50429. return ret;
  50430. };
  50431. /**
  50432. * Add an event to this animation
  50433. * @param event Event to add
  50434. */
  50435. Animation.prototype.addEvent = function (event) {
  50436. this._events.push(event);
  50437. };
  50438. /**
  50439. * Remove all events found at the given frame
  50440. * @param frame The frame to remove events from
  50441. */
  50442. Animation.prototype.removeEvents = function (frame) {
  50443. for (var index = 0; index < this._events.length; index++) {
  50444. if (this._events[index].frame === frame) {
  50445. this._events.splice(index, 1);
  50446. index--;
  50447. }
  50448. }
  50449. };
  50450. /**
  50451. * Retrieves all the events from the animation
  50452. * @returns Events from the animation
  50453. */
  50454. Animation.prototype.getEvents = function () {
  50455. return this._events;
  50456. };
  50457. /**
  50458. * Creates an animation range
  50459. * @param name Name of the animation range
  50460. * @param from Starting frame of the animation range
  50461. * @param to Ending frame of the animation
  50462. */
  50463. Animation.prototype.createRange = function (name, from, to) {
  50464. // check name not already in use; could happen for bones after serialized
  50465. if (!this._ranges[name]) {
  50466. this._ranges[name] = new AnimationRange(name, from, to);
  50467. }
  50468. };
  50469. /**
  50470. * Deletes an animation range by name
  50471. * @param name Name of the animation range to delete
  50472. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50473. */
  50474. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50475. if (deleteFrames === void 0) { deleteFrames = true; }
  50476. var range = this._ranges[name];
  50477. if (!range) {
  50478. return;
  50479. }
  50480. if (deleteFrames) {
  50481. var from = range.from;
  50482. var to = range.to;
  50483. // this loop MUST go high to low for multiple splices to work
  50484. for (var key = this._keys.length - 1; key >= 0; key--) {
  50485. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50486. this._keys.splice(key, 1);
  50487. }
  50488. }
  50489. }
  50490. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50491. };
  50492. /**
  50493. * Gets the animation range by name, or null if not defined
  50494. * @param name Name of the animation range
  50495. * @returns Nullable animation range
  50496. */
  50497. Animation.prototype.getRange = function (name) {
  50498. return this._ranges[name];
  50499. };
  50500. /**
  50501. * Gets the key frames from the animation
  50502. * @returns The key frames of the animation
  50503. */
  50504. Animation.prototype.getKeys = function () {
  50505. return this._keys;
  50506. };
  50507. /**
  50508. * Gets the highest frame rate of the animation
  50509. * @returns Highest frame rate of the animation
  50510. */
  50511. Animation.prototype.getHighestFrame = function () {
  50512. var ret = 0;
  50513. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50514. if (ret < this._keys[key].frame) {
  50515. ret = this._keys[key].frame;
  50516. }
  50517. }
  50518. return ret;
  50519. };
  50520. /**
  50521. * Gets the easing function of the animation
  50522. * @returns Easing function of the animation
  50523. */
  50524. Animation.prototype.getEasingFunction = function () {
  50525. return this._easingFunction;
  50526. };
  50527. /**
  50528. * Sets the easing function of the animation
  50529. * @param easingFunction A custom mathematical formula for animation
  50530. */
  50531. Animation.prototype.setEasingFunction = function (easingFunction) {
  50532. this._easingFunction = easingFunction;
  50533. };
  50534. /**
  50535. * Interpolates a scalar linearly
  50536. * @param startValue Start value of the animation curve
  50537. * @param endValue End value of the animation curve
  50538. * @param gradient Scalar amount to interpolate
  50539. * @returns Interpolated scalar value
  50540. */
  50541. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50542. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50543. };
  50544. /**
  50545. * Interpolates a scalar cubically
  50546. * @param startValue Start value of the animation curve
  50547. * @param outTangent End tangent of the animation
  50548. * @param endValue End value of the animation curve
  50549. * @param inTangent Start tangent of the animation curve
  50550. * @param gradient Scalar amount to interpolate
  50551. * @returns Interpolated scalar value
  50552. */
  50553. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50554. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50555. };
  50556. /**
  50557. * Interpolates a quaternion using a spherical linear interpolation
  50558. * @param startValue Start value of the animation curve
  50559. * @param endValue End value of the animation curve
  50560. * @param gradient Scalar amount to interpolate
  50561. * @returns Interpolated quaternion value
  50562. */
  50563. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50564. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50565. };
  50566. /**
  50567. * Interpolates a quaternion cubically
  50568. * @param startValue Start value of the animation curve
  50569. * @param outTangent End tangent of the animation curve
  50570. * @param endValue End value of the animation curve
  50571. * @param inTangent Start tangent of the animation curve
  50572. * @param gradient Scalar amount to interpolate
  50573. * @returns Interpolated quaternion value
  50574. */
  50575. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50576. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50577. };
  50578. /**
  50579. * Interpolates a Vector3 linearl
  50580. * @param startValue Start value of the animation curve
  50581. * @param endValue End value of the animation curve
  50582. * @param gradient Scalar amount to interpolate
  50583. * @returns Interpolated scalar value
  50584. */
  50585. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50586. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50587. };
  50588. /**
  50589. * Interpolates a Vector3 cubically
  50590. * @param startValue Start value of the animation curve
  50591. * @param outTangent End tangent of the animation
  50592. * @param endValue End value of the animation curve
  50593. * @param inTangent Start tangent of the animation curve
  50594. * @param gradient Scalar amount to interpolate
  50595. * @returns InterpolatedVector3 value
  50596. */
  50597. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50598. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50599. };
  50600. /**
  50601. * Interpolates a Vector2 linearly
  50602. * @param startValue Start value of the animation curve
  50603. * @param endValue End value of the animation curve
  50604. * @param gradient Scalar amount to interpolate
  50605. * @returns Interpolated Vector2 value
  50606. */
  50607. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50608. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50609. };
  50610. /**
  50611. * Interpolates a Vector2 cubically
  50612. * @param startValue Start value of the animation curve
  50613. * @param outTangent End tangent of the animation
  50614. * @param endValue End value of the animation curve
  50615. * @param inTangent Start tangent of the animation curve
  50616. * @param gradient Scalar amount to interpolate
  50617. * @returns Interpolated Vector2 value
  50618. */
  50619. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50620. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50621. };
  50622. /**
  50623. * Interpolates a size linearly
  50624. * @param startValue Start value of the animation curve
  50625. * @param endValue End value of the animation curve
  50626. * @param gradient Scalar amount to interpolate
  50627. * @returns Interpolated Size value
  50628. */
  50629. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50630. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50631. };
  50632. /**
  50633. * Interpolates a Color3 linearly
  50634. * @param startValue Start value of the animation curve
  50635. * @param endValue End value of the animation curve
  50636. * @param gradient Scalar amount to interpolate
  50637. * @returns Interpolated Color3 value
  50638. */
  50639. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50640. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50641. };
  50642. /**
  50643. * @hidden Internal use only
  50644. */
  50645. Animation.prototype._getKeyValue = function (value) {
  50646. if (typeof value === "function") {
  50647. return value();
  50648. }
  50649. return value;
  50650. };
  50651. /**
  50652. * @hidden Internal use only
  50653. */
  50654. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50655. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50656. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50657. }
  50658. var keys = this.getKeys();
  50659. // Try to get a hash to find the right key
  50660. 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));
  50661. if (keys[startKeyIndex].frame >= currentFrame) {
  50662. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50663. startKeyIndex--;
  50664. }
  50665. }
  50666. for (var key = startKeyIndex; key < keys.length; key++) {
  50667. var endKey = keys[key + 1];
  50668. if (endKey.frame >= currentFrame) {
  50669. var startKey = keys[key];
  50670. var startValue = this._getKeyValue(startKey.value);
  50671. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50672. return startValue;
  50673. }
  50674. var endValue = this._getKeyValue(endKey.value);
  50675. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50676. var frameDelta = endKey.frame - startKey.frame;
  50677. // gradient : percent of currentFrame between the frame inf and the frame sup
  50678. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50679. // check for easingFunction and correction of gradient
  50680. var easingFunction = this.getEasingFunction();
  50681. if (easingFunction != null) {
  50682. gradient = easingFunction.ease(gradient);
  50683. }
  50684. switch (this.dataType) {
  50685. // Float
  50686. case Animation.ANIMATIONTYPE_FLOAT:
  50687. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50688. switch (loopMode) {
  50689. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50690. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50691. return floatValue;
  50692. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50693. return offsetValue * repeatCount + floatValue;
  50694. }
  50695. break;
  50696. // Quaternion
  50697. case Animation.ANIMATIONTYPE_QUATERNION:
  50698. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50699. switch (loopMode) {
  50700. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50701. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50702. return quatValue;
  50703. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50704. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50705. }
  50706. return quatValue;
  50707. // Vector3
  50708. case Animation.ANIMATIONTYPE_VECTOR3:
  50709. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50710. switch (loopMode) {
  50711. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50712. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50713. return vec3Value;
  50714. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50715. return vec3Value.add(offsetValue.scale(repeatCount));
  50716. }
  50717. // Vector2
  50718. case Animation.ANIMATIONTYPE_VECTOR2:
  50719. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50720. switch (loopMode) {
  50721. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50722. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50723. return vec2Value;
  50724. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50725. return vec2Value.add(offsetValue.scale(repeatCount));
  50726. }
  50727. // Size
  50728. case Animation.ANIMATIONTYPE_SIZE:
  50729. switch (loopMode) {
  50730. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50731. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50732. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50733. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50734. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50735. }
  50736. // Color3
  50737. case Animation.ANIMATIONTYPE_COLOR3:
  50738. switch (loopMode) {
  50739. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50740. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50741. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50742. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50743. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50744. }
  50745. // Matrix
  50746. case Animation.ANIMATIONTYPE_MATRIX:
  50747. switch (loopMode) {
  50748. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50749. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50750. if (Animation.AllowMatricesInterpolation) {
  50751. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50752. }
  50753. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50754. return startValue;
  50755. }
  50756. default:
  50757. break;
  50758. }
  50759. break;
  50760. }
  50761. }
  50762. return this._getKeyValue(keys[keys.length - 1].value);
  50763. };
  50764. /**
  50765. * Defines the function to use to interpolate matrices
  50766. * @param startValue defines the start matrix
  50767. * @param endValue defines the end matrix
  50768. * @param gradient defines the gradient between both matrices
  50769. * @param result defines an optional target matrix where to store the interpolation
  50770. * @returns the interpolated matrix
  50771. */
  50772. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50773. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50774. if (result) {
  50775. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50776. return result;
  50777. }
  50778. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50779. }
  50780. if (result) {
  50781. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50782. return result;
  50783. }
  50784. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50785. };
  50786. /**
  50787. * Makes a copy of the animation
  50788. * @returns Cloned animation
  50789. */
  50790. Animation.prototype.clone = function () {
  50791. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50792. clone.enableBlending = this.enableBlending;
  50793. clone.blendingSpeed = this.blendingSpeed;
  50794. if (this._keys) {
  50795. clone.setKeys(this._keys);
  50796. }
  50797. if (this._ranges) {
  50798. clone._ranges = {};
  50799. for (var name in this._ranges) {
  50800. var range = this._ranges[name];
  50801. if (!range) {
  50802. continue;
  50803. }
  50804. clone._ranges[name] = range.clone();
  50805. }
  50806. }
  50807. return clone;
  50808. };
  50809. /**
  50810. * Sets the key frames of the animation
  50811. * @param values The animation key frames to set
  50812. */
  50813. Animation.prototype.setKeys = function (values) {
  50814. this._keys = values.slice(0);
  50815. };
  50816. /**
  50817. * Serializes the animation to an object
  50818. * @returns Serialized object
  50819. */
  50820. Animation.prototype.serialize = function () {
  50821. var serializationObject = {};
  50822. serializationObject.name = this.name;
  50823. serializationObject.property = this.targetProperty;
  50824. serializationObject.framePerSecond = this.framePerSecond;
  50825. serializationObject.dataType = this.dataType;
  50826. serializationObject.loopBehavior = this.loopMode;
  50827. serializationObject.enableBlending = this.enableBlending;
  50828. serializationObject.blendingSpeed = this.blendingSpeed;
  50829. var dataType = this.dataType;
  50830. serializationObject.keys = [];
  50831. var keys = this.getKeys();
  50832. for (var index = 0; index < keys.length; index++) {
  50833. var animationKey = keys[index];
  50834. var key = {};
  50835. key.frame = animationKey.frame;
  50836. switch (dataType) {
  50837. case Animation.ANIMATIONTYPE_FLOAT:
  50838. key.values = [animationKey.value];
  50839. break;
  50840. case Animation.ANIMATIONTYPE_QUATERNION:
  50841. case Animation.ANIMATIONTYPE_MATRIX:
  50842. case Animation.ANIMATIONTYPE_VECTOR3:
  50843. case Animation.ANIMATIONTYPE_COLOR3:
  50844. key.values = animationKey.value.asArray();
  50845. break;
  50846. }
  50847. serializationObject.keys.push(key);
  50848. }
  50849. serializationObject.ranges = [];
  50850. for (var name in this._ranges) {
  50851. var source = this._ranges[name];
  50852. if (!source) {
  50853. continue;
  50854. }
  50855. var range = {};
  50856. range.name = name;
  50857. range.from = source.from;
  50858. range.to = source.to;
  50859. serializationObject.ranges.push(range);
  50860. }
  50861. return serializationObject;
  50862. };
  50863. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50864. /**
  50865. * Get the float animation type
  50866. */
  50867. get: function () {
  50868. return Animation._ANIMATIONTYPE_FLOAT;
  50869. },
  50870. enumerable: true,
  50871. configurable: true
  50872. });
  50873. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50874. /**
  50875. * Get the Vector3 animation type
  50876. */
  50877. get: function () {
  50878. return Animation._ANIMATIONTYPE_VECTOR3;
  50879. },
  50880. enumerable: true,
  50881. configurable: true
  50882. });
  50883. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50884. /**
  50885. * Get the Vectpr2 animation type
  50886. */
  50887. get: function () {
  50888. return Animation._ANIMATIONTYPE_VECTOR2;
  50889. },
  50890. enumerable: true,
  50891. configurable: true
  50892. });
  50893. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50894. /**
  50895. * Get the Size animation type
  50896. */
  50897. get: function () {
  50898. return Animation._ANIMATIONTYPE_SIZE;
  50899. },
  50900. enumerable: true,
  50901. configurable: true
  50902. });
  50903. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50904. /**
  50905. * Get the Quaternion animation type
  50906. */
  50907. get: function () {
  50908. return Animation._ANIMATIONTYPE_QUATERNION;
  50909. },
  50910. enumerable: true,
  50911. configurable: true
  50912. });
  50913. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50914. /**
  50915. * Get the Matrix animation type
  50916. */
  50917. get: function () {
  50918. return Animation._ANIMATIONTYPE_MATRIX;
  50919. },
  50920. enumerable: true,
  50921. configurable: true
  50922. });
  50923. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50924. /**
  50925. * Get the Color3 animation type
  50926. */
  50927. get: function () {
  50928. return Animation._ANIMATIONTYPE_COLOR3;
  50929. },
  50930. enumerable: true,
  50931. configurable: true
  50932. });
  50933. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50934. /**
  50935. * Get the Relative Loop Mode
  50936. */
  50937. get: function () {
  50938. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50939. },
  50940. enumerable: true,
  50941. configurable: true
  50942. });
  50943. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50944. /**
  50945. * Get the Cycle Loop Mode
  50946. */
  50947. get: function () {
  50948. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50949. },
  50950. enumerable: true,
  50951. configurable: true
  50952. });
  50953. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50954. /**
  50955. * Get the Constant Loop Mode
  50956. */
  50957. get: function () {
  50958. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50959. },
  50960. enumerable: true,
  50961. configurable: true
  50962. });
  50963. /**
  50964. * Parses an animation object and creates an animation
  50965. * @param parsedAnimation Parsed animation object
  50966. * @returns Animation object
  50967. */
  50968. Animation.Parse = function (parsedAnimation) {
  50969. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50970. var dataType = parsedAnimation.dataType;
  50971. var keys = [];
  50972. var data;
  50973. var index;
  50974. if (parsedAnimation.enableBlending) {
  50975. animation.enableBlending = parsedAnimation.enableBlending;
  50976. }
  50977. if (parsedAnimation.blendingSpeed) {
  50978. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50979. }
  50980. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50981. var key = parsedAnimation.keys[index];
  50982. var inTangent;
  50983. var outTangent;
  50984. switch (dataType) {
  50985. case Animation.ANIMATIONTYPE_FLOAT:
  50986. data = key.values[0];
  50987. if (key.values.length >= 1) {
  50988. inTangent = key.values[1];
  50989. }
  50990. if (key.values.length >= 2) {
  50991. outTangent = key.values[2];
  50992. }
  50993. break;
  50994. case Animation.ANIMATIONTYPE_QUATERNION:
  50995. data = BABYLON.Quaternion.FromArray(key.values);
  50996. if (key.values.length >= 8) {
  50997. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50998. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50999. inTangent = _inTangent;
  51000. }
  51001. }
  51002. if (key.values.length >= 12) {
  51003. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51004. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51005. outTangent = _outTangent;
  51006. }
  51007. }
  51008. break;
  51009. case Animation.ANIMATIONTYPE_MATRIX:
  51010. data = BABYLON.Matrix.FromArray(key.values);
  51011. break;
  51012. case Animation.ANIMATIONTYPE_COLOR3:
  51013. data = BABYLON.Color3.FromArray(key.values);
  51014. break;
  51015. case Animation.ANIMATIONTYPE_VECTOR3:
  51016. default:
  51017. data = BABYLON.Vector3.FromArray(key.values);
  51018. break;
  51019. }
  51020. var keyData = {};
  51021. keyData.frame = key.frame;
  51022. keyData.value = data;
  51023. if (inTangent != undefined) {
  51024. keyData.inTangent = inTangent;
  51025. }
  51026. if (outTangent != undefined) {
  51027. keyData.outTangent = outTangent;
  51028. }
  51029. keys.push(keyData);
  51030. }
  51031. animation.setKeys(keys);
  51032. if (parsedAnimation.ranges) {
  51033. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51034. data = parsedAnimation.ranges[index];
  51035. animation.createRange(data.name, data.from, data.to);
  51036. }
  51037. }
  51038. return animation;
  51039. };
  51040. /**
  51041. * Appends the serialized animations from the source animations
  51042. * @param source Source containing the animations
  51043. * @param destination Target to store the animations
  51044. */
  51045. Animation.AppendSerializedAnimations = function (source, destination) {
  51046. if (source.animations) {
  51047. destination.animations = [];
  51048. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51049. var animation = source.animations[animationIndex];
  51050. destination.animations.push(animation.serialize());
  51051. }
  51052. }
  51053. };
  51054. /**
  51055. * Use matrix interpolation instead of using direct key value when animating matrices
  51056. */
  51057. Animation.AllowMatricesInterpolation = false;
  51058. /**
  51059. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51060. */
  51061. Animation.AllowMatrixDecomposeForInterpolation = true;
  51062. // Statics
  51063. /**
  51064. * Float animation type
  51065. */
  51066. Animation._ANIMATIONTYPE_FLOAT = 0;
  51067. /**
  51068. * Vector3 animation type
  51069. */
  51070. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51071. /**
  51072. * Quaternion animation type
  51073. */
  51074. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51075. /**
  51076. * Matrix animation type
  51077. */
  51078. Animation._ANIMATIONTYPE_MATRIX = 3;
  51079. /**
  51080. * Color3 animation type
  51081. */
  51082. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51083. /**
  51084. * Vector2 animation type
  51085. */
  51086. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51087. /**
  51088. * Size animation type
  51089. */
  51090. Animation._ANIMATIONTYPE_SIZE = 6;
  51091. /**
  51092. * Relative Loop Mode
  51093. */
  51094. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51095. /**
  51096. * Cycle Loop Mode
  51097. */
  51098. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51099. /**
  51100. * Constant Loop Mode
  51101. */
  51102. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51103. return Animation;
  51104. }());
  51105. BABYLON.Animation = Animation;
  51106. })(BABYLON || (BABYLON = {}));
  51107. //# sourceMappingURL=babylon.animation.js.map
  51108. var BABYLON;
  51109. (function (BABYLON) {
  51110. /**
  51111. * This class defines the direct association between an animation and a target
  51112. */
  51113. var TargetedAnimation = /** @class */ (function () {
  51114. function TargetedAnimation() {
  51115. }
  51116. return TargetedAnimation;
  51117. }());
  51118. BABYLON.TargetedAnimation = TargetedAnimation;
  51119. /**
  51120. * Use this class to create coordinated animations on multiple targets
  51121. */
  51122. var AnimationGroup = /** @class */ (function () {
  51123. function AnimationGroup(name, scene) {
  51124. if (scene === void 0) { scene = null; }
  51125. this.name = name;
  51126. this._targetedAnimations = new Array();
  51127. this._animatables = new Array();
  51128. this._from = Number.MAX_VALUE;
  51129. this._to = -Number.MAX_VALUE;
  51130. this._speedRatio = 1;
  51131. this.onAnimationEndObservable = new BABYLON.Observable();
  51132. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51133. this._scene.animationGroups.push(this);
  51134. }
  51135. Object.defineProperty(AnimationGroup.prototype, "from", {
  51136. /**
  51137. * Gets the first frame
  51138. */
  51139. get: function () {
  51140. return this._from;
  51141. },
  51142. enumerable: true,
  51143. configurable: true
  51144. });
  51145. Object.defineProperty(AnimationGroup.prototype, "to", {
  51146. /**
  51147. * Gets the last frame
  51148. */
  51149. get: function () {
  51150. return this._to;
  51151. },
  51152. enumerable: true,
  51153. configurable: true
  51154. });
  51155. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51156. /**
  51157. * Define if the animations are started
  51158. */
  51159. get: function () {
  51160. return this._isStarted;
  51161. },
  51162. enumerable: true,
  51163. configurable: true
  51164. });
  51165. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51166. /**
  51167. * Gets or sets the speed ratio to use for all animations
  51168. */
  51169. get: function () {
  51170. return this._speedRatio;
  51171. },
  51172. /**
  51173. * Gets or sets the speed ratio to use for all animations
  51174. */
  51175. set: function (value) {
  51176. if (this._speedRatio === value) {
  51177. return;
  51178. }
  51179. this._speedRatio = value;
  51180. for (var index = 0; index < this._animatables.length; index++) {
  51181. var animatable = this._animatables[index];
  51182. animatable.speedRatio = this._speedRatio;
  51183. }
  51184. },
  51185. enumerable: true,
  51186. configurable: true
  51187. });
  51188. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51189. /**
  51190. * Gets the targeted animations for this animation group
  51191. */
  51192. get: function () {
  51193. return this._targetedAnimations;
  51194. },
  51195. enumerable: true,
  51196. configurable: true
  51197. });
  51198. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51199. /**
  51200. * returning the list of animatables controlled by this animation group.
  51201. */
  51202. get: function () {
  51203. return this._animatables;
  51204. },
  51205. enumerable: true,
  51206. configurable: true
  51207. });
  51208. /**
  51209. * Add an animation (with its target) in the group
  51210. * @param animation defines the animation we want to add
  51211. * @param target defines the target of the animation
  51212. * @returns the {BABYLON.TargetedAnimation} object
  51213. */
  51214. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51215. var targetedAnimation = {
  51216. animation: animation,
  51217. target: target
  51218. };
  51219. var keys = animation.getKeys();
  51220. if (this._from > keys[0].frame) {
  51221. this._from = keys[0].frame;
  51222. }
  51223. if (this._to < keys[keys.length - 1].frame) {
  51224. this._to = keys[keys.length - 1].frame;
  51225. }
  51226. this._targetedAnimations.push(targetedAnimation);
  51227. return targetedAnimation;
  51228. };
  51229. /**
  51230. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51231. * It can add constant keys at begin or end
  51232. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  51233. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  51234. */
  51235. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51236. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  51237. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  51238. beginFrame = Math.max(beginFrame, this._from);
  51239. endFrame = Math.min(endFrame, this._to);
  51240. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51241. var targetedAnimation = this._targetedAnimations[index];
  51242. var keys = targetedAnimation.animation.getKeys();
  51243. var startKey = keys[0];
  51244. var endKey = keys[keys.length - 1];
  51245. if (startKey.frame > beginFrame) {
  51246. var newKey = {
  51247. frame: beginFrame,
  51248. value: startKey.value,
  51249. inTangent: startKey.inTangent,
  51250. outTangent: startKey.outTangent,
  51251. interpolation: startKey.interpolation
  51252. };
  51253. keys.splice(0, 0, newKey);
  51254. }
  51255. if (endKey.frame < endFrame) {
  51256. var newKey = {
  51257. frame: endFrame,
  51258. value: endKey.value,
  51259. inTangent: endKey.outTangent,
  51260. outTangent: endKey.outTangent,
  51261. interpolation: endKey.interpolation
  51262. };
  51263. keys.push(newKey);
  51264. }
  51265. }
  51266. return this;
  51267. };
  51268. /**
  51269. * Start all animations on given targets
  51270. * @param loop defines if animations must loop
  51271. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51272. * @param from defines the from key (optional)
  51273. * @param to defines the to key (optional)
  51274. * @returns the current animation group
  51275. */
  51276. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51277. var _this = this;
  51278. if (loop === void 0) { loop = false; }
  51279. if (speedRatio === void 0) { speedRatio = 1; }
  51280. if (this._isStarted || this._targetedAnimations.length === 0) {
  51281. return this;
  51282. }
  51283. var _loop_1 = function (targetedAnimation) {
  51284. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51285. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51286. }));
  51287. };
  51288. var this_1 = this;
  51289. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51290. var targetedAnimation = _a[_i];
  51291. _loop_1(targetedAnimation);
  51292. }
  51293. this._speedRatio = speedRatio;
  51294. this._isStarted = true;
  51295. return this;
  51296. };
  51297. /**
  51298. * Pause all animations
  51299. */
  51300. AnimationGroup.prototype.pause = function () {
  51301. if (!this._isStarted) {
  51302. return this;
  51303. }
  51304. for (var index = 0; index < this._animatables.length; index++) {
  51305. var animatable = this._animatables[index];
  51306. animatable.pause();
  51307. }
  51308. return this;
  51309. };
  51310. /**
  51311. * Play all animations to initial state
  51312. * This function will start() the animations if they were not started or will restart() them if they were paused
  51313. * @param loop defines if animations must loop
  51314. */
  51315. AnimationGroup.prototype.play = function (loop) {
  51316. if (this.isStarted) {
  51317. if (loop !== undefined) {
  51318. for (var index = 0; index < this._animatables.length; index++) {
  51319. var animatable = this._animatables[index];
  51320. animatable.loopAnimation = loop;
  51321. }
  51322. }
  51323. this.restart();
  51324. }
  51325. else {
  51326. this.start(loop, this._speedRatio);
  51327. }
  51328. return this;
  51329. };
  51330. /**
  51331. * Reset all animations to initial state
  51332. */
  51333. AnimationGroup.prototype.reset = function () {
  51334. if (!this._isStarted) {
  51335. return this;
  51336. }
  51337. for (var index = 0; index < this._animatables.length; index++) {
  51338. var animatable = this._animatables[index];
  51339. animatable.reset();
  51340. }
  51341. return this;
  51342. };
  51343. /**
  51344. * Restart animations from key 0
  51345. */
  51346. AnimationGroup.prototype.restart = function () {
  51347. if (!this._isStarted) {
  51348. return this;
  51349. }
  51350. for (var index = 0; index < this._animatables.length; index++) {
  51351. var animatable = this._animatables[index];
  51352. animatable.restart();
  51353. }
  51354. return this;
  51355. };
  51356. /**
  51357. * Stop all animations
  51358. */
  51359. AnimationGroup.prototype.stop = function () {
  51360. if (!this._isStarted) {
  51361. return this;
  51362. }
  51363. for (var index = 0; index < this._animatables.length; index++) {
  51364. var animatable = this._animatables[index];
  51365. animatable.stop();
  51366. }
  51367. this._isStarted = false;
  51368. return this;
  51369. };
  51370. /**
  51371. * Set animation weight for all animatables
  51372. * @param weight defines the weight to use
  51373. * @return the animationGroup
  51374. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51375. */
  51376. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51377. for (var index = 0; index < this._animatables.length; index++) {
  51378. var animatable = this._animatables[index];
  51379. animatable.weight = weight;
  51380. }
  51381. return this;
  51382. };
  51383. /**
  51384. * Synchronize and normalize all animatables with a source animatable
  51385. * @param root defines the root animatable to synchronize with
  51386. * @return the animationGroup
  51387. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51388. */
  51389. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51390. for (var index = 0; index < this._animatables.length; index++) {
  51391. var animatable = this._animatables[index];
  51392. animatable.syncWith(root);
  51393. }
  51394. return this;
  51395. };
  51396. /**
  51397. * Goes to a specific frame in this animation group
  51398. * @param frame the frame number to go to
  51399. * @return the animationGroup
  51400. */
  51401. AnimationGroup.prototype.goToFrame = function (frame) {
  51402. if (!this._isStarted) {
  51403. return this;
  51404. }
  51405. for (var index = 0; index < this._animatables.length; index++) {
  51406. var animatable = this._animatables[index];
  51407. animatable.goToFrame(frame);
  51408. }
  51409. return this;
  51410. };
  51411. /**
  51412. * Dispose all associated resources
  51413. */
  51414. AnimationGroup.prototype.dispose = function () {
  51415. this._targetedAnimations = [];
  51416. this._animatables = [];
  51417. var index = this._scene.animationGroups.indexOf(this);
  51418. if (index > -1) {
  51419. this._scene.animationGroups.splice(index, 1);
  51420. }
  51421. };
  51422. return AnimationGroup;
  51423. }());
  51424. BABYLON.AnimationGroup = AnimationGroup;
  51425. })(BABYLON || (BABYLON = {}));
  51426. //# sourceMappingURL=babylon.animationGroup.js.map
  51427. var BABYLON;
  51428. (function (BABYLON) {
  51429. /**
  51430. * Defines a runtime animation
  51431. */
  51432. var RuntimeAnimation = /** @class */ (function () {
  51433. /**
  51434. * Create a new RuntimeAnimation object
  51435. * @param target defines the target of the animation
  51436. * @param animation defines the source animation object
  51437. * @param scene defines the hosting scene
  51438. * @param host defines the initiating Animatable
  51439. */
  51440. function RuntimeAnimation(target, animation, scene, host) {
  51441. /**
  51442. * The current frame of the runtime animation
  51443. */
  51444. this._currentFrame = 0;
  51445. /**
  51446. * The offsets cache of the runtime animation
  51447. */
  51448. this._offsetsCache = {};
  51449. /**
  51450. * The high limits cache of the runtime animation
  51451. */
  51452. this._highLimitsCache = {};
  51453. /**
  51454. * Specifies if the runtime animation has been stopped
  51455. */
  51456. this._stopped = false;
  51457. /**
  51458. * The blending factor of the runtime animation
  51459. */
  51460. this._blendingFactor = 0;
  51461. /**
  51462. * The target path of the runtime animation
  51463. */
  51464. this._targetPath = "";
  51465. /**
  51466. * The weight of the runtime animation
  51467. */
  51468. this._weight = 1.0;
  51469. /**
  51470. * The ratio offset of the runtime animation
  51471. */
  51472. this._ratioOffset = 0;
  51473. /**
  51474. * The previous delay of the runtime animation
  51475. */
  51476. this._previousDelay = 0;
  51477. /**
  51478. * The previous ratio of the runtime animation
  51479. */
  51480. this._previousRatio = 0;
  51481. this._animation = animation;
  51482. this._target = target;
  51483. this._scene = scene;
  51484. this._host = host;
  51485. animation._runtimeAnimations.push(this);
  51486. }
  51487. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51488. /**
  51489. * Gets the current frame of the runtime animation
  51490. */
  51491. get: function () {
  51492. return this._currentFrame;
  51493. },
  51494. enumerable: true,
  51495. configurable: true
  51496. });
  51497. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51498. /**
  51499. * Gets the weight of the runtime animation
  51500. */
  51501. get: function () {
  51502. return this._weight;
  51503. },
  51504. enumerable: true,
  51505. configurable: true
  51506. });
  51507. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51508. /**
  51509. * Gets the original value of the runtime animation
  51510. */
  51511. get: function () {
  51512. return this._originalValue;
  51513. },
  51514. enumerable: true,
  51515. configurable: true
  51516. });
  51517. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51518. /**
  51519. * Gets the current value of the runtime animation
  51520. */
  51521. get: function () {
  51522. return this._currentValue;
  51523. },
  51524. enumerable: true,
  51525. configurable: true
  51526. });
  51527. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51528. /**
  51529. * Gets the target path of the runtime animation
  51530. */
  51531. get: function () {
  51532. return this._targetPath;
  51533. },
  51534. enumerable: true,
  51535. configurable: true
  51536. });
  51537. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51538. /**
  51539. * Gets the actual target of the runtime animation
  51540. */
  51541. get: function () {
  51542. return this._activeTarget;
  51543. },
  51544. enumerable: true,
  51545. configurable: true
  51546. });
  51547. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51548. /**
  51549. * Gets the animation from the runtime animation
  51550. */
  51551. get: function () {
  51552. return this._animation;
  51553. },
  51554. enumerable: true,
  51555. configurable: true
  51556. });
  51557. /**
  51558. * Resets the runtime animation to the beginning
  51559. */
  51560. RuntimeAnimation.prototype.reset = function () {
  51561. this._offsetsCache = {};
  51562. this._highLimitsCache = {};
  51563. this._currentFrame = 0;
  51564. this._blendingFactor = 0;
  51565. this._originalValue = null;
  51566. };
  51567. /**
  51568. * Specifies if the runtime animation is stopped
  51569. * @returns Boolean specifying if the runtime animation is stopped
  51570. */
  51571. RuntimeAnimation.prototype.isStopped = function () {
  51572. return this._stopped;
  51573. };
  51574. /**
  51575. * Disposes of the runtime animation
  51576. */
  51577. RuntimeAnimation.prototype.dispose = function () {
  51578. var index = this._animation.runtimeAnimations.indexOf(this);
  51579. if (index > -1) {
  51580. this._animation.runtimeAnimations.splice(index, 1);
  51581. }
  51582. };
  51583. /**
  51584. * Interpolates the animation from the current frame
  51585. * @param currentFrame The frame to interpolate the animation to
  51586. * @param repeatCount The number of times that the animation should loop
  51587. * @param loopMode The type of looping mode to use
  51588. * @param offsetValue Animation offset value
  51589. * @param highLimitValue The high limit value
  51590. * @returns The interpolated value
  51591. */
  51592. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51593. this._currentFrame = currentFrame;
  51594. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51595. this._workValue = BABYLON.Matrix.Zero();
  51596. }
  51597. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51598. };
  51599. /**
  51600. * Affect the interpolated value to the target
  51601. * @param currentValue defines the value computed by the animation
  51602. * @param weight defines the weight to apply to this value
  51603. */
  51604. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51605. if (weight === void 0) { weight = 1.0; }
  51606. if (this._target instanceof Array) {
  51607. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51608. var target = _a[_i];
  51609. this._setValue(target, currentValue, weight);
  51610. }
  51611. }
  51612. else {
  51613. this._setValue(this._target, currentValue, weight);
  51614. }
  51615. };
  51616. /**
  51617. * Sets the value of the runtime animation
  51618. * @param target The target property of the runtime animation
  51619. * @param currentValue The current value to use for the runtime animation
  51620. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51621. */
  51622. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51623. if (weight === void 0) { weight = 1.0; }
  51624. // Set value
  51625. var path;
  51626. var destination;
  51627. var targetPropertyPath = this._animation.targetPropertyPath;
  51628. if (targetPropertyPath.length > 1) {
  51629. var property = target[targetPropertyPath[0]];
  51630. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51631. property = property[targetPropertyPath[index]];
  51632. }
  51633. path = targetPropertyPath[targetPropertyPath.length - 1];
  51634. destination = property;
  51635. }
  51636. else {
  51637. path = targetPropertyPath[0];
  51638. destination = target;
  51639. }
  51640. this._targetPath = path;
  51641. this._activeTarget = destination;
  51642. this._weight = weight;
  51643. // Blending
  51644. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51645. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51646. if (enableBlending && this._blendingFactor <= 1.0) {
  51647. if (!this._originalBlendValue) {
  51648. var originalValue = destination[path];
  51649. if (originalValue.clone) {
  51650. this._originalBlendValue = originalValue.clone();
  51651. }
  51652. else {
  51653. this._originalBlendValue = originalValue;
  51654. }
  51655. }
  51656. }
  51657. if (weight !== -1.0) {
  51658. if (!this._originalValue) {
  51659. var originalValue = void 0;
  51660. if (destination.getRestPose && path === "_matrix") { // For bones
  51661. originalValue = destination.getRestPose();
  51662. }
  51663. else {
  51664. originalValue = destination[path];
  51665. }
  51666. if (originalValue.clone) {
  51667. this._originalValue = originalValue.clone();
  51668. }
  51669. else {
  51670. this._originalValue = originalValue;
  51671. }
  51672. }
  51673. }
  51674. if (enableBlending && this._blendingFactor <= 1.0) {
  51675. if (this._originalBlendValue.m) { // Matrix
  51676. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51677. if (this._currentValue) {
  51678. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51679. }
  51680. else {
  51681. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51682. }
  51683. }
  51684. else {
  51685. if (this._currentValue) {
  51686. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51687. }
  51688. else {
  51689. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51690. }
  51691. }
  51692. }
  51693. else {
  51694. var constructor = this._originalBlendValue.constructor;
  51695. if (constructor.Lerp) { // Lerp supported
  51696. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51697. }
  51698. else if (constructor.Slerp) { // Slerp supported
  51699. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51700. }
  51701. else if (this._originalBlendValue.toFixed) { // Number
  51702. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51703. }
  51704. else { // Blending not supported
  51705. this._currentValue = currentValue;
  51706. }
  51707. }
  51708. this._blendingFactor += blendingSpeed;
  51709. }
  51710. else {
  51711. this._currentValue = currentValue;
  51712. }
  51713. if (weight !== -1.0) {
  51714. this._scene._registerTargetForLateAnimationBinding(this);
  51715. }
  51716. else {
  51717. destination[path] = this._currentValue;
  51718. }
  51719. if (target.markAsDirty) {
  51720. target.markAsDirty(this._animation.targetProperty);
  51721. }
  51722. };
  51723. /**
  51724. * Gets the loop pmode of the runtime animation
  51725. * @returns Loop Mode
  51726. */
  51727. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51728. if (this._target && this._target.animationPropertiesOverride) {
  51729. return this._target.animationPropertiesOverride.loopMode;
  51730. }
  51731. return this._animation.loopMode;
  51732. };
  51733. /**
  51734. * Move the current animation to a given frame
  51735. * @param frame defines the frame to move to
  51736. */
  51737. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51738. var keys = this._animation.getKeys();
  51739. if (frame < keys[0].frame) {
  51740. frame = keys[0].frame;
  51741. }
  51742. else if (frame > keys[keys.length - 1].frame) {
  51743. frame = keys[keys.length - 1].frame;
  51744. }
  51745. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51746. this.setValue(currentValue, -1);
  51747. };
  51748. /**
  51749. * @hidden Internal use only
  51750. */
  51751. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51752. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51753. this._ratioOffset = this._previousRatio - newRatio;
  51754. };
  51755. /**
  51756. * Execute the current animation
  51757. * @param delay defines the delay to add to the current frame
  51758. * @param from defines the lower bound of the animation range
  51759. * @param to defines the upper bound of the animation range
  51760. * @param loop defines if the current animation must loop
  51761. * @param speedRatio defines the current speed ratio
  51762. * @param weight defines the weight of the animation (default is -1 so no weight)
  51763. * @returns a boolean indicating if the animation has ended
  51764. */
  51765. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51766. if (weight === void 0) { weight = -1.0; }
  51767. var targetPropertyPath = this._animation.targetPropertyPath;
  51768. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51769. this._stopped = true;
  51770. return false;
  51771. }
  51772. var returnValue = true;
  51773. var keys = this._animation.getKeys();
  51774. // Adding a start key at frame 0 if missing
  51775. if (keys[0].frame !== 0) {
  51776. var newKey = { frame: 0, value: keys[0].value };
  51777. keys.splice(0, 0, newKey);
  51778. }
  51779. // Check limits
  51780. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51781. from = keys[0].frame;
  51782. }
  51783. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51784. to = keys[keys.length - 1].frame;
  51785. }
  51786. //to and from cannot be the same key
  51787. if (from === to) {
  51788. if (from > keys[0].frame) {
  51789. from--;
  51790. }
  51791. else if (to < keys[keys.length - 1].frame) {
  51792. to++;
  51793. }
  51794. }
  51795. // Compute ratio
  51796. var range = to - from;
  51797. var offsetValue;
  51798. // ratio represents the frame delta between from and to
  51799. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51800. var highLimitValue = 0;
  51801. this._previousDelay = delay;
  51802. this._previousRatio = ratio;
  51803. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51804. returnValue = false;
  51805. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51806. }
  51807. else {
  51808. // Get max value if required
  51809. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51810. var keyOffset = to.toString() + from.toString();
  51811. if (!this._offsetsCache[keyOffset]) {
  51812. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51813. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51814. switch (this._animation.dataType) {
  51815. // Float
  51816. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51817. this._offsetsCache[keyOffset] = toValue - fromValue;
  51818. break;
  51819. // Quaternion
  51820. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51821. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51822. break;
  51823. // Vector3
  51824. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51825. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51826. // Vector2
  51827. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51828. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51829. // Size
  51830. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51831. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51832. // Color3
  51833. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51834. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51835. default:
  51836. break;
  51837. }
  51838. this._highLimitsCache[keyOffset] = toValue;
  51839. }
  51840. highLimitValue = this._highLimitsCache[keyOffset];
  51841. offsetValue = this._offsetsCache[keyOffset];
  51842. }
  51843. }
  51844. if (offsetValue === undefined) {
  51845. switch (this._animation.dataType) {
  51846. // Float
  51847. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51848. offsetValue = 0;
  51849. break;
  51850. // Quaternion
  51851. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51852. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51853. break;
  51854. // Vector3
  51855. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51856. offsetValue = BABYLON.Vector3.Zero();
  51857. break;
  51858. // Vector2
  51859. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51860. offsetValue = BABYLON.Vector2.Zero();
  51861. break;
  51862. // Size
  51863. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51864. offsetValue = BABYLON.Size.Zero();
  51865. break;
  51866. // Color3
  51867. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51868. offsetValue = BABYLON.Color3.Black();
  51869. }
  51870. }
  51871. // Compute value
  51872. var repeatCount = (ratio / range) >> 0;
  51873. var currentFrame = returnValue ? from + ratio % range : to;
  51874. // Need to normalize?
  51875. if (this._host && this._host.syncRoot) {
  51876. var syncRoot = this._host.syncRoot;
  51877. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51878. currentFrame = from + (to - from) * hostNormalizedFrame;
  51879. }
  51880. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51881. // Set value
  51882. this.setValue(currentValue, weight);
  51883. // Check events
  51884. var events = this._animation.getEvents();
  51885. for (var index = 0; index < events.length; index++) {
  51886. // Make sure current frame has passed event frame and that event frame is within the current range
  51887. // Also, handle both forward and reverse animations
  51888. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51889. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51890. var event = events[index];
  51891. if (!event.isDone) {
  51892. // If event should be done only once, remove it.
  51893. if (event.onlyOnce) {
  51894. events.splice(index, 1);
  51895. index--;
  51896. }
  51897. event.isDone = true;
  51898. event.action();
  51899. } // Don't do anything if the event has already be done.
  51900. }
  51901. else if (events[index].isDone && !events[index].onlyOnce) {
  51902. // reset event, the animation is looping
  51903. events[index].isDone = false;
  51904. }
  51905. }
  51906. if (!returnValue) {
  51907. this._stopped = true;
  51908. }
  51909. return returnValue;
  51910. };
  51911. return RuntimeAnimation;
  51912. }());
  51913. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51914. })(BABYLON || (BABYLON = {}));
  51915. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51916. var BABYLON;
  51917. (function (BABYLON) {
  51918. var Animatable = /** @class */ (function () {
  51919. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51920. if (fromFrame === void 0) { fromFrame = 0; }
  51921. if (toFrame === void 0) { toFrame = 100; }
  51922. if (loopAnimation === void 0) { loopAnimation = false; }
  51923. if (speedRatio === void 0) { speedRatio = 1.0; }
  51924. this.target = target;
  51925. this.fromFrame = fromFrame;
  51926. this.toFrame = toFrame;
  51927. this.loopAnimation = loopAnimation;
  51928. this.onAnimationEnd = onAnimationEnd;
  51929. this._localDelayOffset = null;
  51930. this._pausedDelay = null;
  51931. this._runtimeAnimations = new Array();
  51932. this._paused = false;
  51933. this._speedRatio = 1;
  51934. this._weight = -1.0;
  51935. this.animationStarted = false;
  51936. this._scene = scene;
  51937. if (animations) {
  51938. this.appendAnimations(target, animations);
  51939. }
  51940. this._speedRatio = speedRatio;
  51941. scene._activeAnimatables.push(this);
  51942. }
  51943. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51944. /**
  51945. * Gets the root Animatable used to synchronize and normalize animations
  51946. */
  51947. get: function () {
  51948. return this._syncRoot;
  51949. },
  51950. enumerable: true,
  51951. configurable: true
  51952. });
  51953. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51954. /**
  51955. * Gets the current frame of the first RuntimeAnimation
  51956. * Used to synchronize Animatables
  51957. */
  51958. get: function () {
  51959. if (this._runtimeAnimations.length === 0) {
  51960. return 0;
  51961. }
  51962. return this._runtimeAnimations[0].currentFrame;
  51963. },
  51964. enumerable: true,
  51965. configurable: true
  51966. });
  51967. Object.defineProperty(Animatable.prototype, "weight", {
  51968. /**
  51969. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51970. */
  51971. get: function () {
  51972. return this._weight;
  51973. },
  51974. set: function (value) {
  51975. if (value === -1) { // -1 is ok and means no weight
  51976. this._weight = -1;
  51977. return;
  51978. }
  51979. // Else weight must be in [0, 1] range
  51980. this._weight = Math.min(Math.max(value, 0), 1.0);
  51981. },
  51982. enumerable: true,
  51983. configurable: true
  51984. });
  51985. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51986. /**
  51987. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51988. */
  51989. get: function () {
  51990. return this._speedRatio;
  51991. },
  51992. set: function (value) {
  51993. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51994. var animation = this._runtimeAnimations[index];
  51995. animation._prepareForSpeedRatioChange(value);
  51996. }
  51997. this._speedRatio = value;
  51998. },
  51999. enumerable: true,
  52000. configurable: true
  52001. });
  52002. // Methods
  52003. /**
  52004. * Synchronize and normalize current Animatable with a source Animatable
  52005. * This is useful when using animation weights and when animations are not of the same length
  52006. * @param root defines the root Animatable to synchronize with
  52007. * @returns the current Animatable
  52008. */
  52009. Animatable.prototype.syncWith = function (root) {
  52010. this._syncRoot = root;
  52011. if (root) {
  52012. // Make sure this animatable will animate after the root
  52013. var index = this._scene._activeAnimatables.indexOf(this);
  52014. if (index > -1) {
  52015. this._scene._activeAnimatables.splice(index, 1);
  52016. this._scene._activeAnimatables.push(this);
  52017. }
  52018. }
  52019. return this;
  52020. };
  52021. Animatable.prototype.getAnimations = function () {
  52022. return this._runtimeAnimations;
  52023. };
  52024. Animatable.prototype.appendAnimations = function (target, animations) {
  52025. for (var index = 0; index < animations.length; index++) {
  52026. var animation = animations[index];
  52027. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52028. }
  52029. };
  52030. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52031. var runtimeAnimations = this._runtimeAnimations;
  52032. for (var index = 0; index < runtimeAnimations.length; index++) {
  52033. if (runtimeAnimations[index].animation.targetProperty === property) {
  52034. return runtimeAnimations[index].animation;
  52035. }
  52036. }
  52037. return null;
  52038. };
  52039. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52040. var runtimeAnimations = this._runtimeAnimations;
  52041. for (var index = 0; index < runtimeAnimations.length; index++) {
  52042. if (runtimeAnimations[index].animation.targetProperty === property) {
  52043. return runtimeAnimations[index];
  52044. }
  52045. }
  52046. return null;
  52047. };
  52048. Animatable.prototype.reset = function () {
  52049. var runtimeAnimations = this._runtimeAnimations;
  52050. for (var index = 0; index < runtimeAnimations.length; index++) {
  52051. runtimeAnimations[index].reset();
  52052. }
  52053. // Reset to original value
  52054. for (index = 0; index < runtimeAnimations.length; index++) {
  52055. var animation = runtimeAnimations[index];
  52056. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  52057. }
  52058. this._localDelayOffset = null;
  52059. this._pausedDelay = null;
  52060. };
  52061. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52062. var runtimeAnimations = this._runtimeAnimations;
  52063. for (var index = 0; index < runtimeAnimations.length; index++) {
  52064. runtimeAnimations[index].animation.enableBlending = true;
  52065. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52066. }
  52067. };
  52068. Animatable.prototype.disableBlending = function () {
  52069. var runtimeAnimations = this._runtimeAnimations;
  52070. for (var index = 0; index < runtimeAnimations.length; index++) {
  52071. runtimeAnimations[index].animation.enableBlending = false;
  52072. }
  52073. };
  52074. Animatable.prototype.goToFrame = function (frame) {
  52075. var runtimeAnimations = this._runtimeAnimations;
  52076. if (runtimeAnimations[0]) {
  52077. var fps = runtimeAnimations[0].animation.framePerSecond;
  52078. var currentFrame = runtimeAnimations[0].currentFrame;
  52079. var adjustTime = frame - currentFrame;
  52080. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52081. if (this._localDelayOffset === null) {
  52082. this._localDelayOffset = 0;
  52083. }
  52084. this._localDelayOffset -= delay;
  52085. }
  52086. for (var index = 0; index < runtimeAnimations.length; index++) {
  52087. runtimeAnimations[index].goToFrame(frame);
  52088. }
  52089. };
  52090. Animatable.prototype.pause = function () {
  52091. if (this._paused) {
  52092. return;
  52093. }
  52094. this._paused = true;
  52095. };
  52096. Animatable.prototype.restart = function () {
  52097. this._paused = false;
  52098. };
  52099. Animatable.prototype.stop = function (animationName) {
  52100. if (animationName) {
  52101. var idx = this._scene._activeAnimatables.indexOf(this);
  52102. if (idx > -1) {
  52103. var runtimeAnimations = this._runtimeAnimations;
  52104. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52105. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52106. continue;
  52107. }
  52108. runtimeAnimations[index].dispose();
  52109. runtimeAnimations.splice(index, 1);
  52110. }
  52111. if (runtimeAnimations.length == 0) {
  52112. this._scene._activeAnimatables.splice(idx, 1);
  52113. if (this.onAnimationEnd) {
  52114. this.onAnimationEnd();
  52115. }
  52116. }
  52117. }
  52118. }
  52119. else {
  52120. var index = this._scene._activeAnimatables.indexOf(this);
  52121. if (index > -1) {
  52122. this._scene._activeAnimatables.splice(index, 1);
  52123. var runtimeAnimations = this._runtimeAnimations;
  52124. for (var index = 0; index < runtimeAnimations.length; index++) {
  52125. runtimeAnimations[index].dispose();
  52126. }
  52127. if (this.onAnimationEnd) {
  52128. this.onAnimationEnd();
  52129. }
  52130. }
  52131. }
  52132. };
  52133. Animatable.prototype._animate = function (delay) {
  52134. if (this._paused) {
  52135. this.animationStarted = false;
  52136. if (this._pausedDelay === null) {
  52137. this._pausedDelay = delay;
  52138. }
  52139. return true;
  52140. }
  52141. if (this._localDelayOffset === null) {
  52142. this._localDelayOffset = delay;
  52143. this._pausedDelay = null;
  52144. }
  52145. else if (this._pausedDelay !== null) {
  52146. this._localDelayOffset += delay - this._pausedDelay;
  52147. this._pausedDelay = null;
  52148. }
  52149. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52150. return true;
  52151. }
  52152. // Animating
  52153. var running = false;
  52154. var runtimeAnimations = this._runtimeAnimations;
  52155. var index;
  52156. for (index = 0; index < runtimeAnimations.length; index++) {
  52157. var animation = runtimeAnimations[index];
  52158. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52159. running = running || isRunning;
  52160. }
  52161. this.animationStarted = running;
  52162. if (!running) {
  52163. // Remove from active animatables
  52164. index = this._scene._activeAnimatables.indexOf(this);
  52165. this._scene._activeAnimatables.splice(index, 1);
  52166. // Dispose all runtime animations
  52167. for (index = 0; index < runtimeAnimations.length; index++) {
  52168. runtimeAnimations[index].dispose();
  52169. }
  52170. }
  52171. if (!running && this.onAnimationEnd) {
  52172. this.onAnimationEnd();
  52173. this.onAnimationEnd = null;
  52174. }
  52175. return running;
  52176. };
  52177. return Animatable;
  52178. }());
  52179. BABYLON.Animatable = Animatable;
  52180. })(BABYLON || (BABYLON = {}));
  52181. //# sourceMappingURL=babylon.animatable.js.map
  52182. var BABYLON;
  52183. (function (BABYLON) {
  52184. var EasingFunction = /** @class */ (function () {
  52185. function EasingFunction() {
  52186. // Properties
  52187. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52188. }
  52189. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52190. get: function () {
  52191. return EasingFunction._EASINGMODE_EASEIN;
  52192. },
  52193. enumerable: true,
  52194. configurable: true
  52195. });
  52196. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52197. get: function () {
  52198. return EasingFunction._EASINGMODE_EASEOUT;
  52199. },
  52200. enumerable: true,
  52201. configurable: true
  52202. });
  52203. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52204. get: function () {
  52205. return EasingFunction._EASINGMODE_EASEINOUT;
  52206. },
  52207. enumerable: true,
  52208. configurable: true
  52209. });
  52210. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52211. var n = Math.min(Math.max(easingMode, 0), 2);
  52212. this._easingMode = n;
  52213. };
  52214. EasingFunction.prototype.getEasingMode = function () {
  52215. return this._easingMode;
  52216. };
  52217. EasingFunction.prototype.easeInCore = function (gradient) {
  52218. throw new Error('You must implement this method');
  52219. };
  52220. EasingFunction.prototype.ease = function (gradient) {
  52221. switch (this._easingMode) {
  52222. case EasingFunction.EASINGMODE_EASEIN:
  52223. return this.easeInCore(gradient);
  52224. case EasingFunction.EASINGMODE_EASEOUT:
  52225. return (1 - this.easeInCore(1 - gradient));
  52226. }
  52227. if (gradient >= 0.5) {
  52228. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52229. }
  52230. return (this.easeInCore(gradient * 2) * 0.5);
  52231. };
  52232. //Statics
  52233. EasingFunction._EASINGMODE_EASEIN = 0;
  52234. EasingFunction._EASINGMODE_EASEOUT = 1;
  52235. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52236. return EasingFunction;
  52237. }());
  52238. BABYLON.EasingFunction = EasingFunction;
  52239. var CircleEase = /** @class */ (function (_super) {
  52240. __extends(CircleEase, _super);
  52241. function CircleEase() {
  52242. return _super !== null && _super.apply(this, arguments) || this;
  52243. }
  52244. CircleEase.prototype.easeInCore = function (gradient) {
  52245. gradient = Math.max(0, Math.min(1, gradient));
  52246. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52247. };
  52248. return CircleEase;
  52249. }(EasingFunction));
  52250. BABYLON.CircleEase = CircleEase;
  52251. var BackEase = /** @class */ (function (_super) {
  52252. __extends(BackEase, _super);
  52253. function BackEase(amplitude) {
  52254. if (amplitude === void 0) { amplitude = 1; }
  52255. var _this = _super.call(this) || this;
  52256. _this.amplitude = amplitude;
  52257. return _this;
  52258. }
  52259. BackEase.prototype.easeInCore = function (gradient) {
  52260. var num = Math.max(0, this.amplitude);
  52261. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52262. };
  52263. return BackEase;
  52264. }(EasingFunction));
  52265. BABYLON.BackEase = BackEase;
  52266. var BounceEase = /** @class */ (function (_super) {
  52267. __extends(BounceEase, _super);
  52268. function BounceEase(bounces, bounciness) {
  52269. if (bounces === void 0) { bounces = 3; }
  52270. if (bounciness === void 0) { bounciness = 2; }
  52271. var _this = _super.call(this) || this;
  52272. _this.bounces = bounces;
  52273. _this.bounciness = bounciness;
  52274. return _this;
  52275. }
  52276. BounceEase.prototype.easeInCore = function (gradient) {
  52277. var y = Math.max(0.0, this.bounces);
  52278. var bounciness = this.bounciness;
  52279. if (bounciness <= 1.0) {
  52280. bounciness = 1.001;
  52281. }
  52282. var num9 = Math.pow(bounciness, y);
  52283. var num5 = 1.0 - bounciness;
  52284. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52285. var num15 = gradient * num4;
  52286. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52287. var num3 = Math.floor(num65);
  52288. var num13 = num3 + 1.0;
  52289. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52290. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52291. var num7 = (num8 + num12) * 0.5;
  52292. var num6 = gradient - num7;
  52293. var num2 = num7 - num8;
  52294. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52295. };
  52296. return BounceEase;
  52297. }(EasingFunction));
  52298. BABYLON.BounceEase = BounceEase;
  52299. var CubicEase = /** @class */ (function (_super) {
  52300. __extends(CubicEase, _super);
  52301. function CubicEase() {
  52302. return _super !== null && _super.apply(this, arguments) || this;
  52303. }
  52304. CubicEase.prototype.easeInCore = function (gradient) {
  52305. return (gradient * gradient * gradient);
  52306. };
  52307. return CubicEase;
  52308. }(EasingFunction));
  52309. BABYLON.CubicEase = CubicEase;
  52310. var ElasticEase = /** @class */ (function (_super) {
  52311. __extends(ElasticEase, _super);
  52312. function ElasticEase(oscillations, springiness) {
  52313. if (oscillations === void 0) { oscillations = 3; }
  52314. if (springiness === void 0) { springiness = 3; }
  52315. var _this = _super.call(this) || this;
  52316. _this.oscillations = oscillations;
  52317. _this.springiness = springiness;
  52318. return _this;
  52319. }
  52320. ElasticEase.prototype.easeInCore = function (gradient) {
  52321. var num2;
  52322. var num3 = Math.max(0.0, this.oscillations);
  52323. var num = Math.max(0.0, this.springiness);
  52324. if (num == 0) {
  52325. num2 = gradient;
  52326. }
  52327. else {
  52328. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52329. }
  52330. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52331. };
  52332. return ElasticEase;
  52333. }(EasingFunction));
  52334. BABYLON.ElasticEase = ElasticEase;
  52335. var ExponentialEase = /** @class */ (function (_super) {
  52336. __extends(ExponentialEase, _super);
  52337. function ExponentialEase(exponent) {
  52338. if (exponent === void 0) { exponent = 2; }
  52339. var _this = _super.call(this) || this;
  52340. _this.exponent = exponent;
  52341. return _this;
  52342. }
  52343. ExponentialEase.prototype.easeInCore = function (gradient) {
  52344. if (this.exponent <= 0) {
  52345. return gradient;
  52346. }
  52347. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52348. };
  52349. return ExponentialEase;
  52350. }(EasingFunction));
  52351. BABYLON.ExponentialEase = ExponentialEase;
  52352. var PowerEase = /** @class */ (function (_super) {
  52353. __extends(PowerEase, _super);
  52354. function PowerEase(power) {
  52355. if (power === void 0) { power = 2; }
  52356. var _this = _super.call(this) || this;
  52357. _this.power = power;
  52358. return _this;
  52359. }
  52360. PowerEase.prototype.easeInCore = function (gradient) {
  52361. var y = Math.max(0.0, this.power);
  52362. return Math.pow(gradient, y);
  52363. };
  52364. return PowerEase;
  52365. }(EasingFunction));
  52366. BABYLON.PowerEase = PowerEase;
  52367. var QuadraticEase = /** @class */ (function (_super) {
  52368. __extends(QuadraticEase, _super);
  52369. function QuadraticEase() {
  52370. return _super !== null && _super.apply(this, arguments) || this;
  52371. }
  52372. QuadraticEase.prototype.easeInCore = function (gradient) {
  52373. return (gradient * gradient);
  52374. };
  52375. return QuadraticEase;
  52376. }(EasingFunction));
  52377. BABYLON.QuadraticEase = QuadraticEase;
  52378. var QuarticEase = /** @class */ (function (_super) {
  52379. __extends(QuarticEase, _super);
  52380. function QuarticEase() {
  52381. return _super !== null && _super.apply(this, arguments) || this;
  52382. }
  52383. QuarticEase.prototype.easeInCore = function (gradient) {
  52384. return (gradient * gradient * gradient * gradient);
  52385. };
  52386. return QuarticEase;
  52387. }(EasingFunction));
  52388. BABYLON.QuarticEase = QuarticEase;
  52389. var QuinticEase = /** @class */ (function (_super) {
  52390. __extends(QuinticEase, _super);
  52391. function QuinticEase() {
  52392. return _super !== null && _super.apply(this, arguments) || this;
  52393. }
  52394. QuinticEase.prototype.easeInCore = function (gradient) {
  52395. return (gradient * gradient * gradient * gradient * gradient);
  52396. };
  52397. return QuinticEase;
  52398. }(EasingFunction));
  52399. BABYLON.QuinticEase = QuinticEase;
  52400. var SineEase = /** @class */ (function (_super) {
  52401. __extends(SineEase, _super);
  52402. function SineEase() {
  52403. return _super !== null && _super.apply(this, arguments) || this;
  52404. }
  52405. SineEase.prototype.easeInCore = function (gradient) {
  52406. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52407. };
  52408. return SineEase;
  52409. }(EasingFunction));
  52410. BABYLON.SineEase = SineEase;
  52411. var BezierCurveEase = /** @class */ (function (_super) {
  52412. __extends(BezierCurveEase, _super);
  52413. function BezierCurveEase(x1, y1, x2, y2) {
  52414. if (x1 === void 0) { x1 = 0; }
  52415. if (y1 === void 0) { y1 = 0; }
  52416. if (x2 === void 0) { x2 = 1; }
  52417. if (y2 === void 0) { y2 = 1; }
  52418. var _this = _super.call(this) || this;
  52419. _this.x1 = x1;
  52420. _this.y1 = y1;
  52421. _this.x2 = x2;
  52422. _this.y2 = y2;
  52423. return _this;
  52424. }
  52425. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52426. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52427. };
  52428. return BezierCurveEase;
  52429. }(EasingFunction));
  52430. BABYLON.BezierCurveEase = BezierCurveEase;
  52431. })(BABYLON || (BABYLON = {}));
  52432. //# sourceMappingURL=babylon.easing.js.map
  52433. var BABYLON;
  52434. (function (BABYLON) {
  52435. /**
  52436. * A Condition applied to an Action
  52437. */
  52438. var Condition = /** @class */ (function () {
  52439. /**
  52440. * Creates a new Condition
  52441. * @param actionManager the manager of the action the condition is applied to
  52442. */
  52443. function Condition(actionManager) {
  52444. this._actionManager = actionManager;
  52445. }
  52446. /**
  52447. * Check if the current condition is valid
  52448. * @returns a boolean
  52449. */
  52450. Condition.prototype.isValid = function () {
  52451. return true;
  52452. };
  52453. /**
  52454. * Internal only
  52455. * @hidden
  52456. */
  52457. Condition.prototype._getProperty = function (propertyPath) {
  52458. return this._actionManager._getProperty(propertyPath);
  52459. };
  52460. /**
  52461. * Internal only
  52462. * @hidden
  52463. */
  52464. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52465. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52466. };
  52467. /**
  52468. * Serialize placeholder for child classes
  52469. * @returns the serialized object
  52470. */
  52471. Condition.prototype.serialize = function () {
  52472. };
  52473. /**
  52474. * Internal only
  52475. * @hidden
  52476. */
  52477. Condition.prototype._serialize = function (serializedCondition) {
  52478. return {
  52479. type: 2,
  52480. children: [],
  52481. name: serializedCondition.name,
  52482. properties: serializedCondition.properties
  52483. };
  52484. };
  52485. return Condition;
  52486. }());
  52487. BABYLON.Condition = Condition;
  52488. /**
  52489. * Defines specific conditional operators as extensions of Condition
  52490. */
  52491. var ValueCondition = /** @class */ (function (_super) {
  52492. __extends(ValueCondition, _super);
  52493. /**
  52494. * Creates a new ValueCondition
  52495. * @param actionManager manager for the action the condition applies to
  52496. * @param target for the action
  52497. * @param propertyPath path to specify the property of the target the conditional operator uses
  52498. * @param value the value compared by the conditional operator against the current value of the property
  52499. * @param operator the conditional operator, default ValueCondition.IsEqual
  52500. */
  52501. function ValueCondition(actionManager, target,
  52502. /** path to specify the property of the target the conditional operator uses */
  52503. propertyPath,
  52504. /** the value compared by the conditional operator against the current value of the property */
  52505. value,
  52506. /** the conditional operator, default ValueCondition.IsEqual */
  52507. operator) {
  52508. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52509. var _this = _super.call(this, actionManager) || this;
  52510. _this.propertyPath = propertyPath;
  52511. _this.value = value;
  52512. _this.operator = operator;
  52513. _this._target = target;
  52514. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52515. _this._property = _this._getProperty(_this.propertyPath);
  52516. return _this;
  52517. }
  52518. Object.defineProperty(ValueCondition, "IsEqual", {
  52519. /**
  52520. * returns the number for IsEqual
  52521. */
  52522. get: function () {
  52523. return ValueCondition._IsEqual;
  52524. },
  52525. enumerable: true,
  52526. configurable: true
  52527. });
  52528. Object.defineProperty(ValueCondition, "IsDifferent", {
  52529. /**
  52530. * Returns the number for IsDifferent
  52531. */
  52532. get: function () {
  52533. return ValueCondition._IsDifferent;
  52534. },
  52535. enumerable: true,
  52536. configurable: true
  52537. });
  52538. Object.defineProperty(ValueCondition, "IsGreater", {
  52539. /**
  52540. * Returns the number for IsGreater
  52541. */
  52542. get: function () {
  52543. return ValueCondition._IsGreater;
  52544. },
  52545. enumerable: true,
  52546. configurable: true
  52547. });
  52548. Object.defineProperty(ValueCondition, "IsLesser", {
  52549. /**
  52550. * Returns the number for IsLesser
  52551. */
  52552. get: function () {
  52553. return ValueCondition._IsLesser;
  52554. },
  52555. enumerable: true,
  52556. configurable: true
  52557. });
  52558. /**
  52559. * Compares the given value with the property value for the specified conditional operator
  52560. * @returns the result of the comparison
  52561. */
  52562. ValueCondition.prototype.isValid = function () {
  52563. switch (this.operator) {
  52564. case ValueCondition.IsGreater:
  52565. return this._effectiveTarget[this._property] > this.value;
  52566. case ValueCondition.IsLesser:
  52567. return this._effectiveTarget[this._property] < this.value;
  52568. case ValueCondition.IsEqual:
  52569. case ValueCondition.IsDifferent:
  52570. var check;
  52571. if (this.value.equals) {
  52572. check = this.value.equals(this._effectiveTarget[this._property]);
  52573. }
  52574. else {
  52575. check = this.value === this._effectiveTarget[this._property];
  52576. }
  52577. return this.operator === ValueCondition.IsEqual ? check : !check;
  52578. }
  52579. return false;
  52580. };
  52581. /**
  52582. * Serialize the ValueCondition into a JSON compatible object
  52583. * @returns serialization object
  52584. */
  52585. ValueCondition.prototype.serialize = function () {
  52586. return this._serialize({
  52587. name: "ValueCondition",
  52588. properties: [
  52589. BABYLON.Action._GetTargetProperty(this._target),
  52590. { name: "propertyPath", value: this.propertyPath },
  52591. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52592. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52593. ]
  52594. });
  52595. };
  52596. /**
  52597. * Gets the name of the conditional operator for the ValueCondition
  52598. * @param operator the conditional operator
  52599. * @returns the name
  52600. */
  52601. ValueCondition.GetOperatorName = function (operator) {
  52602. switch (operator) {
  52603. case ValueCondition._IsEqual: return "IsEqual";
  52604. case ValueCondition._IsDifferent: return "IsDifferent";
  52605. case ValueCondition._IsGreater: return "IsGreater";
  52606. case ValueCondition._IsLesser: return "IsLesser";
  52607. default: return "";
  52608. }
  52609. };
  52610. /**
  52611. * Internal only
  52612. * @hidden
  52613. */
  52614. ValueCondition._IsEqual = 0;
  52615. /**
  52616. * Internal only
  52617. * @hidden
  52618. */
  52619. ValueCondition._IsDifferent = 1;
  52620. /**
  52621. * Internal only
  52622. * @hidden
  52623. */
  52624. ValueCondition._IsGreater = 2;
  52625. /**
  52626. * Internal only
  52627. * @hidden
  52628. */
  52629. ValueCondition._IsLesser = 3;
  52630. return ValueCondition;
  52631. }(Condition));
  52632. BABYLON.ValueCondition = ValueCondition;
  52633. /**
  52634. * Defines a predicate condition as an extension of Condition
  52635. */
  52636. var PredicateCondition = /** @class */ (function (_super) {
  52637. __extends(PredicateCondition, _super);
  52638. /**
  52639. * Creates a new PredicateCondition
  52640. * @param actionManager manager for the action the condition applies to
  52641. * @param predicate defines the predicate function used to validate the condition
  52642. */
  52643. function PredicateCondition(actionManager,
  52644. /** defines the predicate function used to validate the condition */
  52645. predicate) {
  52646. var _this = _super.call(this, actionManager) || this;
  52647. _this.predicate = predicate;
  52648. return _this;
  52649. }
  52650. /**
  52651. * @returns the validity of the predicate condition
  52652. */
  52653. PredicateCondition.prototype.isValid = function () {
  52654. return this.predicate();
  52655. };
  52656. return PredicateCondition;
  52657. }(Condition));
  52658. BABYLON.PredicateCondition = PredicateCondition;
  52659. /**
  52660. * Defines a state condition as an extension of Condition
  52661. */
  52662. var StateCondition = /** @class */ (function (_super) {
  52663. __extends(StateCondition, _super);
  52664. /**
  52665. * Creates a new StateCondition
  52666. * @param actionManager manager for the action the condition applies to
  52667. * @param target of the condition
  52668. * @param value to compare with target state
  52669. */
  52670. function StateCondition(actionManager, target, value) {
  52671. var _this = _super.call(this, actionManager) || this;
  52672. _this.value = value;
  52673. _this._target = target;
  52674. return _this;
  52675. }
  52676. /**
  52677. * @returns the validity of the state
  52678. */
  52679. StateCondition.prototype.isValid = function () {
  52680. return this._target.state === this.value;
  52681. };
  52682. /**
  52683. * Serialize the StateCondition into a JSON compatible object
  52684. * @returns serialization object
  52685. */
  52686. StateCondition.prototype.serialize = function () {
  52687. return this._serialize({
  52688. name: "StateCondition",
  52689. properties: [
  52690. BABYLON.Action._GetTargetProperty(this._target),
  52691. { name: "value", value: this.value }
  52692. ]
  52693. });
  52694. };
  52695. return StateCondition;
  52696. }(Condition));
  52697. BABYLON.StateCondition = StateCondition;
  52698. })(BABYLON || (BABYLON = {}));
  52699. //# sourceMappingURL=babylon.condition.js.map
  52700. var BABYLON;
  52701. (function (BABYLON) {
  52702. /**
  52703. * The action to be carried out following a trigger
  52704. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52705. */
  52706. var Action = /** @class */ (function () {
  52707. /**
  52708. * Creates a new Action
  52709. * @param triggerOptions the trigger, with or without parameters, for the action
  52710. * @param condition an optional determinant of action
  52711. */
  52712. function Action(
  52713. /** the trigger, with or without parameters, for the action */
  52714. triggerOptions, condition) {
  52715. this.triggerOptions = triggerOptions;
  52716. /**
  52717. * An event triggered prior to action being executed.
  52718. */
  52719. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52720. if (triggerOptions.parameter) {
  52721. this.trigger = triggerOptions.trigger;
  52722. this._triggerParameter = triggerOptions.parameter;
  52723. }
  52724. else {
  52725. this.trigger = triggerOptions;
  52726. }
  52727. this._nextActiveAction = this;
  52728. this._condition = condition;
  52729. }
  52730. /**
  52731. * Internal only
  52732. * @hidden
  52733. */
  52734. Action.prototype._prepare = function () {
  52735. };
  52736. /**
  52737. * Gets the trigger parameters
  52738. * @returns the trigger parameters
  52739. */
  52740. Action.prototype.getTriggerParameter = function () {
  52741. return this._triggerParameter;
  52742. };
  52743. /**
  52744. * Internal only - executes current action event
  52745. * @hidden
  52746. */
  52747. Action.prototype._executeCurrent = function (evt) {
  52748. if (this._nextActiveAction._condition) {
  52749. var condition = this._nextActiveAction._condition;
  52750. var currentRenderId = this._actionManager.getScene().getRenderId();
  52751. // We cache the current evaluation for the current frame
  52752. if (condition._evaluationId === currentRenderId) {
  52753. if (!condition._currentResult) {
  52754. return;
  52755. }
  52756. }
  52757. else {
  52758. condition._evaluationId = currentRenderId;
  52759. if (!condition.isValid()) {
  52760. condition._currentResult = false;
  52761. return;
  52762. }
  52763. condition._currentResult = true;
  52764. }
  52765. }
  52766. this.onBeforeExecuteObservable.notifyObservers(this);
  52767. this._nextActiveAction.execute(evt);
  52768. this.skipToNextActiveAction();
  52769. };
  52770. /**
  52771. * Execute placeholder for child classes
  52772. * @param evt optional action event
  52773. */
  52774. Action.prototype.execute = function (evt) {
  52775. };
  52776. /**
  52777. * Skips to next active action
  52778. */
  52779. Action.prototype.skipToNextActiveAction = function () {
  52780. if (this._nextActiveAction._child) {
  52781. if (!this._nextActiveAction._child._actionManager) {
  52782. this._nextActiveAction._child._actionManager = this._actionManager;
  52783. }
  52784. this._nextActiveAction = this._nextActiveAction._child;
  52785. }
  52786. else {
  52787. this._nextActiveAction = this;
  52788. }
  52789. };
  52790. /**
  52791. * Adds action to chain of actions, may be a DoNothingAction
  52792. * @param action defines the next action to execute
  52793. * @returns The action passed in
  52794. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52795. */
  52796. Action.prototype.then = function (action) {
  52797. this._child = action;
  52798. action._actionManager = this._actionManager;
  52799. action._prepare();
  52800. return action;
  52801. };
  52802. /**
  52803. * Internal only
  52804. * @hidden
  52805. */
  52806. Action.prototype._getProperty = function (propertyPath) {
  52807. return this._actionManager._getProperty(propertyPath);
  52808. };
  52809. /**
  52810. * Internal only
  52811. * @hidden
  52812. */
  52813. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52814. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52815. };
  52816. /**
  52817. * Serialize placeholder for child classes
  52818. * @param parent of child
  52819. * @returns the serialized object
  52820. */
  52821. Action.prototype.serialize = function (parent) {
  52822. };
  52823. /**
  52824. * Internal only called by serialize
  52825. * @hidden
  52826. */
  52827. Action.prototype._serialize = function (serializedAction, parent) {
  52828. var serializationObject = {
  52829. type: 1,
  52830. children: [],
  52831. name: serializedAction.name,
  52832. properties: serializedAction.properties || []
  52833. };
  52834. // Serialize child
  52835. if (this._child) {
  52836. this._child.serialize(serializationObject);
  52837. }
  52838. // Check if "this" has a condition
  52839. if (this._condition) {
  52840. var serializedCondition = this._condition.serialize();
  52841. serializedCondition.children.push(serializationObject);
  52842. if (parent) {
  52843. parent.children.push(serializedCondition);
  52844. }
  52845. return serializedCondition;
  52846. }
  52847. if (parent) {
  52848. parent.children.push(serializationObject);
  52849. }
  52850. return serializationObject;
  52851. };
  52852. /**
  52853. * Internal only
  52854. * @hidden
  52855. */
  52856. Action._SerializeValueAsString = function (value) {
  52857. if (typeof value === "number") {
  52858. return value.toString();
  52859. }
  52860. if (typeof value === "boolean") {
  52861. return value ? "true" : "false";
  52862. }
  52863. if (value instanceof BABYLON.Vector2) {
  52864. return value.x + ", " + value.y;
  52865. }
  52866. if (value instanceof BABYLON.Vector3) {
  52867. return value.x + ", " + value.y + ", " + value.z;
  52868. }
  52869. if (value instanceof BABYLON.Color3) {
  52870. return value.r + ", " + value.g + ", " + value.b;
  52871. }
  52872. if (value instanceof BABYLON.Color4) {
  52873. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52874. }
  52875. return value; // string
  52876. };
  52877. /**
  52878. * Internal only
  52879. * @hidden
  52880. */
  52881. Action._GetTargetProperty = function (target) {
  52882. return {
  52883. name: "target",
  52884. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52885. : target instanceof BABYLON.Light ? "LightProperties"
  52886. : target instanceof BABYLON.Camera ? "CameraProperties"
  52887. : "SceneProperties",
  52888. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52889. };
  52890. };
  52891. return Action;
  52892. }());
  52893. BABYLON.Action = Action;
  52894. })(BABYLON || (BABYLON = {}));
  52895. //# sourceMappingURL=babylon.action.js.map
  52896. var BABYLON;
  52897. (function (BABYLON) {
  52898. /**
  52899. * ActionEvent is the event being sent when an action is triggered.
  52900. */
  52901. var ActionEvent = /** @class */ (function () {
  52902. /**
  52903. * Creates a new ActionEvent
  52904. * @param source The mesh or sprite that triggered the action
  52905. * @param pointerX The X mouse cursor position at the time of the event
  52906. * @param pointerY The Y mouse cursor position at the time of the event
  52907. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52908. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52909. * @param additionalData additional data for the event
  52910. */
  52911. function ActionEvent(
  52912. /** The mesh or sprite that triggered the action */
  52913. source,
  52914. /** The X mouse cursor position at the time of the event */
  52915. pointerX,
  52916. /** The Y mouse cursor position at the time of the event */
  52917. pointerY,
  52918. /** The mesh that is currently pointed at (can be null) */
  52919. meshUnderPointer,
  52920. /** the original (browser) event that triggered the ActionEvent */
  52921. sourceEvent,
  52922. /** additional data for the event */
  52923. additionalData) {
  52924. this.source = source;
  52925. this.pointerX = pointerX;
  52926. this.pointerY = pointerY;
  52927. this.meshUnderPointer = meshUnderPointer;
  52928. this.sourceEvent = sourceEvent;
  52929. this.additionalData = additionalData;
  52930. }
  52931. /**
  52932. * Helper function to auto-create an ActionEvent from a source mesh.
  52933. * @param source The source mesh that triggered the event
  52934. * @param evt The original (browser) event
  52935. * @param additionalData additional data for the event
  52936. * @returns the new ActionEvent
  52937. */
  52938. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52939. var scene = source.getScene();
  52940. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52941. };
  52942. /**
  52943. * Helper function to auto-create an ActionEvent from a source sprite
  52944. * @param source The source sprite that triggered the event
  52945. * @param scene Scene associated with the sprite
  52946. * @param evt The original (browser) event
  52947. * @param additionalData additional data for the event
  52948. * @returns the new ActionEvent
  52949. */
  52950. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52951. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52952. };
  52953. /**
  52954. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52955. * @param scene the scene where the event occurred
  52956. * @param evt The original (browser) event
  52957. * @returns the new ActionEvent
  52958. */
  52959. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52960. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52961. };
  52962. /**
  52963. * Helper function to auto-create an ActionEvent from a primitive
  52964. * @param prim defines the target primitive
  52965. * @param pointerPos defines the pointer position
  52966. * @param evt The original (browser) event
  52967. * @param additionalData additional data for the event
  52968. * @returns the new ActionEvent
  52969. */
  52970. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52971. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52972. };
  52973. return ActionEvent;
  52974. }());
  52975. BABYLON.ActionEvent = ActionEvent;
  52976. /**
  52977. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52978. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52979. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52980. */
  52981. var ActionManager = /** @class */ (function () {
  52982. /**
  52983. * Creates a new action manager
  52984. * @param scene defines the hosting scene
  52985. */
  52986. function ActionManager(scene) {
  52987. // Members
  52988. /** Gets the list of actions */
  52989. this.actions = new Array();
  52990. /** Gets the cursor to use when hovering items */
  52991. this.hoverCursor = '';
  52992. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52993. scene._actionManagers.push(this);
  52994. }
  52995. Object.defineProperty(ActionManager, "NothingTrigger", {
  52996. /**
  52997. * Nothing
  52998. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52999. */
  53000. get: function () {
  53001. return ActionManager._NothingTrigger;
  53002. },
  53003. enumerable: true,
  53004. configurable: true
  53005. });
  53006. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53007. /**
  53008. * On pick
  53009. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53010. */
  53011. get: function () {
  53012. return ActionManager._OnPickTrigger;
  53013. },
  53014. enumerable: true,
  53015. configurable: true
  53016. });
  53017. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53018. /**
  53019. * On left pick
  53020. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53021. */
  53022. get: function () {
  53023. return ActionManager._OnLeftPickTrigger;
  53024. },
  53025. enumerable: true,
  53026. configurable: true
  53027. });
  53028. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53029. /**
  53030. * On right pick
  53031. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53032. */
  53033. get: function () {
  53034. return ActionManager._OnRightPickTrigger;
  53035. },
  53036. enumerable: true,
  53037. configurable: true
  53038. });
  53039. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53040. /**
  53041. * On center pick
  53042. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53043. */
  53044. get: function () {
  53045. return ActionManager._OnCenterPickTrigger;
  53046. },
  53047. enumerable: true,
  53048. configurable: true
  53049. });
  53050. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53051. /**
  53052. * On pick down
  53053. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53054. */
  53055. get: function () {
  53056. return ActionManager._OnPickDownTrigger;
  53057. },
  53058. enumerable: true,
  53059. configurable: true
  53060. });
  53061. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53062. /**
  53063. * On double pick
  53064. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53065. */
  53066. get: function () {
  53067. return ActionManager._OnDoublePickTrigger;
  53068. },
  53069. enumerable: true,
  53070. configurable: true
  53071. });
  53072. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53073. /**
  53074. * On pick up
  53075. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53076. */
  53077. get: function () {
  53078. return ActionManager._OnPickUpTrigger;
  53079. },
  53080. enumerable: true,
  53081. configurable: true
  53082. });
  53083. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53084. /**
  53085. * On pick out.
  53086. * This trigger will only be raised if you also declared a OnPickDown
  53087. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53088. */
  53089. get: function () {
  53090. return ActionManager._OnPickOutTrigger;
  53091. },
  53092. enumerable: true,
  53093. configurable: true
  53094. });
  53095. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53096. /**
  53097. * On long press
  53098. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53099. */
  53100. get: function () {
  53101. return ActionManager._OnLongPressTrigger;
  53102. },
  53103. enumerable: true,
  53104. configurable: true
  53105. });
  53106. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53107. /**
  53108. * On pointer over
  53109. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53110. */
  53111. get: function () {
  53112. return ActionManager._OnPointerOverTrigger;
  53113. },
  53114. enumerable: true,
  53115. configurable: true
  53116. });
  53117. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53118. /**
  53119. * On pointer out
  53120. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53121. */
  53122. get: function () {
  53123. return ActionManager._OnPointerOutTrigger;
  53124. },
  53125. enumerable: true,
  53126. configurable: true
  53127. });
  53128. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53129. /**
  53130. * On every frame
  53131. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53132. */
  53133. get: function () {
  53134. return ActionManager._OnEveryFrameTrigger;
  53135. },
  53136. enumerable: true,
  53137. configurable: true
  53138. });
  53139. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53140. /**
  53141. * On intersection enter
  53142. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53143. */
  53144. get: function () {
  53145. return ActionManager._OnIntersectionEnterTrigger;
  53146. },
  53147. enumerable: true,
  53148. configurable: true
  53149. });
  53150. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53151. /**
  53152. * On intersection exit
  53153. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53154. */
  53155. get: function () {
  53156. return ActionManager._OnIntersectionExitTrigger;
  53157. },
  53158. enumerable: true,
  53159. configurable: true
  53160. });
  53161. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53162. /**
  53163. * On key down
  53164. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53165. */
  53166. get: function () {
  53167. return ActionManager._OnKeyDownTrigger;
  53168. },
  53169. enumerable: true,
  53170. configurable: true
  53171. });
  53172. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53173. /**
  53174. * On key up
  53175. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53176. */
  53177. get: function () {
  53178. return ActionManager._OnKeyUpTrigger;
  53179. },
  53180. enumerable: true,
  53181. configurable: true
  53182. });
  53183. // Methods
  53184. /**
  53185. * Releases all associated resources
  53186. */
  53187. ActionManager.prototype.dispose = function () {
  53188. var index = this._scene._actionManagers.indexOf(this);
  53189. for (var i = 0; i < this.actions.length; i++) {
  53190. var action = this.actions[i];
  53191. ActionManager.Triggers[action.trigger]--;
  53192. if (ActionManager.Triggers[action.trigger] === 0) {
  53193. delete ActionManager.Triggers[action.trigger];
  53194. }
  53195. }
  53196. if (index > -1) {
  53197. this._scene._actionManagers.splice(index, 1);
  53198. }
  53199. };
  53200. /**
  53201. * Gets hosting scene
  53202. * @returns the hosting scene
  53203. */
  53204. ActionManager.prototype.getScene = function () {
  53205. return this._scene;
  53206. };
  53207. /**
  53208. * Does this action manager handles actions of any of the given triggers
  53209. * @param triggers defines the triggers to be tested
  53210. * @return a boolean indicating whether one (or more) of the triggers is handled
  53211. */
  53212. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53213. for (var index = 0; index < this.actions.length; index++) {
  53214. var action = this.actions[index];
  53215. if (triggers.indexOf(action.trigger) > -1) {
  53216. return true;
  53217. }
  53218. }
  53219. return false;
  53220. };
  53221. /**
  53222. * Does this action manager handles actions of a given trigger
  53223. * @param trigger defines the trigger to be tested
  53224. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53225. * @return whether the trigger is handled
  53226. */
  53227. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53228. for (var index = 0; index < this.actions.length; index++) {
  53229. var action = this.actions[index];
  53230. if (action.trigger === trigger) {
  53231. if (parameterPredicate) {
  53232. if (parameterPredicate(action.getTriggerParameter())) {
  53233. return true;
  53234. }
  53235. }
  53236. else {
  53237. return true;
  53238. }
  53239. }
  53240. }
  53241. return false;
  53242. };
  53243. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53244. /**
  53245. * Does this action manager has pointer triggers
  53246. */
  53247. get: function () {
  53248. for (var index = 0; index < this.actions.length; index++) {
  53249. var action = this.actions[index];
  53250. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53251. return true;
  53252. }
  53253. }
  53254. return false;
  53255. },
  53256. enumerable: true,
  53257. configurable: true
  53258. });
  53259. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53260. /**
  53261. * Does this action manager has pick triggers
  53262. */
  53263. get: function () {
  53264. for (var index = 0; index < this.actions.length; index++) {
  53265. var action = this.actions[index];
  53266. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53267. return true;
  53268. }
  53269. }
  53270. return false;
  53271. },
  53272. enumerable: true,
  53273. configurable: true
  53274. });
  53275. Object.defineProperty(ActionManager, "HasTriggers", {
  53276. /**
  53277. * Does exist one action manager with at least one trigger
  53278. **/
  53279. get: function () {
  53280. for (var t in ActionManager.Triggers) {
  53281. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53282. return true;
  53283. }
  53284. }
  53285. return false;
  53286. },
  53287. enumerable: true,
  53288. configurable: true
  53289. });
  53290. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53291. /**
  53292. * Does exist one action manager with at least one pick trigger
  53293. **/
  53294. get: function () {
  53295. for (var t in ActionManager.Triggers) {
  53296. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53297. var t_int = parseInt(t);
  53298. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53299. return true;
  53300. }
  53301. }
  53302. }
  53303. return false;
  53304. },
  53305. enumerable: true,
  53306. configurable: true
  53307. });
  53308. /**
  53309. * Does exist one action manager that handles actions of a given trigger
  53310. * @param trigger defines the trigger to be tested
  53311. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53312. **/
  53313. ActionManager.HasSpecificTrigger = function (trigger) {
  53314. for (var t in ActionManager.Triggers) {
  53315. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53316. var t_int = parseInt(t);
  53317. if (t_int === trigger) {
  53318. return true;
  53319. }
  53320. }
  53321. }
  53322. return false;
  53323. };
  53324. /**
  53325. * Registers an action to this action manager
  53326. * @param action defines the action to be registered
  53327. * @return the action amended (prepared) after registration
  53328. */
  53329. ActionManager.prototype.registerAction = function (action) {
  53330. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53331. if (this.getScene().actionManager !== this) {
  53332. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53333. return null;
  53334. }
  53335. }
  53336. this.actions.push(action);
  53337. if (ActionManager.Triggers[action.trigger]) {
  53338. ActionManager.Triggers[action.trigger]++;
  53339. }
  53340. else {
  53341. ActionManager.Triggers[action.trigger] = 1;
  53342. }
  53343. action._actionManager = this;
  53344. action._prepare();
  53345. return action;
  53346. };
  53347. /**
  53348. * Unregisters an action to this action manager
  53349. * @param action defines the action to be unregistered
  53350. * @return a boolean indicating whether the action has been unregistered
  53351. */
  53352. ActionManager.prototype.unregisterAction = function (action) {
  53353. var index = this.actions.indexOf(action);
  53354. if (index !== -1) {
  53355. this.actions.splice(index, 1);
  53356. ActionManager.Triggers[action.trigger] -= 1;
  53357. if (ActionManager.Triggers[action.trigger] === 0) {
  53358. delete ActionManager.Triggers[action.trigger];
  53359. }
  53360. delete action._actionManager;
  53361. return true;
  53362. }
  53363. return false;
  53364. };
  53365. /**
  53366. * Process a specific trigger
  53367. * @param trigger defines the trigger to process
  53368. * @param evt defines the event details to be processed
  53369. */
  53370. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53371. for (var index = 0; index < this.actions.length; index++) {
  53372. var action = this.actions[index];
  53373. if (action.trigger === trigger) {
  53374. if (evt) {
  53375. if (trigger === ActionManager.OnKeyUpTrigger
  53376. || trigger === ActionManager.OnKeyDownTrigger) {
  53377. var parameter = action.getTriggerParameter();
  53378. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53379. if (!parameter.toLowerCase) {
  53380. continue;
  53381. }
  53382. var lowerCase = parameter.toLowerCase();
  53383. if (lowerCase !== evt.sourceEvent.key) {
  53384. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53385. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53386. if (actualkey !== lowerCase) {
  53387. continue;
  53388. }
  53389. }
  53390. }
  53391. }
  53392. }
  53393. action._executeCurrent(evt);
  53394. }
  53395. }
  53396. };
  53397. /** @hidden */
  53398. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53399. var properties = propertyPath.split(".");
  53400. for (var index = 0; index < properties.length - 1; index++) {
  53401. target = target[properties[index]];
  53402. }
  53403. return target;
  53404. };
  53405. /** @hidden */
  53406. ActionManager.prototype._getProperty = function (propertyPath) {
  53407. var properties = propertyPath.split(".");
  53408. return properties[properties.length - 1];
  53409. };
  53410. /**
  53411. * Serialize this manager to a JSON object
  53412. * @param name defines the property name to store this manager
  53413. * @returns a JSON representation of this manager
  53414. */
  53415. ActionManager.prototype.serialize = function (name) {
  53416. var root = {
  53417. children: new Array(),
  53418. name: name,
  53419. type: 3,
  53420. properties: new Array() // Empty for root but required
  53421. };
  53422. for (var i = 0; i < this.actions.length; i++) {
  53423. var triggerObject = {
  53424. type: 0,
  53425. children: new Array(),
  53426. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53427. properties: new Array()
  53428. };
  53429. var triggerOptions = this.actions[i].triggerOptions;
  53430. if (triggerOptions && typeof triggerOptions !== "number") {
  53431. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53432. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53433. }
  53434. else {
  53435. var parameter = {};
  53436. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53437. if (triggerOptions.parameter.mesh) {
  53438. parameter._meshId = triggerOptions.parameter.mesh.id;
  53439. }
  53440. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53441. }
  53442. }
  53443. // Serialize child action, recursively
  53444. this.actions[i].serialize(triggerObject);
  53445. // Add serialized trigger
  53446. root.children.push(triggerObject);
  53447. }
  53448. return root;
  53449. };
  53450. /**
  53451. * Creates a new ActionManager from a JSON data
  53452. * @param parsedActions defines the JSON data to read from
  53453. * @param object defines the hosting mesh
  53454. * @param scene defines the hosting scene
  53455. */
  53456. ActionManager.Parse = function (parsedActions, object, scene) {
  53457. var actionManager = new ActionManager(scene);
  53458. if (object === null)
  53459. scene.actionManager = actionManager;
  53460. else
  53461. object.actionManager = actionManager;
  53462. // instanciate a new object
  53463. var instanciate = function (name, params) {
  53464. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53465. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53466. newInstance.constructor.apply(newInstance, params);
  53467. return newInstance;
  53468. };
  53469. var parseParameter = function (name, value, target, propertyPath) {
  53470. if (propertyPath === null) {
  53471. // String, boolean or float
  53472. var floatValue = parseFloat(value);
  53473. if (value === "true" || value === "false")
  53474. return value === "true";
  53475. else
  53476. return isNaN(floatValue) ? value : floatValue;
  53477. }
  53478. var effectiveTarget = propertyPath.split(".");
  53479. var values = value.split(",");
  53480. // Get effective Target
  53481. for (var i = 0; i < effectiveTarget.length; i++) {
  53482. target = target[effectiveTarget[i]];
  53483. }
  53484. // Return appropriate value with its type
  53485. if (typeof (target) === "boolean")
  53486. return values[0] === "true";
  53487. if (typeof (target) === "string")
  53488. return values[0];
  53489. // Parameters with multiple values such as Vector3 etc.
  53490. var split = new Array();
  53491. for (var i = 0; i < values.length; i++)
  53492. split.push(parseFloat(values[i]));
  53493. if (target instanceof BABYLON.Vector3)
  53494. return BABYLON.Vector3.FromArray(split);
  53495. if (target instanceof BABYLON.Vector4)
  53496. return BABYLON.Vector4.FromArray(split);
  53497. if (target instanceof BABYLON.Color3)
  53498. return BABYLON.Color3.FromArray(split);
  53499. if (target instanceof BABYLON.Color4)
  53500. return BABYLON.Color4.FromArray(split);
  53501. return parseFloat(values[0]);
  53502. };
  53503. // traverse graph per trigger
  53504. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53505. if (combineArray === void 0) { combineArray = null; }
  53506. if (parsedAction.detached)
  53507. return;
  53508. var parameters = new Array();
  53509. var target = null;
  53510. var propertyPath = null;
  53511. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53512. // Parameters
  53513. if (parsedAction.type === 2)
  53514. parameters.push(actionManager);
  53515. else
  53516. parameters.push(trigger);
  53517. if (combine) {
  53518. var actions = new Array();
  53519. for (var j = 0; j < parsedAction.combine.length; j++) {
  53520. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53521. }
  53522. parameters.push(actions);
  53523. }
  53524. else {
  53525. for (var i = 0; i < parsedAction.properties.length; i++) {
  53526. var value = parsedAction.properties[i].value;
  53527. var name = parsedAction.properties[i].name;
  53528. var targetType = parsedAction.properties[i].targetType;
  53529. if (name === "target")
  53530. if (targetType !== null && targetType === "SceneProperties")
  53531. value = target = scene;
  53532. else
  53533. value = target = scene.getNodeByName(value);
  53534. else if (name === "parent")
  53535. value = scene.getNodeByName(value);
  53536. else if (name === "sound")
  53537. value = scene.getSoundByName(value);
  53538. else if (name !== "propertyPath") {
  53539. if (parsedAction.type === 2 && name === "operator")
  53540. value = BABYLON.ValueCondition[value];
  53541. else
  53542. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53543. }
  53544. else {
  53545. propertyPath = value;
  53546. }
  53547. parameters.push(value);
  53548. }
  53549. }
  53550. if (combineArray === null) {
  53551. parameters.push(condition);
  53552. }
  53553. else {
  53554. parameters.push(null);
  53555. }
  53556. // If interpolate value action
  53557. if (parsedAction.name === "InterpolateValueAction") {
  53558. var param = parameters[parameters.length - 2];
  53559. parameters[parameters.length - 1] = param;
  53560. parameters[parameters.length - 2] = condition;
  53561. }
  53562. // Action or condition(s) and not CombineAction
  53563. var newAction = instanciate(parsedAction.name, parameters);
  53564. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53565. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53566. if (action)
  53567. action.then(nothing);
  53568. else
  53569. actionManager.registerAction(nothing);
  53570. action = nothing;
  53571. }
  53572. if (combineArray === null) {
  53573. if (newAction instanceof BABYLON.Condition) {
  53574. condition = newAction;
  53575. newAction = action;
  53576. }
  53577. else {
  53578. condition = null;
  53579. if (action)
  53580. action.then(newAction);
  53581. else
  53582. actionManager.registerAction(newAction);
  53583. }
  53584. }
  53585. else {
  53586. combineArray.push(newAction);
  53587. }
  53588. for (var i = 0; i < parsedAction.children.length; i++)
  53589. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53590. };
  53591. // triggers
  53592. for (var i = 0; i < parsedActions.children.length; i++) {
  53593. var triggerParams;
  53594. var trigger = parsedActions.children[i];
  53595. if (trigger.properties.length > 0) {
  53596. var param = trigger.properties[0].value;
  53597. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53598. if (value._meshId) {
  53599. value.mesh = scene.getMeshByID(value._meshId);
  53600. }
  53601. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53602. }
  53603. else
  53604. triggerParams = ActionManager[trigger.name];
  53605. for (var j = 0; j < trigger.children.length; j++) {
  53606. if (!trigger.detached)
  53607. traverse(trigger.children[j], triggerParams, null, null);
  53608. }
  53609. }
  53610. };
  53611. /**
  53612. * Get a trigger name by index
  53613. * @param trigger defines the trigger index
  53614. * @returns a trigger name
  53615. */
  53616. ActionManager.GetTriggerName = function (trigger) {
  53617. switch (trigger) {
  53618. case 0: return "NothingTrigger";
  53619. case 1: return "OnPickTrigger";
  53620. case 2: return "OnLeftPickTrigger";
  53621. case 3: return "OnRightPickTrigger";
  53622. case 4: return "OnCenterPickTrigger";
  53623. case 5: return "OnPickDownTrigger";
  53624. case 6: return "OnPickUpTrigger";
  53625. case 7: return "OnLongPressTrigger";
  53626. case 8: return "OnPointerOverTrigger";
  53627. case 9: return "OnPointerOutTrigger";
  53628. case 10: return "OnEveryFrameTrigger";
  53629. case 11: return "OnIntersectionEnterTrigger";
  53630. case 12: return "OnIntersectionExitTrigger";
  53631. case 13: return "OnKeyDownTrigger";
  53632. case 14: return "OnKeyUpTrigger";
  53633. case 15: return "OnPickOutTrigger";
  53634. default: return "";
  53635. }
  53636. };
  53637. // Statics
  53638. ActionManager._NothingTrigger = 0;
  53639. ActionManager._OnPickTrigger = 1;
  53640. ActionManager._OnLeftPickTrigger = 2;
  53641. ActionManager._OnRightPickTrigger = 3;
  53642. ActionManager._OnCenterPickTrigger = 4;
  53643. ActionManager._OnPickDownTrigger = 5;
  53644. ActionManager._OnDoublePickTrigger = 6;
  53645. ActionManager._OnPickUpTrigger = 7;
  53646. ActionManager._OnLongPressTrigger = 8;
  53647. ActionManager._OnPointerOverTrigger = 9;
  53648. ActionManager._OnPointerOutTrigger = 10;
  53649. ActionManager._OnEveryFrameTrigger = 11;
  53650. ActionManager._OnIntersectionEnterTrigger = 12;
  53651. ActionManager._OnIntersectionExitTrigger = 13;
  53652. ActionManager._OnKeyDownTrigger = 14;
  53653. ActionManager._OnKeyUpTrigger = 15;
  53654. ActionManager._OnPickOutTrigger = 16;
  53655. /** Gets the list of active triggers */
  53656. ActionManager.Triggers = {};
  53657. return ActionManager;
  53658. }());
  53659. BABYLON.ActionManager = ActionManager;
  53660. })(BABYLON || (BABYLON = {}));
  53661. //# sourceMappingURL=babylon.actionManager.js.map
  53662. var BABYLON;
  53663. (function (BABYLON) {
  53664. var InterpolateValueAction = /** @class */ (function (_super) {
  53665. __extends(InterpolateValueAction, _super);
  53666. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53667. if (duration === void 0) { duration = 1000; }
  53668. var _this = _super.call(this, triggerOptions, condition) || this;
  53669. _this.propertyPath = propertyPath;
  53670. _this.value = value;
  53671. _this.duration = duration;
  53672. _this.stopOtherAnimations = stopOtherAnimations;
  53673. _this.onInterpolationDone = onInterpolationDone;
  53674. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53675. _this._target = _this._effectiveTarget = target;
  53676. return _this;
  53677. }
  53678. InterpolateValueAction.prototype._prepare = function () {
  53679. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53680. this._property = this._getProperty(this.propertyPath);
  53681. };
  53682. InterpolateValueAction.prototype.execute = function () {
  53683. var _this = this;
  53684. var scene = this._actionManager.getScene();
  53685. var keys = [
  53686. {
  53687. frame: 0,
  53688. value: this._effectiveTarget[this._property]
  53689. }, {
  53690. frame: 100,
  53691. value: this.value
  53692. }
  53693. ];
  53694. var dataType;
  53695. if (typeof this.value === "number") {
  53696. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53697. }
  53698. else if (this.value instanceof BABYLON.Color3) {
  53699. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53700. }
  53701. else if (this.value instanceof BABYLON.Vector3) {
  53702. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53703. }
  53704. else if (this.value instanceof BABYLON.Matrix) {
  53705. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53706. }
  53707. else if (this.value instanceof BABYLON.Quaternion) {
  53708. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53709. }
  53710. else {
  53711. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53712. return;
  53713. }
  53714. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53715. animation.setKeys(keys);
  53716. if (this.stopOtherAnimations) {
  53717. scene.stopAnimation(this._effectiveTarget);
  53718. }
  53719. var wrapper = function () {
  53720. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53721. if (_this.onInterpolationDone) {
  53722. _this.onInterpolationDone();
  53723. }
  53724. };
  53725. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53726. };
  53727. InterpolateValueAction.prototype.serialize = function (parent) {
  53728. return _super.prototype._serialize.call(this, {
  53729. name: "InterpolateValueAction",
  53730. properties: [
  53731. BABYLON.Action._GetTargetProperty(this._target),
  53732. { name: "propertyPath", value: this.propertyPath },
  53733. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53734. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53735. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53736. ]
  53737. }, parent);
  53738. };
  53739. return InterpolateValueAction;
  53740. }(BABYLON.Action));
  53741. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53742. })(BABYLON || (BABYLON = {}));
  53743. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53744. var BABYLON;
  53745. (function (BABYLON) {
  53746. var SwitchBooleanAction = /** @class */ (function (_super) {
  53747. __extends(SwitchBooleanAction, _super);
  53748. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53749. var _this = _super.call(this, triggerOptions, condition) || this;
  53750. _this.propertyPath = propertyPath;
  53751. _this._target = _this._effectiveTarget = target;
  53752. return _this;
  53753. }
  53754. SwitchBooleanAction.prototype._prepare = function () {
  53755. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53756. this._property = this._getProperty(this.propertyPath);
  53757. };
  53758. SwitchBooleanAction.prototype.execute = function () {
  53759. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53760. };
  53761. SwitchBooleanAction.prototype.serialize = function (parent) {
  53762. return _super.prototype._serialize.call(this, {
  53763. name: "SwitchBooleanAction",
  53764. properties: [
  53765. BABYLON.Action._GetTargetProperty(this._target),
  53766. { name: "propertyPath", value: this.propertyPath }
  53767. ]
  53768. }, parent);
  53769. };
  53770. return SwitchBooleanAction;
  53771. }(BABYLON.Action));
  53772. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53773. var SetStateAction = /** @class */ (function (_super) {
  53774. __extends(SetStateAction, _super);
  53775. function SetStateAction(triggerOptions, target, value, condition) {
  53776. var _this = _super.call(this, triggerOptions, condition) || this;
  53777. _this.value = value;
  53778. _this._target = target;
  53779. return _this;
  53780. }
  53781. SetStateAction.prototype.execute = function () {
  53782. this._target.state = this.value;
  53783. };
  53784. SetStateAction.prototype.serialize = function (parent) {
  53785. return _super.prototype._serialize.call(this, {
  53786. name: "SetStateAction",
  53787. properties: [
  53788. BABYLON.Action._GetTargetProperty(this._target),
  53789. { name: "value", value: this.value }
  53790. ]
  53791. }, parent);
  53792. };
  53793. return SetStateAction;
  53794. }(BABYLON.Action));
  53795. BABYLON.SetStateAction = SetStateAction;
  53796. var SetValueAction = /** @class */ (function (_super) {
  53797. __extends(SetValueAction, _super);
  53798. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53799. var _this = _super.call(this, triggerOptions, condition) || this;
  53800. _this.propertyPath = propertyPath;
  53801. _this.value = value;
  53802. _this._target = _this._effectiveTarget = target;
  53803. return _this;
  53804. }
  53805. SetValueAction.prototype._prepare = function () {
  53806. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53807. this._property = this._getProperty(this.propertyPath);
  53808. };
  53809. SetValueAction.prototype.execute = function () {
  53810. this._effectiveTarget[this._property] = this.value;
  53811. if (this._target.markAsDirty) {
  53812. this._target.markAsDirty(this._property);
  53813. }
  53814. };
  53815. SetValueAction.prototype.serialize = function (parent) {
  53816. return _super.prototype._serialize.call(this, {
  53817. name: "SetValueAction",
  53818. properties: [
  53819. BABYLON.Action._GetTargetProperty(this._target),
  53820. { name: "propertyPath", value: this.propertyPath },
  53821. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53822. ]
  53823. }, parent);
  53824. };
  53825. return SetValueAction;
  53826. }(BABYLON.Action));
  53827. BABYLON.SetValueAction = SetValueAction;
  53828. var IncrementValueAction = /** @class */ (function (_super) {
  53829. __extends(IncrementValueAction, _super);
  53830. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53831. var _this = _super.call(this, triggerOptions, condition) || this;
  53832. _this.propertyPath = propertyPath;
  53833. _this.value = value;
  53834. _this._target = _this._effectiveTarget = target;
  53835. return _this;
  53836. }
  53837. IncrementValueAction.prototype._prepare = function () {
  53838. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53839. this._property = this._getProperty(this.propertyPath);
  53840. if (typeof this._effectiveTarget[this._property] !== "number") {
  53841. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53842. }
  53843. };
  53844. IncrementValueAction.prototype.execute = function () {
  53845. this._effectiveTarget[this._property] += this.value;
  53846. if (this._target.markAsDirty) {
  53847. this._target.markAsDirty(this._property);
  53848. }
  53849. };
  53850. IncrementValueAction.prototype.serialize = function (parent) {
  53851. return _super.prototype._serialize.call(this, {
  53852. name: "IncrementValueAction",
  53853. properties: [
  53854. BABYLON.Action._GetTargetProperty(this._target),
  53855. { name: "propertyPath", value: this.propertyPath },
  53856. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53857. ]
  53858. }, parent);
  53859. };
  53860. return IncrementValueAction;
  53861. }(BABYLON.Action));
  53862. BABYLON.IncrementValueAction = IncrementValueAction;
  53863. var PlayAnimationAction = /** @class */ (function (_super) {
  53864. __extends(PlayAnimationAction, _super);
  53865. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53866. var _this = _super.call(this, triggerOptions, condition) || this;
  53867. _this.from = from;
  53868. _this.to = to;
  53869. _this.loop = loop;
  53870. _this._target = target;
  53871. return _this;
  53872. }
  53873. PlayAnimationAction.prototype._prepare = function () {
  53874. };
  53875. PlayAnimationAction.prototype.execute = function () {
  53876. var scene = this._actionManager.getScene();
  53877. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53878. };
  53879. PlayAnimationAction.prototype.serialize = function (parent) {
  53880. return _super.prototype._serialize.call(this, {
  53881. name: "PlayAnimationAction",
  53882. properties: [
  53883. BABYLON.Action._GetTargetProperty(this._target),
  53884. { name: "from", value: String(this.from) },
  53885. { name: "to", value: String(this.to) },
  53886. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53887. ]
  53888. }, parent);
  53889. };
  53890. return PlayAnimationAction;
  53891. }(BABYLON.Action));
  53892. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53893. var StopAnimationAction = /** @class */ (function (_super) {
  53894. __extends(StopAnimationAction, _super);
  53895. function StopAnimationAction(triggerOptions, target, condition) {
  53896. var _this = _super.call(this, triggerOptions, condition) || this;
  53897. _this._target = target;
  53898. return _this;
  53899. }
  53900. StopAnimationAction.prototype._prepare = function () {
  53901. };
  53902. StopAnimationAction.prototype.execute = function () {
  53903. var scene = this._actionManager.getScene();
  53904. scene.stopAnimation(this._target);
  53905. };
  53906. StopAnimationAction.prototype.serialize = function (parent) {
  53907. return _super.prototype._serialize.call(this, {
  53908. name: "StopAnimationAction",
  53909. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53910. }, parent);
  53911. };
  53912. return StopAnimationAction;
  53913. }(BABYLON.Action));
  53914. BABYLON.StopAnimationAction = StopAnimationAction;
  53915. var DoNothingAction = /** @class */ (function (_super) {
  53916. __extends(DoNothingAction, _super);
  53917. function DoNothingAction(triggerOptions, condition) {
  53918. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53919. return _super.call(this, triggerOptions, condition) || this;
  53920. }
  53921. DoNothingAction.prototype.execute = function () {
  53922. };
  53923. DoNothingAction.prototype.serialize = function (parent) {
  53924. return _super.prototype._serialize.call(this, {
  53925. name: "DoNothingAction",
  53926. properties: []
  53927. }, parent);
  53928. };
  53929. return DoNothingAction;
  53930. }(BABYLON.Action));
  53931. BABYLON.DoNothingAction = DoNothingAction;
  53932. var CombineAction = /** @class */ (function (_super) {
  53933. __extends(CombineAction, _super);
  53934. function CombineAction(triggerOptions, children, condition) {
  53935. var _this = _super.call(this, triggerOptions, condition) || this;
  53936. _this.children = children;
  53937. return _this;
  53938. }
  53939. CombineAction.prototype._prepare = function () {
  53940. for (var index = 0; index < this.children.length; index++) {
  53941. this.children[index]._actionManager = this._actionManager;
  53942. this.children[index]._prepare();
  53943. }
  53944. };
  53945. CombineAction.prototype.execute = function (evt) {
  53946. for (var index = 0; index < this.children.length; index++) {
  53947. this.children[index].execute(evt);
  53948. }
  53949. };
  53950. CombineAction.prototype.serialize = function (parent) {
  53951. var serializationObject = _super.prototype._serialize.call(this, {
  53952. name: "CombineAction",
  53953. properties: [],
  53954. combine: []
  53955. }, parent);
  53956. for (var i = 0; i < this.children.length; i++) {
  53957. serializationObject.combine.push(this.children[i].serialize(null));
  53958. }
  53959. return serializationObject;
  53960. };
  53961. return CombineAction;
  53962. }(BABYLON.Action));
  53963. BABYLON.CombineAction = CombineAction;
  53964. var ExecuteCodeAction = /** @class */ (function (_super) {
  53965. __extends(ExecuteCodeAction, _super);
  53966. function ExecuteCodeAction(triggerOptions, func, condition) {
  53967. var _this = _super.call(this, triggerOptions, condition) || this;
  53968. _this.func = func;
  53969. return _this;
  53970. }
  53971. ExecuteCodeAction.prototype.execute = function (evt) {
  53972. this.func(evt);
  53973. };
  53974. return ExecuteCodeAction;
  53975. }(BABYLON.Action));
  53976. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53977. var SetParentAction = /** @class */ (function (_super) {
  53978. __extends(SetParentAction, _super);
  53979. function SetParentAction(triggerOptions, target, parent, condition) {
  53980. var _this = _super.call(this, triggerOptions, condition) || this;
  53981. _this._target = target;
  53982. _this._parent = parent;
  53983. return _this;
  53984. }
  53985. SetParentAction.prototype._prepare = function () {
  53986. };
  53987. SetParentAction.prototype.execute = function () {
  53988. if (this._target.parent === this._parent) {
  53989. return;
  53990. }
  53991. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53992. invertParentWorldMatrix.invert();
  53993. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53994. this._target.parent = this._parent;
  53995. };
  53996. SetParentAction.prototype.serialize = function (parent) {
  53997. return _super.prototype._serialize.call(this, {
  53998. name: "SetParentAction",
  53999. properties: [
  54000. BABYLON.Action._GetTargetProperty(this._target),
  54001. BABYLON.Action._GetTargetProperty(this._parent),
  54002. ]
  54003. }, parent);
  54004. };
  54005. return SetParentAction;
  54006. }(BABYLON.Action));
  54007. BABYLON.SetParentAction = SetParentAction;
  54008. var PlaySoundAction = /** @class */ (function (_super) {
  54009. __extends(PlaySoundAction, _super);
  54010. function PlaySoundAction(triggerOptions, sound, condition) {
  54011. var _this = _super.call(this, triggerOptions, condition) || this;
  54012. _this._sound = sound;
  54013. return _this;
  54014. }
  54015. PlaySoundAction.prototype._prepare = function () {
  54016. };
  54017. PlaySoundAction.prototype.execute = function () {
  54018. if (this._sound !== undefined)
  54019. this._sound.play();
  54020. };
  54021. PlaySoundAction.prototype.serialize = function (parent) {
  54022. return _super.prototype._serialize.call(this, {
  54023. name: "PlaySoundAction",
  54024. properties: [{ name: "sound", value: this._sound.name }]
  54025. }, parent);
  54026. };
  54027. return PlaySoundAction;
  54028. }(BABYLON.Action));
  54029. BABYLON.PlaySoundAction = PlaySoundAction;
  54030. var StopSoundAction = /** @class */ (function (_super) {
  54031. __extends(StopSoundAction, _super);
  54032. function StopSoundAction(triggerOptions, sound, condition) {
  54033. var _this = _super.call(this, triggerOptions, condition) || this;
  54034. _this._sound = sound;
  54035. return _this;
  54036. }
  54037. StopSoundAction.prototype._prepare = function () {
  54038. };
  54039. StopSoundAction.prototype.execute = function () {
  54040. if (this._sound !== undefined)
  54041. this._sound.stop();
  54042. };
  54043. StopSoundAction.prototype.serialize = function (parent) {
  54044. return _super.prototype._serialize.call(this, {
  54045. name: "StopSoundAction",
  54046. properties: [{ name: "sound", value: this._sound.name }]
  54047. }, parent);
  54048. };
  54049. return StopSoundAction;
  54050. }(BABYLON.Action));
  54051. BABYLON.StopSoundAction = StopSoundAction;
  54052. })(BABYLON || (BABYLON = {}));
  54053. //# sourceMappingURL=babylon.directActions.js.map
  54054. var BABYLON;
  54055. (function (BABYLON) {
  54056. var SpriteManager = /** @class */ (function () {
  54057. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54058. if (epsilon === void 0) { epsilon = 0.01; }
  54059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54060. this.name = name;
  54061. this.sprites = new Array();
  54062. this.renderingGroupId = 0;
  54063. this.layerMask = 0x0FFFFFFF;
  54064. this.fogEnabled = true;
  54065. this.isPickable = false;
  54066. /**
  54067. * An event triggered when the manager is disposed.
  54068. */
  54069. this.onDisposeObservable = new BABYLON.Observable();
  54070. this._vertexBuffers = {};
  54071. this._capacity = capacity;
  54072. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54073. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54074. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54075. if (cellSize.width && cellSize.height) {
  54076. this.cellWidth = cellSize.width;
  54077. this.cellHeight = cellSize.height;
  54078. }
  54079. else if (cellSize !== undefined) {
  54080. this.cellWidth = cellSize;
  54081. this.cellHeight = cellSize;
  54082. }
  54083. else {
  54084. return;
  54085. }
  54086. this._epsilon = epsilon;
  54087. this._scene = scene;
  54088. this._scene.spriteManagers.push(this);
  54089. var indices = [];
  54090. var index = 0;
  54091. for (var count = 0; count < capacity; count++) {
  54092. indices.push(index);
  54093. indices.push(index + 1);
  54094. indices.push(index + 2);
  54095. indices.push(index);
  54096. indices.push(index + 2);
  54097. indices.push(index + 3);
  54098. index += 4;
  54099. }
  54100. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54101. // VBO
  54102. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54103. this._vertexData = new Float32Array(capacity * 16 * 4);
  54104. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54105. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54106. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54107. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54108. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54109. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54110. this._vertexBuffers["options"] = options;
  54111. this._vertexBuffers["cellInfo"] = cellInfo;
  54112. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54113. // Effects
  54114. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54115. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54116. }
  54117. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54118. set: function (callback) {
  54119. if (this._onDisposeObserver) {
  54120. this.onDisposeObservable.remove(this._onDisposeObserver);
  54121. }
  54122. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54123. },
  54124. enumerable: true,
  54125. configurable: true
  54126. });
  54127. Object.defineProperty(SpriteManager.prototype, "texture", {
  54128. get: function () {
  54129. return this._spriteTexture;
  54130. },
  54131. set: function (value) {
  54132. this._spriteTexture = value;
  54133. },
  54134. enumerable: true,
  54135. configurable: true
  54136. });
  54137. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54138. var arrayOffset = index * 16;
  54139. if (offsetX === 0)
  54140. offsetX = this._epsilon;
  54141. else if (offsetX === 1)
  54142. offsetX = 1 - this._epsilon;
  54143. if (offsetY === 0)
  54144. offsetY = this._epsilon;
  54145. else if (offsetY === 1)
  54146. offsetY = 1 - this._epsilon;
  54147. this._vertexData[arrayOffset] = sprite.position.x;
  54148. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54149. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54150. this._vertexData[arrayOffset + 3] = sprite.angle;
  54151. this._vertexData[arrayOffset + 4] = sprite.width;
  54152. this._vertexData[arrayOffset + 5] = sprite.height;
  54153. this._vertexData[arrayOffset + 6] = offsetX;
  54154. this._vertexData[arrayOffset + 7] = offsetY;
  54155. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54156. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54157. var offset = (sprite.cellIndex / rowSize) >> 0;
  54158. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54159. this._vertexData[arrayOffset + 11] = offset;
  54160. // Color
  54161. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54162. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54163. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54164. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54165. };
  54166. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54167. var count = Math.min(this._capacity, this.sprites.length);
  54168. var min = BABYLON.Vector3.Zero();
  54169. var max = BABYLON.Vector3.Zero();
  54170. var distance = Number.MAX_VALUE;
  54171. var currentSprite = null;
  54172. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54173. var cameraView = camera.getViewMatrix();
  54174. for (var index = 0; index < count; index++) {
  54175. var sprite = this.sprites[index];
  54176. if (!sprite) {
  54177. continue;
  54178. }
  54179. if (predicate) {
  54180. if (!predicate(sprite)) {
  54181. continue;
  54182. }
  54183. }
  54184. else if (!sprite.isPickable) {
  54185. continue;
  54186. }
  54187. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54188. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54189. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54190. if (ray.intersectsBoxMinMax(min, max)) {
  54191. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54192. if (distance > currentDistance) {
  54193. distance = currentDistance;
  54194. currentSprite = sprite;
  54195. if (fastCheck) {
  54196. break;
  54197. }
  54198. }
  54199. }
  54200. }
  54201. if (currentSprite) {
  54202. var result = new BABYLON.PickingInfo();
  54203. result.hit = true;
  54204. result.pickedSprite = currentSprite;
  54205. result.distance = distance;
  54206. return result;
  54207. }
  54208. return null;
  54209. };
  54210. SpriteManager.prototype.render = function () {
  54211. // Check
  54212. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54213. return;
  54214. var engine = this._scene.getEngine();
  54215. var baseSize = this._spriteTexture.getBaseSize();
  54216. // Sprites
  54217. var deltaTime = engine.getDeltaTime();
  54218. var max = Math.min(this._capacity, this.sprites.length);
  54219. var rowSize = baseSize.width / this.cellWidth;
  54220. var offset = 0;
  54221. for (var index = 0; index < max; index++) {
  54222. var sprite = this.sprites[index];
  54223. if (!sprite) {
  54224. continue;
  54225. }
  54226. sprite._animate(deltaTime);
  54227. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54228. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54229. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54230. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54231. }
  54232. this._buffer.update(this._vertexData);
  54233. // Render
  54234. var effect = this._effectBase;
  54235. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54236. effect = this._effectFog;
  54237. }
  54238. engine.enableEffect(effect);
  54239. var viewMatrix = this._scene.getViewMatrix();
  54240. effect.setTexture("diffuseSampler", this._spriteTexture);
  54241. effect.setMatrix("view", viewMatrix);
  54242. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54243. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54244. // Fog
  54245. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54246. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54247. effect.setColor3("vFogColor", this._scene.fogColor);
  54248. }
  54249. // VBOs
  54250. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54251. // Draw order
  54252. engine.setDepthFunctionToLessOrEqual();
  54253. effect.setBool("alphaTest", true);
  54254. engine.setColorWrite(false);
  54255. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54256. engine.setColorWrite(true);
  54257. effect.setBool("alphaTest", false);
  54258. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54259. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54260. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54261. };
  54262. SpriteManager.prototype.dispose = function () {
  54263. if (this._buffer) {
  54264. this._buffer.dispose();
  54265. this._buffer = null;
  54266. }
  54267. if (this._indexBuffer) {
  54268. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54269. this._indexBuffer = null;
  54270. }
  54271. if (this._spriteTexture) {
  54272. this._spriteTexture.dispose();
  54273. this._spriteTexture = null;
  54274. }
  54275. // Remove from scene
  54276. var index = this._scene.spriteManagers.indexOf(this);
  54277. this._scene.spriteManagers.splice(index, 1);
  54278. // Callback
  54279. this.onDisposeObservable.notifyObservers(this);
  54280. this.onDisposeObservable.clear();
  54281. };
  54282. return SpriteManager;
  54283. }());
  54284. BABYLON.SpriteManager = SpriteManager;
  54285. })(BABYLON || (BABYLON = {}));
  54286. //# sourceMappingURL=babylon.spriteManager.js.map
  54287. var BABYLON;
  54288. (function (BABYLON) {
  54289. var Sprite = /** @class */ (function () {
  54290. function Sprite(name, manager) {
  54291. this.name = name;
  54292. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54293. this.width = 1.0;
  54294. this.height = 1.0;
  54295. this.angle = 0;
  54296. this.cellIndex = 0;
  54297. this.invertU = 0;
  54298. this.invertV = 0;
  54299. this.animations = new Array();
  54300. this.isPickable = false;
  54301. this._animationStarted = false;
  54302. this._loopAnimation = false;
  54303. this._fromIndex = 0;
  54304. this._toIndex = 0;
  54305. this._delay = 0;
  54306. this._direction = 1;
  54307. this._time = 0;
  54308. this._manager = manager;
  54309. this._manager.sprites.push(this);
  54310. this.position = BABYLON.Vector3.Zero();
  54311. }
  54312. Object.defineProperty(Sprite.prototype, "size", {
  54313. get: function () {
  54314. return this.width;
  54315. },
  54316. set: function (value) {
  54317. this.width = value;
  54318. this.height = value;
  54319. },
  54320. enumerable: true,
  54321. configurable: true
  54322. });
  54323. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54324. this._fromIndex = from;
  54325. this._toIndex = to;
  54326. this._loopAnimation = loop;
  54327. this._delay = delay;
  54328. this._animationStarted = true;
  54329. this._direction = from < to ? 1 : -1;
  54330. this.cellIndex = from;
  54331. this._time = 0;
  54332. this._onAnimationEnd = onAnimationEnd;
  54333. };
  54334. Sprite.prototype.stopAnimation = function () {
  54335. this._animationStarted = false;
  54336. };
  54337. Sprite.prototype._animate = function (deltaTime) {
  54338. if (!this._animationStarted)
  54339. return;
  54340. this._time += deltaTime;
  54341. if (this._time > this._delay) {
  54342. this._time = this._time % this._delay;
  54343. this.cellIndex += this._direction;
  54344. if (this.cellIndex > this._toIndex) {
  54345. if (this._loopAnimation) {
  54346. this.cellIndex = this._fromIndex;
  54347. }
  54348. else {
  54349. this.cellIndex = this._toIndex;
  54350. this._animationStarted = false;
  54351. if (this._onAnimationEnd) {
  54352. this._onAnimationEnd();
  54353. }
  54354. if (this.disposeWhenFinishedAnimating) {
  54355. this.dispose();
  54356. }
  54357. }
  54358. }
  54359. }
  54360. };
  54361. Sprite.prototype.dispose = function () {
  54362. for (var i = 0; i < this._manager.sprites.length; i++) {
  54363. if (this._manager.sprites[i] == this) {
  54364. this._manager.sprites.splice(i, 1);
  54365. }
  54366. }
  54367. };
  54368. return Sprite;
  54369. }());
  54370. BABYLON.Sprite = Sprite;
  54371. })(BABYLON || (BABYLON = {}));
  54372. //# sourceMappingURL=babylon.sprite.js.map
  54373. var BABYLON;
  54374. (function (BABYLON) {
  54375. var IntersectionInfo = /** @class */ (function () {
  54376. function IntersectionInfo(bu, bv, distance) {
  54377. this.bu = bu;
  54378. this.bv = bv;
  54379. this.distance = distance;
  54380. this.faceId = 0;
  54381. this.subMeshId = 0;
  54382. }
  54383. return IntersectionInfo;
  54384. }());
  54385. BABYLON.IntersectionInfo = IntersectionInfo;
  54386. var PickingInfo = /** @class */ (function () {
  54387. function PickingInfo() {
  54388. this.hit = false;
  54389. this.distance = 0;
  54390. this.pickedPoint = null;
  54391. this.pickedMesh = null;
  54392. this.bu = 0;
  54393. this.bv = 0;
  54394. this.faceId = -1;
  54395. this.subMeshId = 0;
  54396. this.pickedSprite = null;
  54397. }
  54398. // Methods
  54399. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54400. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54401. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54402. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54403. return null;
  54404. }
  54405. var indices = this.pickedMesh.getIndices();
  54406. if (!indices) {
  54407. return null;
  54408. }
  54409. var result;
  54410. if (useVerticesNormals) {
  54411. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54412. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54413. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54414. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54415. normal0 = normal0.scale(this.bu);
  54416. normal1 = normal1.scale(this.bv);
  54417. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54418. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54419. }
  54420. else {
  54421. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54422. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54423. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54424. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54425. var p1p2 = vertex1.subtract(vertex2);
  54426. var p3p2 = vertex3.subtract(vertex2);
  54427. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54428. }
  54429. if (useWorldCoordinates) {
  54430. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54431. }
  54432. return BABYLON.Vector3.Normalize(result);
  54433. };
  54434. PickingInfo.prototype.getTextureCoordinates = function () {
  54435. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54436. return null;
  54437. }
  54438. var indices = this.pickedMesh.getIndices();
  54439. if (!indices) {
  54440. return null;
  54441. }
  54442. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54443. if (!uvs) {
  54444. return null;
  54445. }
  54446. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54447. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54448. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54449. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54450. uv1 = uv1.scale(this.bu);
  54451. uv2 = uv2.scale(this.bv);
  54452. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54453. };
  54454. return PickingInfo;
  54455. }());
  54456. BABYLON.PickingInfo = PickingInfo;
  54457. })(BABYLON || (BABYLON = {}));
  54458. //# sourceMappingURL=babylon.pickingInfo.js.map
  54459. var BABYLON;
  54460. (function (BABYLON) {
  54461. var Ray = /** @class */ (function () {
  54462. function Ray(origin, direction, length) {
  54463. if (length === void 0) { length = Number.MAX_VALUE; }
  54464. this.origin = origin;
  54465. this.direction = direction;
  54466. this.length = length;
  54467. }
  54468. // Methods
  54469. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54470. var d = 0.0;
  54471. var maxValue = Number.MAX_VALUE;
  54472. var inv;
  54473. var min;
  54474. var max;
  54475. var temp;
  54476. if (Math.abs(this.direction.x) < 0.0000001) {
  54477. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54478. return false;
  54479. }
  54480. }
  54481. else {
  54482. inv = 1.0 / this.direction.x;
  54483. min = (minimum.x - this.origin.x) * inv;
  54484. max = (maximum.x - this.origin.x) * inv;
  54485. if (max === -Infinity) {
  54486. max = Infinity;
  54487. }
  54488. if (min > max) {
  54489. temp = min;
  54490. min = max;
  54491. max = temp;
  54492. }
  54493. d = Math.max(min, d);
  54494. maxValue = Math.min(max, maxValue);
  54495. if (d > maxValue) {
  54496. return false;
  54497. }
  54498. }
  54499. if (Math.abs(this.direction.y) < 0.0000001) {
  54500. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54501. return false;
  54502. }
  54503. }
  54504. else {
  54505. inv = 1.0 / this.direction.y;
  54506. min = (minimum.y - this.origin.y) * inv;
  54507. max = (maximum.y - this.origin.y) * inv;
  54508. if (max === -Infinity) {
  54509. max = Infinity;
  54510. }
  54511. if (min > max) {
  54512. temp = min;
  54513. min = max;
  54514. max = temp;
  54515. }
  54516. d = Math.max(min, d);
  54517. maxValue = Math.min(max, maxValue);
  54518. if (d > maxValue) {
  54519. return false;
  54520. }
  54521. }
  54522. if (Math.abs(this.direction.z) < 0.0000001) {
  54523. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54524. return false;
  54525. }
  54526. }
  54527. else {
  54528. inv = 1.0 / this.direction.z;
  54529. min = (minimum.z - this.origin.z) * inv;
  54530. max = (maximum.z - this.origin.z) * inv;
  54531. if (max === -Infinity) {
  54532. max = Infinity;
  54533. }
  54534. if (min > max) {
  54535. temp = min;
  54536. min = max;
  54537. max = temp;
  54538. }
  54539. d = Math.max(min, d);
  54540. maxValue = Math.min(max, maxValue);
  54541. if (d > maxValue) {
  54542. return false;
  54543. }
  54544. }
  54545. return true;
  54546. };
  54547. Ray.prototype.intersectsBox = function (box) {
  54548. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54549. };
  54550. Ray.prototype.intersectsSphere = function (sphere) {
  54551. var x = sphere.center.x - this.origin.x;
  54552. var y = sphere.center.y - this.origin.y;
  54553. var z = sphere.center.z - this.origin.z;
  54554. var pyth = (x * x) + (y * y) + (z * z);
  54555. var rr = sphere.radius * sphere.radius;
  54556. if (pyth <= rr) {
  54557. return true;
  54558. }
  54559. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54560. if (dot < 0.0) {
  54561. return false;
  54562. }
  54563. var temp = pyth - (dot * dot);
  54564. return temp <= rr;
  54565. };
  54566. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54567. if (!this._edge1) {
  54568. this._edge1 = BABYLON.Vector3.Zero();
  54569. this._edge2 = BABYLON.Vector3.Zero();
  54570. this._pvec = BABYLON.Vector3.Zero();
  54571. this._tvec = BABYLON.Vector3.Zero();
  54572. this._qvec = BABYLON.Vector3.Zero();
  54573. }
  54574. vertex1.subtractToRef(vertex0, this._edge1);
  54575. vertex2.subtractToRef(vertex0, this._edge2);
  54576. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54577. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54578. if (det === 0) {
  54579. return null;
  54580. }
  54581. var invdet = 1 / det;
  54582. this.origin.subtractToRef(vertex0, this._tvec);
  54583. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54584. if (bu < 0 || bu > 1.0) {
  54585. return null;
  54586. }
  54587. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54588. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54589. if (bv < 0 || bu + bv > 1.0) {
  54590. return null;
  54591. }
  54592. //check if the distance is longer than the predefined length.
  54593. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54594. if (distance > this.length) {
  54595. return null;
  54596. }
  54597. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54598. };
  54599. Ray.prototype.intersectsPlane = function (plane) {
  54600. var distance;
  54601. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54602. if (Math.abs(result1) < 9.99999997475243E-07) {
  54603. return null;
  54604. }
  54605. else {
  54606. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54607. distance = (-plane.d - result2) / result1;
  54608. if (distance < 0.0) {
  54609. if (distance < -9.99999997475243E-07) {
  54610. return null;
  54611. }
  54612. else {
  54613. return 0;
  54614. }
  54615. }
  54616. return distance;
  54617. }
  54618. };
  54619. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54620. var tm = BABYLON.Tmp.Matrix[0];
  54621. mesh.getWorldMatrix().invertToRef(tm);
  54622. if (this._tmpRay) {
  54623. Ray.TransformToRef(this, tm, this._tmpRay);
  54624. }
  54625. else {
  54626. this._tmpRay = Ray.Transform(this, tm);
  54627. }
  54628. return mesh.intersects(this._tmpRay, fastCheck);
  54629. };
  54630. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54631. if (results) {
  54632. results.length = 0;
  54633. }
  54634. else {
  54635. results = [];
  54636. }
  54637. for (var i = 0; i < meshes.length; i++) {
  54638. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54639. if (pickInfo.hit) {
  54640. results.push(pickInfo);
  54641. }
  54642. }
  54643. results.sort(this._comparePickingInfo);
  54644. return results;
  54645. };
  54646. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54647. if (pickingInfoA.distance < pickingInfoB.distance) {
  54648. return -1;
  54649. }
  54650. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54651. return 1;
  54652. }
  54653. else {
  54654. return 0;
  54655. }
  54656. };
  54657. /**
  54658. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54659. * @param sega the first point of the segment to test the intersection against
  54660. * @param segb the second point of the segment to test the intersection against
  54661. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54662. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54663. */
  54664. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54665. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54666. var u = segb.subtract(sega);
  54667. var v = rsegb.subtract(this.origin);
  54668. var w = sega.subtract(this.origin);
  54669. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54670. var b = BABYLON.Vector3.Dot(u, v);
  54671. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54672. var d = BABYLON.Vector3.Dot(u, w);
  54673. var e = BABYLON.Vector3.Dot(v, w);
  54674. var D = a * c - b * b; // always >= 0
  54675. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54676. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54677. // compute the line parameters of the two closest points
  54678. if (D < Ray.smallnum) { // the lines are almost parallel
  54679. sN = 0.0; // force using point P0 on segment S1
  54680. sD = 1.0; // to prevent possible division by 0.0 later
  54681. tN = e;
  54682. tD = c;
  54683. }
  54684. else { // get the closest points on the infinite lines
  54685. sN = (b * e - c * d);
  54686. tN = (a * e - b * d);
  54687. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54688. sN = 0.0;
  54689. tN = e;
  54690. tD = c;
  54691. }
  54692. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54693. sN = sD;
  54694. tN = e + b;
  54695. tD = c;
  54696. }
  54697. }
  54698. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54699. tN = 0.0;
  54700. // recompute sc for this edge
  54701. if (-d < 0.0) {
  54702. sN = 0.0;
  54703. }
  54704. else if (-d > a)
  54705. sN = sD;
  54706. else {
  54707. sN = -d;
  54708. sD = a;
  54709. }
  54710. }
  54711. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54712. tN = tD;
  54713. // recompute sc for this edge
  54714. if ((-d + b) < 0.0) {
  54715. sN = 0;
  54716. }
  54717. else if ((-d + b) > a) {
  54718. sN = sD;
  54719. }
  54720. else {
  54721. sN = (-d + b);
  54722. sD = a;
  54723. }
  54724. }
  54725. // finally do the division to get sc and tc
  54726. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54727. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54728. // get the difference of the two closest points
  54729. var qtc = v.multiplyByFloats(tc, tc, tc);
  54730. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54731. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54732. if (isIntersected) {
  54733. return qtc.length();
  54734. }
  54735. return -1;
  54736. };
  54737. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54738. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54739. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54740. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54741. this.direction.normalize();
  54742. return this;
  54743. };
  54744. // Statics
  54745. Ray.Zero = function () {
  54746. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54747. };
  54748. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54749. var result = Ray.Zero();
  54750. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54751. };
  54752. /**
  54753. * 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
  54754. * transformed to the given world matrix.
  54755. * @param origin The origin point
  54756. * @param end The end point
  54757. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54758. */
  54759. Ray.CreateNewFromTo = function (origin, end, world) {
  54760. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54761. var direction = end.subtract(origin);
  54762. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54763. direction.normalize();
  54764. return Ray.Transform(new Ray(origin, direction, length), world);
  54765. };
  54766. Ray.Transform = function (ray, matrix) {
  54767. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54768. Ray.TransformToRef(ray, matrix, result);
  54769. return result;
  54770. };
  54771. Ray.TransformToRef = function (ray, matrix, result) {
  54772. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54773. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54774. result.length = ray.length;
  54775. var dir = result.direction;
  54776. var len = dir.length();
  54777. if (!(len === 0 || len === 1)) {
  54778. var num = 1.0 / len;
  54779. dir.x *= num;
  54780. dir.y *= num;
  54781. dir.z *= num;
  54782. result.length *= len;
  54783. }
  54784. };
  54785. Ray.smallnum = 0.00000001;
  54786. Ray.rayl = 10e8;
  54787. return Ray;
  54788. }());
  54789. BABYLON.Ray = Ray;
  54790. })(BABYLON || (BABYLON = {}));
  54791. //# sourceMappingURL=babylon.ray.js.map
  54792. var BABYLON;
  54793. (function (BABYLON) {
  54794. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54795. if (boxMin.x > sphereCenter.x + sphereRadius)
  54796. return false;
  54797. if (sphereCenter.x - sphereRadius > boxMax.x)
  54798. return false;
  54799. if (boxMin.y > sphereCenter.y + sphereRadius)
  54800. return false;
  54801. if (sphereCenter.y - sphereRadius > boxMax.y)
  54802. return false;
  54803. if (boxMin.z > sphereCenter.z + sphereRadius)
  54804. return false;
  54805. if (sphereCenter.z - sphereRadius > boxMax.z)
  54806. return false;
  54807. return true;
  54808. };
  54809. var getLowestRoot = (function () {
  54810. var result = { root: 0, found: false };
  54811. return function (a, b, c, maxR) {
  54812. result.root = 0;
  54813. result.found = false;
  54814. var determinant = b * b - 4.0 * a * c;
  54815. if (determinant < 0)
  54816. return result;
  54817. var sqrtD = Math.sqrt(determinant);
  54818. var r1 = (-b - sqrtD) / (2.0 * a);
  54819. var r2 = (-b + sqrtD) / (2.0 * a);
  54820. if (r1 > r2) {
  54821. var temp = r2;
  54822. r2 = r1;
  54823. r1 = temp;
  54824. }
  54825. if (r1 > 0 && r1 < maxR) {
  54826. result.root = r1;
  54827. result.found = true;
  54828. return result;
  54829. }
  54830. if (r2 > 0 && r2 < maxR) {
  54831. result.root = r2;
  54832. result.found = true;
  54833. return result;
  54834. }
  54835. return result;
  54836. };
  54837. })();
  54838. var Collider = /** @class */ (function () {
  54839. function Collider() {
  54840. this._collisionPoint = BABYLON.Vector3.Zero();
  54841. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54842. this._tempVector = BABYLON.Vector3.Zero();
  54843. this._tempVector2 = BABYLON.Vector3.Zero();
  54844. this._tempVector3 = BABYLON.Vector3.Zero();
  54845. this._tempVector4 = BABYLON.Vector3.Zero();
  54846. this._edge = BABYLON.Vector3.Zero();
  54847. this._baseToVertex = BABYLON.Vector3.Zero();
  54848. this._destinationPoint = BABYLON.Vector3.Zero();
  54849. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54850. this._displacementVector = BABYLON.Vector3.Zero();
  54851. this._radius = BABYLON.Vector3.One();
  54852. this._retry = 0;
  54853. this._basePointWorld = BABYLON.Vector3.Zero();
  54854. this._velocityWorld = BABYLON.Vector3.Zero();
  54855. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54856. this._collisionMask = -1;
  54857. }
  54858. Object.defineProperty(Collider.prototype, "collisionMask", {
  54859. get: function () {
  54860. return this._collisionMask;
  54861. },
  54862. set: function (mask) {
  54863. this._collisionMask = !isNaN(mask) ? mask : -1;
  54864. },
  54865. enumerable: true,
  54866. configurable: true
  54867. });
  54868. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54869. /**
  54870. * Gets the plane normal used to compute the sliding response (in local space)
  54871. */
  54872. get: function () {
  54873. return this._slidePlaneNormal;
  54874. },
  54875. enumerable: true,
  54876. configurable: true
  54877. });
  54878. // Methods
  54879. Collider.prototype._initialize = function (source, dir, e) {
  54880. this._velocity = dir;
  54881. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54882. this._basePoint = source;
  54883. source.multiplyToRef(this._radius, this._basePointWorld);
  54884. dir.multiplyToRef(this._radius, this._velocityWorld);
  54885. this._velocityWorldLength = this._velocityWorld.length();
  54886. this._epsilon = e;
  54887. this.collisionFound = false;
  54888. };
  54889. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54890. pa.subtractToRef(point, this._tempVector);
  54891. pb.subtractToRef(point, this._tempVector2);
  54892. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54893. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54894. if (d < 0)
  54895. return false;
  54896. pc.subtractToRef(point, this._tempVector3);
  54897. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54898. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54899. if (d < 0)
  54900. return false;
  54901. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54902. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54903. return d >= 0;
  54904. };
  54905. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54906. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54907. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54908. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54909. return false;
  54910. }
  54911. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54912. return false;
  54913. return true;
  54914. };
  54915. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54916. var t0;
  54917. var embeddedInPlane = false;
  54918. //defensive programming, actually not needed.
  54919. if (!trianglePlaneArray) {
  54920. trianglePlaneArray = [];
  54921. }
  54922. if (!trianglePlaneArray[faceIndex]) {
  54923. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54924. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54925. }
  54926. var trianglePlane = trianglePlaneArray[faceIndex];
  54927. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54928. return;
  54929. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54930. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54931. if (normalDotVelocity == 0) {
  54932. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54933. return;
  54934. embeddedInPlane = true;
  54935. t0 = 0;
  54936. }
  54937. else {
  54938. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54939. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54940. if (t0 > t1) {
  54941. var temp = t1;
  54942. t1 = t0;
  54943. t0 = temp;
  54944. }
  54945. if (t0 > 1.0 || t1 < 0.0)
  54946. return;
  54947. if (t0 < 0)
  54948. t0 = 0;
  54949. if (t0 > 1.0)
  54950. t0 = 1.0;
  54951. }
  54952. this._collisionPoint.copyFromFloats(0, 0, 0);
  54953. var found = false;
  54954. var t = 1.0;
  54955. if (!embeddedInPlane) {
  54956. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54957. this._velocity.scaleToRef(t0, this._tempVector);
  54958. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54959. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54960. found = true;
  54961. t = t0;
  54962. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54963. }
  54964. }
  54965. if (!found) {
  54966. var velocitySquaredLength = this._velocity.lengthSquared();
  54967. var a = velocitySquaredLength;
  54968. this._basePoint.subtractToRef(p1, this._tempVector);
  54969. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54970. var c = this._tempVector.lengthSquared() - 1.0;
  54971. var lowestRoot = getLowestRoot(a, b, c, t);
  54972. if (lowestRoot.found) {
  54973. t = lowestRoot.root;
  54974. found = true;
  54975. this._collisionPoint.copyFrom(p1);
  54976. }
  54977. this._basePoint.subtractToRef(p2, this._tempVector);
  54978. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54979. c = this._tempVector.lengthSquared() - 1.0;
  54980. lowestRoot = getLowestRoot(a, b, c, t);
  54981. if (lowestRoot.found) {
  54982. t = lowestRoot.root;
  54983. found = true;
  54984. this._collisionPoint.copyFrom(p2);
  54985. }
  54986. this._basePoint.subtractToRef(p3, this._tempVector);
  54987. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54988. c = this._tempVector.lengthSquared() - 1.0;
  54989. lowestRoot = getLowestRoot(a, b, c, t);
  54990. if (lowestRoot.found) {
  54991. t = lowestRoot.root;
  54992. found = true;
  54993. this._collisionPoint.copyFrom(p3);
  54994. }
  54995. p2.subtractToRef(p1, this._edge);
  54996. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54997. var edgeSquaredLength = this._edge.lengthSquared();
  54998. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54999. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55000. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55001. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55002. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55003. lowestRoot = getLowestRoot(a, b, c, t);
  55004. if (lowestRoot.found) {
  55005. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55006. if (f >= 0.0 && f <= 1.0) {
  55007. t = lowestRoot.root;
  55008. found = true;
  55009. this._edge.scaleInPlace(f);
  55010. p1.addToRef(this._edge, this._collisionPoint);
  55011. }
  55012. }
  55013. p3.subtractToRef(p2, this._edge);
  55014. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55015. edgeSquaredLength = this._edge.lengthSquared();
  55016. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55017. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55018. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55019. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55020. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55021. lowestRoot = getLowestRoot(a, b, c, t);
  55022. if (lowestRoot.found) {
  55023. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55024. if (f >= 0.0 && f <= 1.0) {
  55025. t = lowestRoot.root;
  55026. found = true;
  55027. this._edge.scaleInPlace(f);
  55028. p2.addToRef(this._edge, this._collisionPoint);
  55029. }
  55030. }
  55031. p1.subtractToRef(p3, this._edge);
  55032. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55033. edgeSquaredLength = this._edge.lengthSquared();
  55034. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55035. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55036. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55037. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55038. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55039. lowestRoot = getLowestRoot(a, b, c, t);
  55040. if (lowestRoot.found) {
  55041. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55042. if (f >= 0.0 && f <= 1.0) {
  55043. t = lowestRoot.root;
  55044. found = true;
  55045. this._edge.scaleInPlace(f);
  55046. p3.addToRef(this._edge, this._collisionPoint);
  55047. }
  55048. }
  55049. }
  55050. if (found) {
  55051. var distToCollision = t * this._velocity.length();
  55052. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55053. if (!this.intersectionPoint) {
  55054. this.intersectionPoint = this._collisionPoint.clone();
  55055. }
  55056. else {
  55057. this.intersectionPoint.copyFrom(this._collisionPoint);
  55058. }
  55059. this._nearestDistance = distToCollision;
  55060. this.collisionFound = true;
  55061. }
  55062. }
  55063. };
  55064. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55065. for (var i = indexStart; i < indexEnd; i += 3) {
  55066. var p1 = pts[indices[i] - decal];
  55067. var p2 = pts[indices[i + 1] - decal];
  55068. var p3 = pts[indices[i + 2] - decal];
  55069. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55070. }
  55071. };
  55072. Collider.prototype._getResponse = function (pos, vel) {
  55073. pos.addToRef(vel, this._destinationPoint);
  55074. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55075. this._basePoint.addToRef(vel, pos);
  55076. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55077. this._slidePlaneNormal.normalize();
  55078. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55079. pos.addInPlace(this._displacementVector);
  55080. this.intersectionPoint.addInPlace(this._displacementVector);
  55081. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55082. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55083. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55084. };
  55085. return Collider;
  55086. }());
  55087. BABYLON.Collider = Collider;
  55088. })(BABYLON || (BABYLON = {}));
  55089. //# sourceMappingURL=babylon.collider.js.map
  55090. var BABYLON;
  55091. (function (BABYLON) {
  55092. //WebWorker code will be inserted to this variable.
  55093. BABYLON.CollisionWorker = "";
  55094. /** Defines supported task for worker process */
  55095. var WorkerTaskType;
  55096. (function (WorkerTaskType) {
  55097. /** Initialization */
  55098. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55099. /** Update of geometry */
  55100. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55101. /** Evaluate collision */
  55102. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55103. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55104. /** Defines kind of replies returned by worker */
  55105. var WorkerReplyType;
  55106. (function (WorkerReplyType) {
  55107. /** Success */
  55108. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55109. /** Unkown error */
  55110. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55111. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55112. var CollisionCoordinatorWorker = /** @class */ (function () {
  55113. function CollisionCoordinatorWorker() {
  55114. var _this = this;
  55115. this._scaledPosition = BABYLON.Vector3.Zero();
  55116. this._scaledVelocity = BABYLON.Vector3.Zero();
  55117. this.onMeshUpdated = function (transformNode) {
  55118. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55119. };
  55120. this.onGeometryUpdated = function (geometry) {
  55121. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55122. };
  55123. this._afterRender = function () {
  55124. if (!_this._init)
  55125. return;
  55126. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55127. return;
  55128. }
  55129. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55130. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55131. if (_this._runningUpdated > 4) {
  55132. return;
  55133. }
  55134. ++_this._runningUpdated;
  55135. var payload = {
  55136. updatedMeshes: _this._addUpdateMeshesList,
  55137. updatedGeometries: _this._addUpdateGeometriesList,
  55138. removedGeometries: _this._toRemoveGeometryArray,
  55139. removedMeshes: _this._toRemoveMeshesArray
  55140. };
  55141. var message = {
  55142. payload: payload,
  55143. taskType: WorkerTaskType.UPDATE
  55144. };
  55145. var serializable = [];
  55146. for (var id in payload.updatedGeometries) {
  55147. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55148. //prepare transferables
  55149. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55150. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55151. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55152. }
  55153. }
  55154. _this._worker.postMessage(message, serializable);
  55155. _this._addUpdateMeshesList = {};
  55156. _this._addUpdateGeometriesList = {};
  55157. _this._toRemoveGeometryArray = [];
  55158. _this._toRemoveMeshesArray = [];
  55159. };
  55160. this._onMessageFromWorker = function (e) {
  55161. var returnData = e.data;
  55162. if (returnData.error != WorkerReplyType.SUCCESS) {
  55163. //TODO what errors can be returned from the worker?
  55164. BABYLON.Tools.Warn("error returned from worker!");
  55165. return;
  55166. }
  55167. switch (returnData.taskType) {
  55168. case WorkerTaskType.INIT:
  55169. _this._init = true;
  55170. //Update the worked with ALL of the scene's current state
  55171. _this._scene.meshes.forEach(function (mesh) {
  55172. _this.onMeshAdded(mesh);
  55173. });
  55174. _this._scene.getGeometries().forEach(function (geometry) {
  55175. _this.onGeometryAdded(geometry);
  55176. });
  55177. break;
  55178. case WorkerTaskType.UPDATE:
  55179. _this._runningUpdated--;
  55180. break;
  55181. case WorkerTaskType.COLLIDE:
  55182. var returnPayload = returnData.payload;
  55183. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55184. return;
  55185. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55186. if (callback) {
  55187. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55188. if (mesh) {
  55189. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55190. }
  55191. }
  55192. //cleanup
  55193. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55194. break;
  55195. }
  55196. };
  55197. this._collisionsCallbackArray = [];
  55198. this._init = false;
  55199. this._runningUpdated = 0;
  55200. this._addUpdateMeshesList = {};
  55201. this._addUpdateGeometriesList = {};
  55202. this._toRemoveGeometryArray = [];
  55203. this._toRemoveMeshesArray = [];
  55204. }
  55205. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55206. if (!this._init)
  55207. return;
  55208. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55209. return;
  55210. position.divideToRef(collider._radius, this._scaledPosition);
  55211. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55212. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55213. var payload = {
  55214. collider: {
  55215. position: this._scaledPosition.asArray(),
  55216. velocity: this._scaledVelocity.asArray(),
  55217. radius: collider._radius.asArray()
  55218. },
  55219. collisionId: collisionIndex,
  55220. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55221. maximumRetry: maximumRetry
  55222. };
  55223. var message = {
  55224. payload: payload,
  55225. taskType: WorkerTaskType.COLLIDE
  55226. };
  55227. this._worker.postMessage(message);
  55228. };
  55229. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55230. this._scene = scene;
  55231. this._scene.registerAfterRender(this._afterRender);
  55232. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55233. this._worker = new Worker(workerUrl);
  55234. this._worker.onmessage = this._onMessageFromWorker;
  55235. var message = {
  55236. payload: {},
  55237. taskType: WorkerTaskType.INIT
  55238. };
  55239. this._worker.postMessage(message);
  55240. };
  55241. CollisionCoordinatorWorker.prototype.destroy = function () {
  55242. this._scene.unregisterAfterRender(this._afterRender);
  55243. this._worker.terminate();
  55244. };
  55245. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55246. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55247. this.onMeshUpdated(mesh);
  55248. };
  55249. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55250. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55251. };
  55252. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55253. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55254. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55255. this.onGeometryUpdated(geometry);
  55256. };
  55257. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55258. this._toRemoveGeometryArray.push(geometry.id);
  55259. };
  55260. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55261. var submeshes = [];
  55262. if (mesh.subMeshes) {
  55263. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55264. var boundingInfo = sm.getBoundingInfo();
  55265. return {
  55266. position: idx,
  55267. verticesStart: sm.verticesStart,
  55268. verticesCount: sm.verticesCount,
  55269. indexStart: sm.indexStart,
  55270. indexCount: sm.indexCount,
  55271. hasMaterial: !!sm.getMaterial(),
  55272. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55273. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55274. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55275. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55276. };
  55277. });
  55278. }
  55279. var geometryId = null;
  55280. if (mesh instanceof BABYLON.Mesh) {
  55281. var geometry = mesh.geometry;
  55282. geometryId = geometry ? geometry.id : null;
  55283. }
  55284. else if (mesh instanceof BABYLON.InstancedMesh) {
  55285. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55286. geometryId = geometry ? geometry.id : null;
  55287. }
  55288. var boundingInfo = mesh.getBoundingInfo();
  55289. return {
  55290. uniqueId: mesh.uniqueId,
  55291. id: mesh.id,
  55292. name: mesh.name,
  55293. geometryId: geometryId,
  55294. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55295. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55296. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55297. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55298. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55299. subMeshes: submeshes,
  55300. checkCollisions: mesh.checkCollisions
  55301. };
  55302. };
  55303. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55304. return {
  55305. id: geometry.id,
  55306. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55307. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55308. indices: new Uint32Array(geometry.getIndices() || []),
  55309. };
  55310. };
  55311. return CollisionCoordinatorWorker;
  55312. }());
  55313. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55314. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55315. function CollisionCoordinatorLegacy() {
  55316. this._scaledPosition = BABYLON.Vector3.Zero();
  55317. this._scaledVelocity = BABYLON.Vector3.Zero();
  55318. this._finalPosition = BABYLON.Vector3.Zero();
  55319. }
  55320. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55321. position.divideToRef(collider._radius, this._scaledPosition);
  55322. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55323. collider.collidedMesh = null;
  55324. collider._retry = 0;
  55325. collider._initialVelocity = this._scaledVelocity;
  55326. collider._initialPosition = this._scaledPosition;
  55327. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55328. this._finalPosition.multiplyInPlace(collider._radius);
  55329. //run the callback
  55330. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55331. };
  55332. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55333. this._scene = scene;
  55334. };
  55335. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55336. //Legacy need no destruction method.
  55337. };
  55338. //No update in legacy mode
  55339. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55340. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55341. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55342. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55343. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55344. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55345. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55346. if (excludedMesh === void 0) { excludedMesh = null; }
  55347. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55348. if (collider._retry >= maximumRetry) {
  55349. finalPosition.copyFrom(position);
  55350. return;
  55351. }
  55352. // Check if this is a mesh else camera or -1
  55353. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55354. collider._initialize(position, velocity, closeDistance);
  55355. // Check all meshes
  55356. for (var index = 0; index < this._scene.meshes.length; index++) {
  55357. var mesh = this._scene.meshes[index];
  55358. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55359. mesh._checkCollision(collider);
  55360. }
  55361. }
  55362. if (!collider.collisionFound) {
  55363. position.addToRef(velocity, finalPosition);
  55364. return;
  55365. }
  55366. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55367. collider._getResponse(position, velocity);
  55368. }
  55369. if (velocity.length() <= closeDistance) {
  55370. finalPosition.copyFrom(position);
  55371. return;
  55372. }
  55373. collider._retry++;
  55374. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55375. };
  55376. return CollisionCoordinatorLegacy;
  55377. }());
  55378. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55379. })(BABYLON || (BABYLON = {}));
  55380. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55381. var BABYLON;
  55382. (function (BABYLON) {
  55383. /**
  55384. * A particle represents one of the element emitted by a particle system.
  55385. * This is mainly define by its coordinates, direction, velocity and age.
  55386. */
  55387. var Particle = /** @class */ (function () {
  55388. /**
  55389. * Creates a new instance Particle
  55390. * @param particleSystem the particle system the particle belongs to
  55391. */
  55392. function Particle(
  55393. /**
  55394. * particleSystem the particle system the particle belongs to.
  55395. */
  55396. particleSystem) {
  55397. this.particleSystem = particleSystem;
  55398. /**
  55399. * The world position of the particle in the scene.
  55400. */
  55401. this.position = BABYLON.Vector3.Zero();
  55402. /**
  55403. * The world direction of the particle in the scene.
  55404. */
  55405. this.direction = BABYLON.Vector3.Zero();
  55406. /**
  55407. * The color of the particle.
  55408. */
  55409. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55410. /**
  55411. * The color change of the particle per step.
  55412. */
  55413. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55414. /**
  55415. * Defines how long will the life of the particle be.
  55416. */
  55417. this.lifeTime = 1.0;
  55418. /**
  55419. * The current age of the particle.
  55420. */
  55421. this.age = 0;
  55422. /**
  55423. * The current size of the particle.
  55424. */
  55425. this.size = 0;
  55426. /**
  55427. * The current angle of the particle.
  55428. */
  55429. this.angle = 0;
  55430. /**
  55431. * Defines how fast is the angle changing.
  55432. */
  55433. this.angularSpeed = 0;
  55434. /**
  55435. * Defines the cell index used by the particle to be rendered from a sprite.
  55436. */
  55437. this.cellIndex = 0;
  55438. this._currentFrameCounter = 0;
  55439. if (!this.particleSystem.isAnimationSheetEnabled) {
  55440. return;
  55441. }
  55442. this.updateCellInfoFromSystem();
  55443. }
  55444. Particle.prototype.updateCellInfoFromSystem = function () {
  55445. this.cellIndex = this.particleSystem.startSpriteCellID;
  55446. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55447. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55448. }
  55449. else {
  55450. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55451. }
  55452. };
  55453. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55454. // (ageOffset / scaledUpdateSpeed) / available cells
  55455. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55456. this._currentFrameCounter += scaledUpdateSpeed;
  55457. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55458. this._currentFrameCounter = 0;
  55459. this.cellIndex++;
  55460. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55461. this.cellIndex = this.particleSystem.endSpriteCellID;
  55462. }
  55463. }
  55464. };
  55465. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55466. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55467. this.cellIndex++;
  55468. this._currentFrameCounter = 0;
  55469. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55470. if (this.particleSystem.spriteCellLoop) {
  55471. this.cellIndex = this.particleSystem.startSpriteCellID;
  55472. }
  55473. else {
  55474. this.cellIndex = this.particleSystem.endSpriteCellID;
  55475. }
  55476. }
  55477. }
  55478. else {
  55479. this._currentFrameCounter++;
  55480. }
  55481. };
  55482. /**
  55483. * Copy the properties of particle to another one.
  55484. * @param other the particle to copy the information to.
  55485. */
  55486. Particle.prototype.copyTo = function (other) {
  55487. other.position.copyFrom(this.position);
  55488. other.direction.copyFrom(this.direction);
  55489. other.color.copyFrom(this.color);
  55490. other.colorStep.copyFrom(this.colorStep);
  55491. other.lifeTime = this.lifeTime;
  55492. other.age = this.age;
  55493. other.size = this.size;
  55494. other.angle = this.angle;
  55495. other.angularSpeed = this.angularSpeed;
  55496. other.particleSystem = this.particleSystem;
  55497. other.cellIndex = this.cellIndex;
  55498. };
  55499. return Particle;
  55500. }());
  55501. BABYLON.Particle = Particle;
  55502. })(BABYLON || (BABYLON = {}));
  55503. //# sourceMappingURL=babylon.particle.js.map
  55504. var BABYLON;
  55505. (function (BABYLON) {
  55506. /**
  55507. * This represents a particle system in Babylon.
  55508. * 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.
  55509. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55510. * @example https://doc.babylonjs.com/babylon101/particles
  55511. */
  55512. var ParticleSystem = /** @class */ (function () {
  55513. /**
  55514. * Instantiates a particle system.
  55515. * 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.
  55516. * @param name The name of the particle system
  55517. * @param capacity The max number of particles alive at the same time
  55518. * @param scene The scene the particle system belongs to
  55519. * @param customEffect a custom effect used to change the way particles are rendered by default
  55520. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55521. * @param epsilon Offset used to render the particles
  55522. */
  55523. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55524. if (customEffect === void 0) { customEffect = null; }
  55525. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55526. if (epsilon === void 0) { epsilon = 0.01; }
  55527. var _this = this;
  55528. /**
  55529. * List of animations used by the particle system.
  55530. */
  55531. this.animations = [];
  55532. /**
  55533. * The rendering group used by the Particle system to chose when to render.
  55534. */
  55535. this.renderingGroupId = 0;
  55536. /**
  55537. * The emitter represents the Mesh or position we are attaching the particle system to.
  55538. */
  55539. this.emitter = null;
  55540. /**
  55541. * The maximum number of particles to emit per frame
  55542. */
  55543. this.emitRate = 10;
  55544. /**
  55545. * If you want to launch only a few particles at once, that can be done, as well.
  55546. */
  55547. this.manualEmitCount = -1;
  55548. /**
  55549. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55550. */
  55551. this.updateSpeed = 0.01;
  55552. /**
  55553. * The amount of time the particle system is running (depends of the overall update speed).
  55554. */
  55555. this.targetStopDuration = 0;
  55556. /**
  55557. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55558. */
  55559. this.disposeOnStop = false;
  55560. /**
  55561. * Minimum power of emitting particles.
  55562. */
  55563. this.minEmitPower = 1;
  55564. /**
  55565. * Maximum power of emitting particles.
  55566. */
  55567. this.maxEmitPower = 1;
  55568. /**
  55569. * Minimum life time of emitting particles.
  55570. */
  55571. this.minLifeTime = 1;
  55572. /**
  55573. * Maximum life time of emitting particles.
  55574. */
  55575. this.maxLifeTime = 1;
  55576. /**
  55577. * Minimum Size of emitting particles.
  55578. */
  55579. this.minSize = 1;
  55580. /**
  55581. * Maximum Size of emitting particles.
  55582. */
  55583. this.maxSize = 1;
  55584. /**
  55585. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55586. */
  55587. this.minAngularSpeed = 0;
  55588. /**
  55589. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55590. */
  55591. this.maxAngularSpeed = 0;
  55592. /**
  55593. * The layer mask we are rendering the particles through.
  55594. */
  55595. this.layerMask = 0x0FFFFFFF;
  55596. /**
  55597. * This can help using your own shader to render the particle system.
  55598. * The according effect will be created
  55599. */
  55600. this.customShader = null;
  55601. /**
  55602. * By default particle system starts as soon as they are created. This prevents the
  55603. * automatic start to happen and let you decide when to start emitting particles.
  55604. */
  55605. this.preventAutoStart = false;
  55606. /**
  55607. * Callback triggered when the particle animation is ending.
  55608. */
  55609. this.onAnimationEnd = null;
  55610. /**
  55611. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55612. */
  55613. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55614. /**
  55615. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55616. * to override the particles.
  55617. */
  55618. this.forceDepthWrite = false;
  55619. /**
  55620. * You can use gravity if you want to give an orientation to your particles.
  55621. */
  55622. this.gravity = BABYLON.Vector3.Zero();
  55623. /**
  55624. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55625. */
  55626. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55627. /**
  55628. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55629. */
  55630. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55631. /**
  55632. * Color the particle will have at the end of its lifetime.
  55633. */
  55634. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55635. /**
  55636. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55637. */
  55638. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55639. /**
  55640. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55641. */
  55642. this.spriteCellLoop = true;
  55643. /**
  55644. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55645. */
  55646. this.spriteCellChangeSpeed = 0;
  55647. /**
  55648. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55649. */
  55650. this.startSpriteCellID = 0;
  55651. /**
  55652. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55653. */
  55654. this.endSpriteCellID = 0;
  55655. /**
  55656. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55657. */
  55658. this.spriteCellWidth = 0;
  55659. /**
  55660. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55661. */
  55662. this.spriteCellHeight = 0;
  55663. /**
  55664. * An event triggered when the system is disposed.
  55665. */
  55666. this.onDisposeObservable = new BABYLON.Observable();
  55667. this._particles = new Array();
  55668. this._stockParticles = new Array();
  55669. this._newPartsExcess = 0;
  55670. this._vertexBuffers = {};
  55671. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55672. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55673. this._scaledDirection = BABYLON.Vector3.Zero();
  55674. this._scaledGravity = BABYLON.Vector3.Zero();
  55675. this._currentRenderId = -1;
  55676. this._started = false;
  55677. this._stopped = false;
  55678. this._actualFrame = 0;
  55679. this._vertexBufferSize = 11;
  55680. // start of sub system methods
  55681. /**
  55682. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55683. * Its lifetime will start back at 0.
  55684. */
  55685. this.recycleParticle = function (particle) {
  55686. var lastParticle = _this._particles.pop();
  55687. if (lastParticle !== particle) {
  55688. lastParticle.copyTo(particle);
  55689. }
  55690. _this._stockParticles.push(lastParticle);
  55691. };
  55692. this._createParticle = function () {
  55693. var particle;
  55694. if (_this._stockParticles.length !== 0) {
  55695. particle = _this._stockParticles.pop();
  55696. particle.age = 0;
  55697. particle.cellIndex = _this.startSpriteCellID;
  55698. }
  55699. else {
  55700. particle = new BABYLON.Particle(_this);
  55701. }
  55702. return particle;
  55703. };
  55704. this._emitFromParticle = function (particle) {
  55705. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55706. return;
  55707. }
  55708. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55709. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55710. subSystem._rootParticleSystem = _this;
  55711. _this.activeSubSystems.push(subSystem);
  55712. subSystem.start();
  55713. };
  55714. this._appendParticleVertexes = null;
  55715. this.id = name;
  55716. this.name = name;
  55717. this._capacity = capacity;
  55718. this._epsilon = epsilon;
  55719. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55720. if (isAnimationSheetEnabled) {
  55721. this._vertexBufferSize = 12;
  55722. }
  55723. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55724. this._customEffect = customEffect;
  55725. scene.particleSystems.push(this);
  55726. this._createIndexBuffer();
  55727. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55728. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55729. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55730. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55731. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55732. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55733. if (this._isAnimationSheetEnabled) {
  55734. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55735. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55736. }
  55737. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55738. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55739. this._vertexBuffers["options"] = options;
  55740. // Default emitter type
  55741. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55742. this.updateFunction = function (particles) {
  55743. for (var index = 0; index < particles.length; index++) {
  55744. var particle = particles[index];
  55745. particle.age += _this._scaledUpdateSpeed;
  55746. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55747. _this._emitFromParticle(particle);
  55748. _this.recycleParticle(particle);
  55749. index--;
  55750. continue;
  55751. }
  55752. else {
  55753. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55754. particle.color.addInPlace(_this._scaledColorStep);
  55755. if (particle.color.a < 0)
  55756. particle.color.a = 0;
  55757. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55758. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55759. particle.position.addInPlace(_this._scaledDirection);
  55760. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55761. particle.direction.addInPlace(_this._scaledGravity);
  55762. if (_this._isAnimationSheetEnabled) {
  55763. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55764. }
  55765. }
  55766. }
  55767. };
  55768. }
  55769. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55770. /**
  55771. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55772. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55773. */
  55774. get: function () {
  55775. if (this.particleEmitterType.direction1) {
  55776. return this.particleEmitterType.direction1;
  55777. }
  55778. return BABYLON.Vector3.Zero();
  55779. },
  55780. set: function (value) {
  55781. if (this.particleEmitterType.direction1) {
  55782. this.particleEmitterType.direction1 = value;
  55783. }
  55784. },
  55785. enumerable: true,
  55786. configurable: true
  55787. });
  55788. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55789. /**
  55790. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55791. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55792. */
  55793. get: function () {
  55794. if (this.particleEmitterType.direction2) {
  55795. return this.particleEmitterType.direction2;
  55796. }
  55797. return BABYLON.Vector3.Zero();
  55798. },
  55799. set: function (value) {
  55800. if (this.particleEmitterType.direction2) {
  55801. this.particleEmitterType.direction2 = value;
  55802. }
  55803. },
  55804. enumerable: true,
  55805. configurable: true
  55806. });
  55807. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55808. /**
  55809. * 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.
  55810. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55811. */
  55812. get: function () {
  55813. if (this.particleEmitterType.minEmitBox) {
  55814. return this.particleEmitterType.minEmitBox;
  55815. }
  55816. return BABYLON.Vector3.Zero();
  55817. },
  55818. set: function (value) {
  55819. if (this.particleEmitterType.minEmitBox) {
  55820. this.particleEmitterType.minEmitBox = value;
  55821. }
  55822. },
  55823. enumerable: true,
  55824. configurable: true
  55825. });
  55826. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55827. /**
  55828. * 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.
  55829. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55830. */
  55831. get: function () {
  55832. if (this.particleEmitterType.maxEmitBox) {
  55833. return this.particleEmitterType.maxEmitBox;
  55834. }
  55835. return BABYLON.Vector3.Zero();
  55836. },
  55837. set: function (value) {
  55838. if (this.particleEmitterType.maxEmitBox) {
  55839. this.particleEmitterType.maxEmitBox = value;
  55840. }
  55841. },
  55842. enumerable: true,
  55843. configurable: true
  55844. });
  55845. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55846. /**
  55847. * Sets a callback that will be triggered when the system is disposed.
  55848. */
  55849. set: function (callback) {
  55850. if (this._onDisposeObserver) {
  55851. this.onDisposeObservable.remove(this._onDisposeObserver);
  55852. }
  55853. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55854. },
  55855. enumerable: true,
  55856. configurable: true
  55857. });
  55858. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55859. /**
  55860. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55861. */
  55862. get: function () {
  55863. return this._isAnimationSheetEnabled;
  55864. },
  55865. enumerable: true,
  55866. configurable: true
  55867. });
  55868. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55869. //end of Sub-emitter
  55870. /**
  55871. * Gets the current list of active particles
  55872. */
  55873. get: function () {
  55874. return this._particles;
  55875. },
  55876. enumerable: true,
  55877. configurable: true
  55878. });
  55879. /**
  55880. * Returns the string "ParticleSystem"
  55881. * @returns a string containing the class name
  55882. */
  55883. ParticleSystem.prototype.getClassName = function () {
  55884. return "ParticleSystem";
  55885. };
  55886. ParticleSystem.prototype._createIndexBuffer = function () {
  55887. var indices = [];
  55888. var index = 0;
  55889. for (var count = 0; count < this._capacity; count++) {
  55890. indices.push(index);
  55891. indices.push(index + 1);
  55892. indices.push(index + 2);
  55893. indices.push(index);
  55894. indices.push(index + 2);
  55895. indices.push(index + 3);
  55896. index += 4;
  55897. }
  55898. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55899. };
  55900. /**
  55901. * Gets the maximum number of particles active at the same time.
  55902. * @returns The max number of active particles.
  55903. */
  55904. ParticleSystem.prototype.getCapacity = function () {
  55905. return this._capacity;
  55906. };
  55907. /**
  55908. * Gets Wether there are still active particles in the system.
  55909. * @returns True if it is alive, otherwise false.
  55910. */
  55911. ParticleSystem.prototype.isAlive = function () {
  55912. return this._alive;
  55913. };
  55914. /**
  55915. * Gets Wether the system has been started.
  55916. * @returns True if it has been started, otherwise false.
  55917. */
  55918. ParticleSystem.prototype.isStarted = function () {
  55919. return this._started;
  55920. };
  55921. /**
  55922. * Starts the particle system and begins to emit.
  55923. */
  55924. ParticleSystem.prototype.start = function () {
  55925. this._started = true;
  55926. this._stopped = false;
  55927. this._actualFrame = 0;
  55928. if (this.subEmitters && this.subEmitters.length != 0) {
  55929. this.activeSubSystems = new Array();
  55930. }
  55931. };
  55932. /**
  55933. * Stops the particle system.
  55934. * @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.
  55935. */
  55936. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55937. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55938. this._stopped = true;
  55939. if (stopSubEmitters) {
  55940. this._stopSubEmitters();
  55941. }
  55942. };
  55943. // animation sheet
  55944. /**
  55945. * Remove all active particles
  55946. */
  55947. ParticleSystem.prototype.reset = function () {
  55948. this._stockParticles = [];
  55949. this._particles = [];
  55950. };
  55951. /**
  55952. * @hidden (for internal use only)
  55953. */
  55954. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55955. var offset = index * this._vertexBufferSize;
  55956. this._vertexData[offset] = particle.position.x;
  55957. this._vertexData[offset + 1] = particle.position.y;
  55958. this._vertexData[offset + 2] = particle.position.z;
  55959. this._vertexData[offset + 3] = particle.color.r;
  55960. this._vertexData[offset + 4] = particle.color.g;
  55961. this._vertexData[offset + 5] = particle.color.b;
  55962. this._vertexData[offset + 6] = particle.color.a;
  55963. this._vertexData[offset + 7] = particle.angle;
  55964. this._vertexData[offset + 8] = particle.size;
  55965. this._vertexData[offset + 9] = offsetX;
  55966. this._vertexData[offset + 10] = offsetY;
  55967. };
  55968. /**
  55969. * @hidden (for internal use only)
  55970. */
  55971. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55972. if (offsetX === 0)
  55973. offsetX = this._epsilon;
  55974. else if (offsetX === 1)
  55975. offsetX = 1 - this._epsilon;
  55976. if (offsetY === 0)
  55977. offsetY = this._epsilon;
  55978. else if (offsetY === 1)
  55979. offsetY = 1 - this._epsilon;
  55980. var offset = index * this._vertexBufferSize;
  55981. this._vertexData[offset] = particle.position.x;
  55982. this._vertexData[offset + 1] = particle.position.y;
  55983. this._vertexData[offset + 2] = particle.position.z;
  55984. this._vertexData[offset + 3] = particle.color.r;
  55985. this._vertexData[offset + 4] = particle.color.g;
  55986. this._vertexData[offset + 5] = particle.color.b;
  55987. this._vertexData[offset + 6] = particle.color.a;
  55988. this._vertexData[offset + 7] = particle.angle;
  55989. this._vertexData[offset + 8] = particle.size;
  55990. this._vertexData[offset + 9] = offsetX;
  55991. this._vertexData[offset + 10] = offsetY;
  55992. this._vertexData[offset + 11] = particle.cellIndex;
  55993. };
  55994. ParticleSystem.prototype._stopSubEmitters = function () {
  55995. if (!this.activeSubSystems) {
  55996. return;
  55997. }
  55998. this.activeSubSystems.forEach(function (subSystem) {
  55999. subSystem.stop(true);
  56000. });
  56001. this.activeSubSystems = new Array();
  56002. };
  56003. ParticleSystem.prototype._removeFromRoot = function () {
  56004. if (!this._rootParticleSystem) {
  56005. return;
  56006. }
  56007. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56008. if (index !== -1) {
  56009. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56010. }
  56011. };
  56012. // end of sub system methods
  56013. ParticleSystem.prototype._update = function (newParticles) {
  56014. // Update current
  56015. this._alive = this._particles.length > 0;
  56016. this.updateFunction(this._particles);
  56017. // Add new ones
  56018. var worldMatrix;
  56019. if (this.emitter.position) {
  56020. var emitterMesh = this.emitter;
  56021. worldMatrix = emitterMesh.getWorldMatrix();
  56022. }
  56023. else {
  56024. var emitterPosition = this.emitter;
  56025. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56026. }
  56027. var particle;
  56028. for (var index = 0; index < newParticles; index++) {
  56029. if (this._particles.length === this._capacity) {
  56030. break;
  56031. }
  56032. particle = this._createParticle();
  56033. this._particles.push(particle);
  56034. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56035. if (this.startPositionFunction) {
  56036. this.startPositionFunction(worldMatrix, particle.position, particle);
  56037. }
  56038. else {
  56039. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56040. }
  56041. if (this.startDirectionFunction) {
  56042. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56043. }
  56044. else {
  56045. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56046. }
  56047. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56048. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56049. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56050. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56051. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56052. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56053. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56054. }
  56055. };
  56056. ParticleSystem.prototype._getEffect = function () {
  56057. if (this._customEffect) {
  56058. return this._customEffect;
  56059. }
  56060. ;
  56061. var defines = [];
  56062. if (this._scene.clipPlane) {
  56063. defines.push("#define CLIPPLANE");
  56064. }
  56065. if (this._isAnimationSheetEnabled) {
  56066. defines.push("#define ANIMATESHEET");
  56067. }
  56068. // Effect
  56069. var join = defines.join("\n");
  56070. if (this._cachedDefines !== join) {
  56071. this._cachedDefines = join;
  56072. var attributesNamesOrOptions;
  56073. var effectCreationOption;
  56074. if (this._isAnimationSheetEnabled) {
  56075. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56076. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56077. }
  56078. else {
  56079. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56080. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56081. }
  56082. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56083. }
  56084. return this._effect;
  56085. };
  56086. /**
  56087. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56088. */
  56089. ParticleSystem.prototype.animate = function () {
  56090. if (!this._started)
  56091. return;
  56092. var effect = this._getEffect();
  56093. // Check
  56094. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56095. return;
  56096. if (this._currentRenderId === this._scene.getRenderId()) {
  56097. return;
  56098. }
  56099. this._currentRenderId = this._scene.getRenderId();
  56100. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56101. // determine the number of particles we need to create
  56102. var newParticles;
  56103. if (this.manualEmitCount > -1) {
  56104. newParticles = this.manualEmitCount;
  56105. this._newPartsExcess = 0;
  56106. this.manualEmitCount = 0;
  56107. }
  56108. else {
  56109. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56110. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56111. }
  56112. if (this._newPartsExcess > 1.0) {
  56113. newParticles += this._newPartsExcess >> 0;
  56114. this._newPartsExcess -= this._newPartsExcess >> 0;
  56115. }
  56116. this._alive = false;
  56117. if (!this._stopped) {
  56118. this._actualFrame += this._scaledUpdateSpeed;
  56119. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56120. this.stop();
  56121. }
  56122. else {
  56123. newParticles = 0;
  56124. }
  56125. this._update(newParticles);
  56126. // Stopped?
  56127. if (this._stopped) {
  56128. if (!this._alive) {
  56129. this._started = false;
  56130. if (this.onAnimationEnd) {
  56131. this.onAnimationEnd();
  56132. }
  56133. if (this.disposeOnStop) {
  56134. this._scene._toBeDisposed.push(this);
  56135. }
  56136. }
  56137. }
  56138. // Animation sheet
  56139. if (this._isAnimationSheetEnabled) {
  56140. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56141. }
  56142. else {
  56143. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56144. }
  56145. // Update VBO
  56146. var offset = 0;
  56147. for (var index = 0; index < this._particles.length; index++) {
  56148. var particle = this._particles[index];
  56149. this._appendParticleVertexes(offset, particle);
  56150. offset += 4;
  56151. }
  56152. if (this._vertexBuffer) {
  56153. this._vertexBuffer.update(this._vertexData);
  56154. }
  56155. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56156. this.stop();
  56157. }
  56158. };
  56159. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56160. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56161. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56162. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56163. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56164. };
  56165. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56166. this._appendParticleVertex(offset++, particle, 0, 0);
  56167. this._appendParticleVertex(offset++, particle, 1, 0);
  56168. this._appendParticleVertex(offset++, particle, 1, 1);
  56169. this._appendParticleVertex(offset++, particle, 0, 1);
  56170. };
  56171. /**
  56172. * Rebuilds the particle system.
  56173. */
  56174. ParticleSystem.prototype.rebuild = function () {
  56175. this._createIndexBuffer();
  56176. if (this._vertexBuffer) {
  56177. this._vertexBuffer._rebuild();
  56178. }
  56179. };
  56180. /**
  56181. * Is this system ready to be used/rendered
  56182. * @return true if the system is ready
  56183. */
  56184. ParticleSystem.prototype.isReady = function () {
  56185. var effect = this._getEffect();
  56186. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56187. return false;
  56188. }
  56189. return true;
  56190. };
  56191. /**
  56192. * Renders the particle system in its current state.
  56193. * @returns the current number of particles
  56194. */
  56195. ParticleSystem.prototype.render = function () {
  56196. var effect = this._getEffect();
  56197. // Check
  56198. if (!this.isReady() || !this._particles.length) {
  56199. return 0;
  56200. }
  56201. var engine = this._scene.getEngine();
  56202. // Render
  56203. engine.enableEffect(effect);
  56204. engine.setState(false);
  56205. var viewMatrix = this._scene.getViewMatrix();
  56206. effect.setTexture("diffuseSampler", this.particleTexture);
  56207. effect.setMatrix("view", viewMatrix);
  56208. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56209. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56210. var baseSize = this.particleTexture.getBaseSize();
  56211. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56212. }
  56213. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56214. if (this._scene.clipPlane) {
  56215. var clipPlane = this._scene.clipPlane;
  56216. var invView = viewMatrix.clone();
  56217. invView.invert();
  56218. effect.setMatrix("invView", invView);
  56219. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56220. }
  56221. // VBOs
  56222. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56223. // Draw order
  56224. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56225. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56226. }
  56227. else {
  56228. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56229. }
  56230. if (this.forceDepthWrite) {
  56231. engine.setDepthWrite(true);
  56232. }
  56233. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56234. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56235. return this._particles.length;
  56236. };
  56237. /**
  56238. * Disposes the particle system and free the associated resources
  56239. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56240. */
  56241. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56242. if (disposeTexture === void 0) { disposeTexture = true; }
  56243. if (this._vertexBuffer) {
  56244. this._vertexBuffer.dispose();
  56245. this._vertexBuffer = null;
  56246. }
  56247. if (this._indexBuffer) {
  56248. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56249. this._indexBuffer = null;
  56250. }
  56251. if (disposeTexture && this.particleTexture) {
  56252. this.particleTexture.dispose();
  56253. this.particleTexture = null;
  56254. }
  56255. this._removeFromRoot();
  56256. // Remove from scene
  56257. var index = this._scene.particleSystems.indexOf(this);
  56258. if (index > -1) {
  56259. this._scene.particleSystems.splice(index, 1);
  56260. }
  56261. // Callback
  56262. this.onDisposeObservable.notifyObservers(this);
  56263. this.onDisposeObservable.clear();
  56264. };
  56265. /**
  56266. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56267. * @param radius The radius of the sphere to emit from
  56268. * @returns the emitter
  56269. */
  56270. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56271. if (radius === void 0) { radius = 1; }
  56272. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56273. this.particleEmitterType = particleEmitter;
  56274. return particleEmitter;
  56275. };
  56276. /**
  56277. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56278. * @param radius The radius of the sphere to emit from
  56279. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56280. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56281. * @returns the emitter
  56282. */
  56283. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56284. if (radius === void 0) { radius = 1; }
  56285. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56286. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56287. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56288. this.particleEmitterType = particleEmitter;
  56289. return particleEmitter;
  56290. };
  56291. /**
  56292. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56293. * @param radius The radius of the cone to emit from
  56294. * @param angle The base angle of the cone
  56295. * @returns the emitter
  56296. */
  56297. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56298. if (radius === void 0) { radius = 1; }
  56299. if (angle === void 0) { angle = Math.PI / 4; }
  56300. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56301. this.particleEmitterType = particleEmitter;
  56302. return particleEmitter;
  56303. };
  56304. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56305. /**
  56306. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56307. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56308. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56309. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56310. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56311. * @returns the emitter
  56312. */
  56313. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56314. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56315. this.particleEmitterType = particleEmitter;
  56316. this.direction1 = direction1;
  56317. this.direction2 = direction2;
  56318. this.minEmitBox = minEmitBox;
  56319. this.maxEmitBox = maxEmitBox;
  56320. return particleEmitter;
  56321. };
  56322. // Clone
  56323. /**
  56324. * Clones the particle system.
  56325. * @param name The name of the cloned object
  56326. * @param newEmitter The new emitter to use
  56327. * @returns the cloned particle system
  56328. */
  56329. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56330. var custom = null;
  56331. var program = null;
  56332. if (this.customShader != null) {
  56333. program = this.customShader;
  56334. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56335. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56336. }
  56337. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56338. result.customShader = program;
  56339. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56340. if (newEmitter === undefined) {
  56341. newEmitter = this.emitter;
  56342. }
  56343. result.emitter = newEmitter;
  56344. if (this.particleTexture) {
  56345. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56346. }
  56347. if (!this.preventAutoStart) {
  56348. result.start();
  56349. }
  56350. return result;
  56351. };
  56352. /**
  56353. * Serializes the particle system to a JSON object.
  56354. * @returns the JSON object
  56355. */
  56356. ParticleSystem.prototype.serialize = function () {
  56357. var serializationObject = {};
  56358. serializationObject.name = this.name;
  56359. serializationObject.id = this.id;
  56360. // Emitter
  56361. if (this.emitter.position) {
  56362. var emitterMesh = this.emitter;
  56363. serializationObject.emitterId = emitterMesh.id;
  56364. }
  56365. else {
  56366. var emitterPosition = this.emitter;
  56367. serializationObject.emitter = emitterPosition.asArray();
  56368. }
  56369. serializationObject.capacity = this.getCapacity();
  56370. if (this.particleTexture) {
  56371. serializationObject.textureName = this.particleTexture.name;
  56372. }
  56373. // Animations
  56374. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56375. // Particle system
  56376. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56377. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56378. serializationObject.minSize = this.minSize;
  56379. serializationObject.maxSize = this.maxSize;
  56380. serializationObject.minEmitPower = this.minEmitPower;
  56381. serializationObject.maxEmitPower = this.maxEmitPower;
  56382. serializationObject.minLifeTime = this.minLifeTime;
  56383. serializationObject.maxLifeTime = this.maxLifeTime;
  56384. serializationObject.emitRate = this.emitRate;
  56385. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56386. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56387. serializationObject.gravity = this.gravity.asArray();
  56388. serializationObject.direction1 = this.direction1.asArray();
  56389. serializationObject.direction2 = this.direction2.asArray();
  56390. serializationObject.color1 = this.color1.asArray();
  56391. serializationObject.color2 = this.color2.asArray();
  56392. serializationObject.colorDead = this.colorDead.asArray();
  56393. serializationObject.updateSpeed = this.updateSpeed;
  56394. serializationObject.targetStopDuration = this.targetStopDuration;
  56395. serializationObject.textureMask = this.textureMask.asArray();
  56396. serializationObject.blendMode = this.blendMode;
  56397. serializationObject.customShader = this.customShader;
  56398. serializationObject.preventAutoStart = this.preventAutoStart;
  56399. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56400. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56401. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56402. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56403. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56404. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56405. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56406. // Emitter
  56407. if (this.particleEmitterType) {
  56408. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56409. }
  56410. return serializationObject;
  56411. };
  56412. /**
  56413. * Parses a JSON object to create a particle system.
  56414. * @param parsedParticleSystem The JSON object to parse
  56415. * @param scene The scene to create the particle system in
  56416. * @param rootUrl The root url to use to load external dependencies like texture
  56417. * @returns the Parsed particle system
  56418. */
  56419. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56420. var name = parsedParticleSystem.name;
  56421. var custom = null;
  56422. var program = null;
  56423. if (parsedParticleSystem.customShader) {
  56424. program = parsedParticleSystem.customShader;
  56425. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56426. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56427. }
  56428. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56429. particleSystem.customShader = program;
  56430. if (parsedParticleSystem.id) {
  56431. particleSystem.id = parsedParticleSystem.id;
  56432. }
  56433. // Auto start
  56434. if (parsedParticleSystem.preventAutoStart) {
  56435. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56436. }
  56437. // Texture
  56438. if (parsedParticleSystem.textureName) {
  56439. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56440. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56441. }
  56442. // Emitter
  56443. if (parsedParticleSystem.emitterId) {
  56444. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56445. }
  56446. else {
  56447. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56448. }
  56449. // Animations
  56450. if (parsedParticleSystem.animations) {
  56451. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56452. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56453. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56454. }
  56455. }
  56456. if (parsedParticleSystem.autoAnimate) {
  56457. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56458. }
  56459. // Particle system
  56460. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56461. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56462. particleSystem.minSize = parsedParticleSystem.minSize;
  56463. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56464. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56465. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56466. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56467. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56468. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56469. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56470. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56471. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56472. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56473. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56474. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56475. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56476. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56477. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56478. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56479. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56480. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56481. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56482. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56483. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56484. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56485. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56486. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56487. if (!particleSystem.preventAutoStart) {
  56488. particleSystem.start();
  56489. }
  56490. return particleSystem;
  56491. };
  56492. /**
  56493. * Source color is added to the destination color without alpha affecting the result.
  56494. */
  56495. ParticleSystem.BLENDMODE_ONEONE = 0;
  56496. /**
  56497. * Blend current color and particle color using particle’s alpha.
  56498. */
  56499. ParticleSystem.BLENDMODE_STANDARD = 1;
  56500. return ParticleSystem;
  56501. }());
  56502. BABYLON.ParticleSystem = ParticleSystem;
  56503. })(BABYLON || (BABYLON = {}));
  56504. //# sourceMappingURL=babylon.particleSystem.js.map
  56505. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56506. var BABYLON;
  56507. (function (BABYLON) {
  56508. /**
  56509. * Particle emitter emitting particles from the inside of a box.
  56510. * It emits the particles randomly between 2 given directions.
  56511. */
  56512. var BoxParticleEmitter = /** @class */ (function () {
  56513. /**
  56514. * Creates a new instance BoxParticleEmitter
  56515. */
  56516. function BoxParticleEmitter() {
  56517. /**
  56518. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56519. */
  56520. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56521. /**
  56522. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56523. */
  56524. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56525. /**
  56526. * 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.
  56527. */
  56528. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56529. /**
  56530. * 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.
  56531. */
  56532. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56533. }
  56534. /**
  56535. * Called by the particle System when the direction is computed for the created particle.
  56536. * @param emitPower is the power of the particle (speed)
  56537. * @param worldMatrix is the world matrix of the particle system
  56538. * @param directionToUpdate is the direction vector to update with the result
  56539. * @param particle is the particle we are computed the direction for
  56540. */
  56541. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56542. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56543. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56544. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56545. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56546. };
  56547. /**
  56548. * Called by the particle System when the position is computed for the created particle.
  56549. * @param worldMatrix is the world matrix of the particle system
  56550. * @param positionToUpdate is the position vector to update with the result
  56551. * @param particle is the particle we are computed the position for
  56552. */
  56553. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56554. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56555. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56556. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56557. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56558. };
  56559. /**
  56560. * Clones the current emitter and returns a copy of it
  56561. * @returns the new emitter
  56562. */
  56563. BoxParticleEmitter.prototype.clone = function () {
  56564. var newOne = new BoxParticleEmitter();
  56565. BABYLON.Tools.DeepCopy(this, newOne);
  56566. return newOne;
  56567. };
  56568. /**
  56569. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56570. * @param effect defines the update shader
  56571. */
  56572. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56573. effect.setVector3("direction1", this.direction1);
  56574. effect.setVector3("direction2", this.direction2);
  56575. effect.setVector3("minEmitBox", this.minEmitBox);
  56576. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56577. };
  56578. /**
  56579. * Returns a string to use to update the GPU particles update shader
  56580. * @returns a string containng the defines string
  56581. */
  56582. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56583. return "#define BOXEMITTER";
  56584. };
  56585. /**
  56586. * Returns the string "BoxEmitter"
  56587. * @returns a string containing the class name
  56588. */
  56589. BoxParticleEmitter.prototype.getClassName = function () {
  56590. return "BoxEmitter";
  56591. };
  56592. /**
  56593. * Serializes the particle system to a JSON object.
  56594. * @returns the JSON object
  56595. */
  56596. BoxParticleEmitter.prototype.serialize = function () {
  56597. var serializationObject = {};
  56598. serializationObject.type = this.getClassName();
  56599. serializationObject.direction1 = this.direction1.asArray();
  56600. ;
  56601. serializationObject.direction2 = this.direction2.asArray();
  56602. ;
  56603. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56604. ;
  56605. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56606. ;
  56607. return serializationObject;
  56608. };
  56609. /**
  56610. * Parse properties from a JSON object
  56611. * @param serializationObject defines the JSON object
  56612. */
  56613. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56614. this.direction1.copyFrom(serializationObject.direction1);
  56615. this.direction2.copyFrom(serializationObject.direction2);
  56616. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56617. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56618. };
  56619. return BoxParticleEmitter;
  56620. }());
  56621. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56622. })(BABYLON || (BABYLON = {}));
  56623. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56624. var BABYLON;
  56625. (function (BABYLON) {
  56626. /**
  56627. * Particle emitter emitting particles from the inside of a cone.
  56628. * It emits the particles alongside the cone volume from the base to the particle.
  56629. * The emission direction might be randomized.
  56630. */
  56631. var ConeParticleEmitter = /** @class */ (function () {
  56632. /**
  56633. * Creates a new instance ConeParticleEmitter
  56634. * @param radius the radius of the emission cone (1 by default)
  56635. * @param angles the cone base angle (PI by default)
  56636. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56637. */
  56638. function ConeParticleEmitter(radius,
  56639. /**
  56640. * The radius of the emission cone.
  56641. */
  56642. angle,
  56643. /**
  56644. * The cone base angle.
  56645. */
  56646. directionRandomizer) {
  56647. if (radius === void 0) { radius = 1; }
  56648. if (angle === void 0) { angle = Math.PI; }
  56649. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56650. this.angle = angle;
  56651. this.directionRandomizer = directionRandomizer;
  56652. this.radius = radius;
  56653. }
  56654. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56655. /**
  56656. * Gets the radius of the emission cone.
  56657. */
  56658. get: function () {
  56659. return this._radius;
  56660. },
  56661. /**
  56662. * Sets the radius of the emission cone.
  56663. */
  56664. set: function (value) {
  56665. this._radius = value;
  56666. if (this.angle !== 0) {
  56667. this._height = value / Math.tan(this.angle / 2);
  56668. }
  56669. else {
  56670. this._height = 1;
  56671. }
  56672. },
  56673. enumerable: true,
  56674. configurable: true
  56675. });
  56676. /**
  56677. * Called by the particle System when the direction is computed for the created particle.
  56678. * @param emitPower is the power of the particle (speed)
  56679. * @param worldMatrix is the world matrix of the particle system
  56680. * @param directionToUpdate is the direction vector to update with the result
  56681. * @param particle is the particle we are computed the direction for
  56682. */
  56683. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56684. if (this.angle === 0) {
  56685. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56686. }
  56687. else {
  56688. // measure the direction Vector from the emitter to the particle.
  56689. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56690. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56691. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56692. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56693. direction.x += randX;
  56694. direction.y += randY;
  56695. direction.z += randZ;
  56696. direction.normalize();
  56697. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56698. }
  56699. };
  56700. /**
  56701. * Called by the particle System when the position is computed for the created particle.
  56702. * @param worldMatrix is the world matrix of the particle system
  56703. * @param positionToUpdate is the position vector to update with the result
  56704. * @param particle is the particle we are computed the position for
  56705. */
  56706. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56707. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56708. var h = BABYLON.Scalar.RandomRange(0, 1);
  56709. // Better distribution in a cone at normal angles.
  56710. h = 1 - h * h;
  56711. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56712. radius = radius * h;
  56713. var randX = radius * Math.sin(s);
  56714. var randZ = radius * Math.cos(s);
  56715. var randY = h * this._height;
  56716. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56717. };
  56718. /**
  56719. * Clones the current emitter and returns a copy of it
  56720. * @returns the new emitter
  56721. */
  56722. ConeParticleEmitter.prototype.clone = function () {
  56723. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56724. BABYLON.Tools.DeepCopy(this, newOne);
  56725. return newOne;
  56726. };
  56727. /**
  56728. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56729. * @param effect defines the update shader
  56730. */
  56731. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56732. effect.setFloat("radius", this.radius);
  56733. effect.setFloat("angle", this.angle);
  56734. effect.setFloat("height", this._height);
  56735. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56736. };
  56737. /**
  56738. * Returns a string to use to update the GPU particles update shader
  56739. * @returns a string containng the defines string
  56740. */
  56741. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56742. return "#define CONEEMITTER";
  56743. };
  56744. /**
  56745. * Returns the string "BoxEmitter"
  56746. * @returns a string containing the class name
  56747. */
  56748. ConeParticleEmitter.prototype.getClassName = function () {
  56749. return "ConeEmitter";
  56750. };
  56751. /**
  56752. * Serializes the particle system to a JSON object.
  56753. * @returns the JSON object
  56754. */
  56755. ConeParticleEmitter.prototype.serialize = function () {
  56756. var serializationObject = {};
  56757. serializationObject.type = this.getClassName();
  56758. serializationObject.radius = this.radius;
  56759. serializationObject.angle = this.angle;
  56760. serializationObject.directionRandomizer = this.directionRandomizer;
  56761. return serializationObject;
  56762. };
  56763. /**
  56764. * Parse properties from a JSON object
  56765. * @param serializationObject defines the JSON object
  56766. */
  56767. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56768. this.radius = serializationObject.radius;
  56769. this.angle = serializationObject.angle;
  56770. this.directionRandomizer = serializationObject.directionRandomizer;
  56771. };
  56772. return ConeParticleEmitter;
  56773. }());
  56774. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56775. })(BABYLON || (BABYLON = {}));
  56776. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56777. var BABYLON;
  56778. (function (BABYLON) {
  56779. /**
  56780. * Particle emitter emitting particles from the inside of a sphere.
  56781. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56782. */
  56783. var SphereParticleEmitter = /** @class */ (function () {
  56784. /**
  56785. * Creates a new instance SphereParticleEmitter
  56786. * @param radius the radius of the emission sphere (1 by default)
  56787. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56788. */
  56789. function SphereParticleEmitter(
  56790. /**
  56791. * The radius of the emission sphere.
  56792. */
  56793. radius,
  56794. /**
  56795. * How much to randomize the particle direction [0-1].
  56796. */
  56797. directionRandomizer) {
  56798. if (radius === void 0) { radius = 1; }
  56799. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56800. this.radius = radius;
  56801. this.directionRandomizer = directionRandomizer;
  56802. }
  56803. /**
  56804. * Called by the particle System when the direction is computed for the created particle.
  56805. * @param emitPower is the power of the particle (speed)
  56806. * @param worldMatrix is the world matrix of the particle system
  56807. * @param directionToUpdate is the direction vector to update with the result
  56808. * @param particle is the particle we are computed the direction for
  56809. */
  56810. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56811. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56812. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56813. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56814. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56815. direction.x += randX;
  56816. direction.y += randY;
  56817. direction.z += randZ;
  56818. direction.normalize();
  56819. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56820. };
  56821. /**
  56822. * Called by the particle System when the position is computed for the created particle.
  56823. * @param worldMatrix is the world matrix of the particle system
  56824. * @param positionToUpdate is the position vector to update with the result
  56825. * @param particle is the particle we are computed the position for
  56826. */
  56827. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56828. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56829. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56830. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56831. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56832. var randY = randRadius * Math.cos(theta);
  56833. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56834. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56835. };
  56836. /**
  56837. * Clones the current emitter and returns a copy of it
  56838. * @returns the new emitter
  56839. */
  56840. SphereParticleEmitter.prototype.clone = function () {
  56841. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56842. BABYLON.Tools.DeepCopy(this, newOne);
  56843. return newOne;
  56844. };
  56845. /**
  56846. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56847. * @param effect defines the update shader
  56848. */
  56849. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56850. effect.setFloat("radius", this.radius);
  56851. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56852. };
  56853. /**
  56854. * Returns a string to use to update the GPU particles update shader
  56855. * @returns a string containng the defines string
  56856. */
  56857. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56858. return "#define SPHEREEMITTER";
  56859. };
  56860. /**
  56861. * Returns the string "SphereParticleEmitter"
  56862. * @returns a string containing the class name
  56863. */
  56864. SphereParticleEmitter.prototype.getClassName = function () {
  56865. return "SphereParticleEmitter";
  56866. };
  56867. /**
  56868. * Serializes the particle system to a JSON object.
  56869. * @returns the JSON object
  56870. */
  56871. SphereParticleEmitter.prototype.serialize = function () {
  56872. var serializationObject = {};
  56873. serializationObject.type = this.getClassName();
  56874. serializationObject.radius = this.radius;
  56875. serializationObject.directionRandomizer = this.directionRandomizer;
  56876. return serializationObject;
  56877. };
  56878. /**
  56879. * Parse properties from a JSON object
  56880. * @param serializationObject defines the JSON object
  56881. */
  56882. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56883. this.radius = serializationObject.radius;
  56884. this.directionRandomizer = serializationObject.directionRandomizer;
  56885. };
  56886. return SphereParticleEmitter;
  56887. }());
  56888. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56889. /**
  56890. * Particle emitter emitting particles from the inside of a sphere.
  56891. * It emits the particles randomly between two vectors.
  56892. */
  56893. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56894. __extends(SphereDirectedParticleEmitter, _super);
  56895. /**
  56896. * Creates a new instance SphereDirectedParticleEmitter
  56897. * @param radius the radius of the emission sphere (1 by default)
  56898. * @param direction1 the min limit of the emission direction (up vector by default)
  56899. * @param direction2 the max limit of the emission direction (up vector by default)
  56900. */
  56901. function SphereDirectedParticleEmitter(radius,
  56902. /**
  56903. * The min limit of the emission direction.
  56904. */
  56905. direction1,
  56906. /**
  56907. * The max limit of the emission direction.
  56908. */
  56909. direction2) {
  56910. if (radius === void 0) { radius = 1; }
  56911. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56912. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56913. var _this = _super.call(this, radius) || this;
  56914. _this.direction1 = direction1;
  56915. _this.direction2 = direction2;
  56916. return _this;
  56917. }
  56918. /**
  56919. * Called by the particle System when the direction is computed for the created particle.
  56920. * @param emitPower is the power of the particle (speed)
  56921. * @param worldMatrix is the world matrix of the particle system
  56922. * @param directionToUpdate is the direction vector to update with the result
  56923. * @param particle is the particle we are computed the direction for
  56924. */
  56925. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56926. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56927. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56928. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56929. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56930. };
  56931. /**
  56932. * Clones the current emitter and returns a copy of it
  56933. * @returns the new emitter
  56934. */
  56935. SphereDirectedParticleEmitter.prototype.clone = function () {
  56936. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56937. BABYLON.Tools.DeepCopy(this, newOne);
  56938. return newOne;
  56939. };
  56940. /**
  56941. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56942. * @param effect defines the update shader
  56943. */
  56944. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56945. effect.setFloat("radius", this.radius);
  56946. effect.setVector3("direction1", this.direction1);
  56947. effect.setVector3("direction2", this.direction2);
  56948. };
  56949. /**
  56950. * Returns a string to use to update the GPU particles update shader
  56951. * @returns a string containng the defines string
  56952. */
  56953. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56954. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56955. };
  56956. /**
  56957. * Returns the string "SphereDirectedParticleEmitter"
  56958. * @returns a string containing the class name
  56959. */
  56960. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56961. return "SphereDirectedParticleEmitter";
  56962. };
  56963. /**
  56964. * Serializes the particle system to a JSON object.
  56965. * @returns the JSON object
  56966. */
  56967. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56968. var serializationObject = _super.prototype.serialize.call(this);
  56969. ;
  56970. serializationObject.direction1 = this.direction1.asArray();
  56971. ;
  56972. serializationObject.direction2 = this.direction2.asArray();
  56973. ;
  56974. return serializationObject;
  56975. };
  56976. /**
  56977. * Parse properties from a JSON object
  56978. * @param serializationObject defines the JSON object
  56979. */
  56980. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56981. _super.prototype.parse.call(this, serializationObject);
  56982. this.direction1.copyFrom(serializationObject.direction1);
  56983. this.direction2.copyFrom(serializationObject.direction2);
  56984. };
  56985. return SphereDirectedParticleEmitter;
  56986. }(SphereParticleEmitter));
  56987. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56988. })(BABYLON || (BABYLON = {}));
  56989. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56990. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56991. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56992. s = arguments[i];
  56993. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56994. t[p] = s[p];
  56995. }
  56996. return t;
  56997. };
  56998. var BABYLON;
  56999. (function (BABYLON) {
  57000. /**
  57001. * This represents a GPU particle system in Babylon
  57002. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57003. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57004. */
  57005. var GPUParticleSystem = /** @class */ (function () {
  57006. /**
  57007. * Instantiates a GPU particle system.
  57008. * 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.
  57009. * @param name The name of the particle system
  57010. * @param capacity The max number of particles alive at the same time
  57011. * @param scene The scene the particle system belongs to
  57012. */
  57013. function GPUParticleSystem(name, options, scene) {
  57014. /**
  57015. * The emitter represents the Mesh or position we are attaching the particle system to.
  57016. */
  57017. this.emitter = null;
  57018. /**
  57019. * The rendering group used by the Particle system to chose when to render.
  57020. */
  57021. this.renderingGroupId = 0;
  57022. /**
  57023. * The layer mask we are rendering the particles through.
  57024. */
  57025. this.layerMask = 0x0FFFFFFF;
  57026. this._targetIndex = 0;
  57027. this._currentRenderId = -1;
  57028. this._started = false;
  57029. this._stopped = false;
  57030. this._timeDelta = 0;
  57031. this._attributesStrideSize = 14;
  57032. this._actualFrame = 0;
  57033. /**
  57034. * List of animations used by the particle system.
  57035. */
  57036. this.animations = [];
  57037. /**
  57038. * An event triggered when the system is disposed.
  57039. */
  57040. this.onDisposeObservable = new BABYLON.Observable();
  57041. /**
  57042. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57043. */
  57044. this.updateSpeed = 0.01;
  57045. /**
  57046. * The amount of time the particle system is running (depends of the overall update speed).
  57047. */
  57048. this.targetStopDuration = 0;
  57049. /**
  57050. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57051. */
  57052. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57053. /**
  57054. * Minimum life time of emitting particles.
  57055. */
  57056. this.minLifeTime = 1;
  57057. /**
  57058. * Maximum life time of emitting particles.
  57059. */
  57060. this.maxLifeTime = 1;
  57061. /**
  57062. * Minimum Size of emitting particles.
  57063. */
  57064. this.minSize = 1;
  57065. /**
  57066. * Maximum Size of emitting particles.
  57067. */
  57068. this.maxSize = 1;
  57069. /**
  57070. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57071. */
  57072. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57073. /**
  57074. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57075. */
  57076. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57077. /**
  57078. * Color the particle will have at the end of its lifetime.
  57079. */
  57080. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57081. /**
  57082. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57083. */
  57084. this.emitRate = 100;
  57085. /**
  57086. * You can use gravity if you want to give an orientation to your particles.
  57087. */
  57088. this.gravity = BABYLON.Vector3.Zero();
  57089. /**
  57090. * Minimum power of emitting particles.
  57091. */
  57092. this.minEmitPower = 1;
  57093. /**
  57094. * Maximum power of emitting particles.
  57095. */
  57096. this.maxEmitPower = 1;
  57097. /**
  57098. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57099. * to override the particles.
  57100. */
  57101. this.forceDepthWrite = false;
  57102. this.id = name;
  57103. this.name = name;
  57104. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57105. this._engine = this._scene.getEngine();
  57106. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57107. this._capacity = fullOptions.capacity;
  57108. this._activeCount = fullOptions.capacity;
  57109. this._currentActiveCount = 0;
  57110. this._scene.particleSystems.push(this);
  57111. this._updateEffectOptions = {
  57112. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57113. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57114. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57115. uniformBuffersNames: [],
  57116. samplers: ["randomSampler"],
  57117. defines: "",
  57118. fallbacks: null,
  57119. onCompiled: null,
  57120. onError: null,
  57121. indexParameters: null,
  57122. maxSimultaneousLights: 0,
  57123. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57124. };
  57125. // Random data
  57126. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57127. var d = [];
  57128. for (var i = 0; i < maxTextureSize; ++i) {
  57129. d.push(Math.random());
  57130. d.push(Math.random());
  57131. d.push(Math.random());
  57132. d.push(Math.random());
  57133. }
  57134. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57135. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57136. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57137. this._randomTextureSize = maxTextureSize;
  57138. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57139. }
  57140. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57141. /**
  57142. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57143. */
  57144. get: function () {
  57145. if (!BABYLON.Engine.LastCreatedEngine) {
  57146. return false;
  57147. }
  57148. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57149. },
  57150. enumerable: true,
  57151. configurable: true
  57152. });
  57153. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57154. /**
  57155. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57156. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57157. */
  57158. get: function () {
  57159. if (this.particleEmitterType.direction1) {
  57160. return this.particleEmitterType.direction1;
  57161. }
  57162. return BABYLON.Vector3.Zero();
  57163. },
  57164. set: function (value) {
  57165. if (this.particleEmitterType.direction1) {
  57166. this.particleEmitterType.direction1 = value;
  57167. }
  57168. },
  57169. enumerable: true,
  57170. configurable: true
  57171. });
  57172. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57173. /**
  57174. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57175. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57176. */
  57177. get: function () {
  57178. if (this.particleEmitterType.direction2) {
  57179. return this.particleEmitterType.direction2;
  57180. }
  57181. return BABYLON.Vector3.Zero();
  57182. },
  57183. set: function (value) {
  57184. if (this.particleEmitterType.direction2) {
  57185. this.particleEmitterType.direction2 = value;
  57186. }
  57187. },
  57188. enumerable: true,
  57189. configurable: true
  57190. });
  57191. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57192. /**
  57193. * 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.
  57194. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57195. */
  57196. get: function () {
  57197. if (this.particleEmitterType.minEmitBox) {
  57198. return this.particleEmitterType.minEmitBox;
  57199. }
  57200. return BABYLON.Vector3.Zero();
  57201. },
  57202. set: function (value) {
  57203. if (this.particleEmitterType.minEmitBox) {
  57204. this.particleEmitterType.minEmitBox = value;
  57205. }
  57206. },
  57207. enumerable: true,
  57208. configurable: true
  57209. });
  57210. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57211. /**
  57212. * 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.
  57213. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57214. */
  57215. get: function () {
  57216. if (this.particleEmitterType.maxEmitBox) {
  57217. return this.particleEmitterType.maxEmitBox;
  57218. }
  57219. return BABYLON.Vector3.Zero();
  57220. },
  57221. set: function (value) {
  57222. if (this.particleEmitterType.maxEmitBox) {
  57223. this.particleEmitterType.maxEmitBox = value;
  57224. }
  57225. },
  57226. enumerable: true,
  57227. configurable: true
  57228. });
  57229. /**
  57230. * Gets the maximum number of particles active at the same time.
  57231. * @returns The max number of active particles.
  57232. */
  57233. GPUParticleSystem.prototype.getCapacity = function () {
  57234. return this._capacity;
  57235. };
  57236. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57237. /**
  57238. * Gets or set the number of active particles
  57239. */
  57240. get: function () {
  57241. return this._activeCount;
  57242. },
  57243. set: function (value) {
  57244. this._activeCount = Math.min(value, this._capacity);
  57245. },
  57246. enumerable: true,
  57247. configurable: true
  57248. });
  57249. /**
  57250. * Is this system ready to be used/rendered
  57251. * @return true if the system is ready
  57252. */
  57253. GPUParticleSystem.prototype.isReady = function () {
  57254. if (!this._updateEffect) {
  57255. this._recreateUpdateEffect();
  57256. this._recreateRenderEffect();
  57257. return false;
  57258. }
  57259. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57260. return false;
  57261. }
  57262. return true;
  57263. };
  57264. /**
  57265. * Gets Wether the system has been started.
  57266. * @returns True if it has been started, otherwise false.
  57267. */
  57268. GPUParticleSystem.prototype.isStarted = function () {
  57269. return this._started;
  57270. };
  57271. /**
  57272. * Starts the particle system and begins to emit.
  57273. */
  57274. GPUParticleSystem.prototype.start = function () {
  57275. this._started = true;
  57276. this._stopped = false;
  57277. };
  57278. /**
  57279. * Stops the particle system.
  57280. */
  57281. GPUParticleSystem.prototype.stop = function () {
  57282. this._stopped = true;
  57283. };
  57284. /**
  57285. * Remove all active particles
  57286. */
  57287. GPUParticleSystem.prototype.reset = function () {
  57288. this._releaseBuffers();
  57289. this._releaseVAOs();
  57290. this._currentActiveCount = 0;
  57291. this._targetIndex = 0;
  57292. };
  57293. /**
  57294. * Returns the string "GPUParticleSystem"
  57295. * @returns a string containing the class name
  57296. */
  57297. GPUParticleSystem.prototype.getClassName = function () {
  57298. return "GPUParticleSystem";
  57299. };
  57300. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57301. var updateVertexBuffers = {};
  57302. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57303. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57304. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57305. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57306. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57307. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57308. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57309. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57310. this._engine.bindArrayBuffer(null);
  57311. return vao;
  57312. };
  57313. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57314. var renderVertexBuffers = {};
  57315. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57316. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57317. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57318. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57319. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57320. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57321. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57322. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57323. this._engine.bindArrayBuffer(null);
  57324. return vao;
  57325. };
  57326. GPUParticleSystem.prototype._initialize = function (force) {
  57327. if (force === void 0) { force = false; }
  57328. if (this._buffer0 && !force) {
  57329. return;
  57330. }
  57331. var engine = this._scene.getEngine();
  57332. var data = new Array();
  57333. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57334. // position
  57335. data.push(0.0);
  57336. data.push(0.0);
  57337. data.push(0.0);
  57338. // Age and life
  57339. data.push(0.0); // create the particle as a dead one to create a new one at start
  57340. data.push(0.0);
  57341. // Seed
  57342. data.push(Math.random());
  57343. // Size
  57344. data.push(0.0);
  57345. // color
  57346. data.push(0.0);
  57347. data.push(0.0);
  57348. data.push(0.0);
  57349. data.push(0.0);
  57350. // direction
  57351. data.push(0.0);
  57352. data.push(0.0);
  57353. data.push(0.0);
  57354. }
  57355. // Sprite data
  57356. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57357. -0.5, 0.5, 0, 1,
  57358. -0.5, -0.5, 0, 0,
  57359. 0.5, -0.5, 1, 0]);
  57360. // Buffers
  57361. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57362. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57363. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57364. // Update VAO
  57365. this._updateVAO = [];
  57366. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57367. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57368. // Render VAO
  57369. this._renderVAO = [];
  57370. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57371. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57372. // Links
  57373. this._sourceBuffer = this._buffer0;
  57374. this._targetBuffer = this._buffer1;
  57375. };
  57376. /** @hidden */
  57377. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57378. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57379. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57380. return;
  57381. }
  57382. this._updateEffectOptions.defines = defines;
  57383. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57384. };
  57385. /** @hidden */
  57386. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57387. var defines = "";
  57388. if (this._scene.clipPlane) {
  57389. defines = "\n#define CLIPPLANE";
  57390. }
  57391. if (this._renderEffect && this._renderEffect.defines === defines) {
  57392. return;
  57393. }
  57394. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57395. };
  57396. /**
  57397. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57398. */
  57399. GPUParticleSystem.prototype.animate = function () {
  57400. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57401. this._actualFrame += this._timeDelta;
  57402. if (!this._stopped) {
  57403. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57404. this.stop();
  57405. }
  57406. }
  57407. };
  57408. /**
  57409. * Renders the particle system in its current state.
  57410. * @returns the current number of particles
  57411. */
  57412. GPUParticleSystem.prototype.render = function () {
  57413. if (!this._started) {
  57414. return 0;
  57415. }
  57416. this._recreateUpdateEffect();
  57417. this._recreateRenderEffect();
  57418. if (!this.isReady()) {
  57419. return 0;
  57420. }
  57421. if (this._currentRenderId === this._scene.getRenderId()) {
  57422. return 0;
  57423. }
  57424. this._currentRenderId = this._scene.getRenderId();
  57425. // Get everything ready to render
  57426. this._initialize();
  57427. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57428. // Enable update effect
  57429. this._engine.enableEffect(this._updateEffect);
  57430. this._engine.setState(false);
  57431. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57432. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57433. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57434. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57435. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57436. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57437. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57438. this._updateEffect.setDirectColor4("color1", this.color1);
  57439. this._updateEffect.setDirectColor4("color2", this.color2);
  57440. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57441. this._updateEffect.setVector3("gravity", this.gravity);
  57442. if (this.particleEmitterType) {
  57443. this.particleEmitterType.applyToShader(this._updateEffect);
  57444. }
  57445. var emitterWM;
  57446. if (this.emitter.position) {
  57447. var emitterMesh = this.emitter;
  57448. emitterWM = emitterMesh.getWorldMatrix();
  57449. }
  57450. else {
  57451. var emitterPosition = this.emitter;
  57452. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57453. }
  57454. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57455. // Bind source VAO
  57456. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57457. // Update
  57458. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57459. this._engine.setRasterizerState(false);
  57460. this._engine.beginTransformFeedback();
  57461. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57462. this._engine.endTransformFeedback();
  57463. this._engine.setRasterizerState(true);
  57464. this._engine.bindTransformFeedbackBuffer(null);
  57465. // Enable render effect
  57466. this._engine.enableEffect(this._renderEffect);
  57467. var viewMatrix = this._scene.getViewMatrix();
  57468. this._renderEffect.setMatrix("view", viewMatrix);
  57469. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57470. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57471. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57472. if (this._scene.clipPlane) {
  57473. var clipPlane = this._scene.clipPlane;
  57474. var invView = viewMatrix.clone();
  57475. invView.invert();
  57476. this._renderEffect.setMatrix("invView", invView);
  57477. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57478. }
  57479. // Draw order
  57480. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57481. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57482. }
  57483. else {
  57484. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57485. }
  57486. if (this.forceDepthWrite) {
  57487. this._engine.setDepthWrite(true);
  57488. }
  57489. // Bind source VAO
  57490. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57491. // Render
  57492. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57493. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57494. // Switch VAOs
  57495. this._targetIndex++;
  57496. if (this._targetIndex === 2) {
  57497. this._targetIndex = 0;
  57498. }
  57499. // Switch buffers
  57500. var tmpBuffer = this._sourceBuffer;
  57501. this._sourceBuffer = this._targetBuffer;
  57502. this._targetBuffer = tmpBuffer;
  57503. return this._currentActiveCount;
  57504. };
  57505. /**
  57506. * Rebuilds the particle system
  57507. */
  57508. GPUParticleSystem.prototype.rebuild = function () {
  57509. this._initialize(true);
  57510. };
  57511. GPUParticleSystem.prototype._releaseBuffers = function () {
  57512. if (this._buffer0) {
  57513. this._buffer0.dispose();
  57514. this._buffer0 = null;
  57515. }
  57516. if (this._buffer1) {
  57517. this._buffer1.dispose();
  57518. this._buffer1 = null;
  57519. }
  57520. if (this._spriteBuffer) {
  57521. this._spriteBuffer.dispose();
  57522. this._spriteBuffer = null;
  57523. }
  57524. };
  57525. GPUParticleSystem.prototype._releaseVAOs = function () {
  57526. if (!this._updateVAO) {
  57527. return;
  57528. }
  57529. for (var index = 0; index < this._updateVAO.length; index++) {
  57530. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57531. }
  57532. this._updateVAO = [];
  57533. for (var index = 0; index < this._renderVAO.length; index++) {
  57534. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57535. }
  57536. this._renderVAO = [];
  57537. };
  57538. /**
  57539. * Disposes the particle system and free the associated resources
  57540. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57541. */
  57542. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57543. if (disposeTexture === void 0) { disposeTexture = true; }
  57544. var index = this._scene.particleSystems.indexOf(this);
  57545. if (index > -1) {
  57546. this._scene.particleSystems.splice(index, 1);
  57547. }
  57548. this._releaseBuffers();
  57549. this._releaseVAOs();
  57550. if (this._randomTexture) {
  57551. this._randomTexture.dispose();
  57552. this._randomTexture = null;
  57553. }
  57554. if (disposeTexture && this.particleTexture) {
  57555. this.particleTexture.dispose();
  57556. this.particleTexture = null;
  57557. }
  57558. // Callback
  57559. this.onDisposeObservable.notifyObservers(this);
  57560. this.onDisposeObservable.clear();
  57561. };
  57562. /**
  57563. * Clones the particle system.
  57564. * @param name The name of the cloned object
  57565. * @param newEmitter The new emitter to use
  57566. * @returns the cloned particle system
  57567. */
  57568. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57569. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57570. BABYLON.Tools.DeepCopy(this, result);
  57571. if (newEmitter === undefined) {
  57572. newEmitter = this.emitter;
  57573. }
  57574. result.emitter = newEmitter;
  57575. if (this.particleTexture) {
  57576. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57577. }
  57578. return result;
  57579. };
  57580. /**
  57581. * Serializes the particle system to a JSON object.
  57582. * @returns the JSON object
  57583. */
  57584. GPUParticleSystem.prototype.serialize = function () {
  57585. var serializationObject = {};
  57586. serializationObject.name = this.name;
  57587. serializationObject.id = this.id;
  57588. // Emitter
  57589. if (this.emitter.position) {
  57590. var emitterMesh = this.emitter;
  57591. serializationObject.emitterId = emitterMesh.id;
  57592. }
  57593. else {
  57594. var emitterPosition = this.emitter;
  57595. serializationObject.emitter = emitterPosition.asArray();
  57596. }
  57597. serializationObject.capacity = this.getCapacity();
  57598. if (this.particleTexture) {
  57599. serializationObject.textureName = this.particleTexture.name;
  57600. }
  57601. // Animations
  57602. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57603. // Particle system
  57604. serializationObject.activeParticleCount = this.activeParticleCount;
  57605. serializationObject.randomTextureSize = this._randomTextureSize;
  57606. serializationObject.minSize = this.minSize;
  57607. serializationObject.maxSize = this.maxSize;
  57608. serializationObject.minEmitPower = this.minEmitPower;
  57609. serializationObject.maxEmitPower = this.maxEmitPower;
  57610. serializationObject.minLifeTime = this.minLifeTime;
  57611. serializationObject.maxLifeTime = this.maxLifeTime;
  57612. serializationObject.emitRate = this.emitRate;
  57613. serializationObject.gravity = this.gravity.asArray();
  57614. serializationObject.color1 = this.color1.asArray();
  57615. serializationObject.color2 = this.color2.asArray();
  57616. serializationObject.colorDead = this.colorDead.asArray();
  57617. serializationObject.updateSpeed = this.updateSpeed;
  57618. serializationObject.targetStopDuration = this.targetStopDuration;
  57619. serializationObject.blendMode = this.blendMode;
  57620. // Emitter
  57621. if (this.particleEmitterType) {
  57622. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57623. }
  57624. return serializationObject;
  57625. };
  57626. /**
  57627. * Parses a JSON object to create a GPU particle system.
  57628. * @param parsedParticleSystem The JSON object to parse
  57629. * @param scene The scene to create the particle system in
  57630. * @param rootUrl The root url to use to load external dependencies like texture
  57631. * @returns the parsed GPU particle system
  57632. */
  57633. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57634. var name = parsedParticleSystem.name;
  57635. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57636. if (parsedParticleSystem.id) {
  57637. particleSystem.id = parsedParticleSystem.id;
  57638. }
  57639. // Texture
  57640. if (parsedParticleSystem.textureName) {
  57641. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57642. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57643. }
  57644. // Emitter
  57645. if (parsedParticleSystem.emitterId) {
  57646. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57647. }
  57648. else {
  57649. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57650. }
  57651. // Animations
  57652. if (parsedParticleSystem.animations) {
  57653. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57654. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57655. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57656. }
  57657. }
  57658. // Particle system
  57659. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57660. particleSystem.minSize = parsedParticleSystem.minSize;
  57661. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57662. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57663. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57664. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57665. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57666. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57667. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57668. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57669. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57670. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57671. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57672. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57673. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57674. // Emitter
  57675. if (parsedParticleSystem.particleEmitterType) {
  57676. var emitterType = void 0;
  57677. switch (parsedParticleSystem.particleEmitterType.type) {
  57678. case "SphereEmitter":
  57679. emitterType = new BABYLON.SphereParticleEmitter();
  57680. break;
  57681. case "SphereDirectedParticleEmitter":
  57682. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57683. break;
  57684. case "ConeEmitter":
  57685. emitterType = new BABYLON.ConeParticleEmitter();
  57686. break;
  57687. case "BoxEmitter":
  57688. default:
  57689. emitterType = new BABYLON.BoxParticleEmitter();
  57690. break;
  57691. }
  57692. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57693. particleSystem.particleEmitterType = emitterType;
  57694. }
  57695. return particleSystem;
  57696. };
  57697. return GPUParticleSystem;
  57698. }());
  57699. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57700. })(BABYLON || (BABYLON = {}));
  57701. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57702. var BABYLON;
  57703. (function (BABYLON) {
  57704. /**
  57705. * Represents one particle of a solid particle system.
  57706. */
  57707. var SolidParticle = /** @class */ (function () {
  57708. /**
  57709. * Creates a Solid Particle object.
  57710. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57711. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57712. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57713. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57714. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57715. * @param shapeId (integer) is the model shape identifier in the SPS.
  57716. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57717. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57718. */
  57719. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57720. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57721. /**
  57722. * particle global index
  57723. */
  57724. this.idx = 0;
  57725. /**
  57726. * The color of the particle
  57727. */
  57728. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57729. /**
  57730. * The world space position of the particle.
  57731. */
  57732. this.position = BABYLON.Vector3.Zero();
  57733. /**
  57734. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57735. */
  57736. this.rotation = BABYLON.Vector3.Zero();
  57737. /**
  57738. * The scaling of the particle.
  57739. */
  57740. this.scaling = BABYLON.Vector3.One();
  57741. /**
  57742. * The uvs of the particle.
  57743. */
  57744. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57745. /**
  57746. * The current speed of the particle.
  57747. */
  57748. this.velocity = BABYLON.Vector3.Zero();
  57749. /**
  57750. * The pivot point in the particle local space.
  57751. */
  57752. this.pivot = BABYLON.Vector3.Zero();
  57753. /**
  57754. * Must the particle be translated from its pivot point in its local space ?
  57755. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57756. * Default : false
  57757. */
  57758. this.translateFromPivot = false;
  57759. /**
  57760. * Is the particle active or not ?
  57761. */
  57762. this.alive = true;
  57763. /**
  57764. * Is the particle visible or not ?
  57765. */
  57766. this.isVisible = true;
  57767. /**
  57768. * Index of this particle in the global "positions" array (Internal use)
  57769. */
  57770. this._pos = 0;
  57771. /**
  57772. * Index of this particle in the global "indices" array (Internal use)
  57773. */
  57774. this._ind = 0;
  57775. /**
  57776. * ModelShape id of this particle
  57777. */
  57778. this.shapeId = 0;
  57779. /**
  57780. * Index of the particle in its shape id (Internal use)
  57781. */
  57782. this.idxInShape = 0;
  57783. /**
  57784. * Still set as invisible in order to skip useless computations (Internal use)
  57785. */
  57786. this._stillInvisible = false;
  57787. /**
  57788. * Last computed particle rotation matrix
  57789. */
  57790. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57791. /**
  57792. * Parent particle Id, if any.
  57793. * Default null.
  57794. */
  57795. this.parentId = null;
  57796. /**
  57797. * Internal global position in the SPS.
  57798. */
  57799. this._globalPosition = BABYLON.Vector3.Zero();
  57800. this.idx = particleIndex;
  57801. this._pos = positionIndex;
  57802. this._ind = indiceIndex;
  57803. this._model = model;
  57804. this.shapeId = shapeId;
  57805. this.idxInShape = idxInShape;
  57806. this._sps = sps;
  57807. if (modelBoundingInfo) {
  57808. this._modelBoundingInfo = modelBoundingInfo;
  57809. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57810. }
  57811. }
  57812. Object.defineProperty(SolidParticle.prototype, "scale", {
  57813. /**
  57814. * Legacy support, changed scale to scaling
  57815. */
  57816. get: function () {
  57817. return this.scaling;
  57818. },
  57819. /**
  57820. * Legacy support, changed scale to scaling
  57821. */
  57822. set: function (scale) {
  57823. this.scaling = scale;
  57824. },
  57825. enumerable: true,
  57826. configurable: true
  57827. });
  57828. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57829. /**
  57830. * Legacy support, changed quaternion to rotationQuaternion
  57831. */
  57832. get: function () {
  57833. return this.rotationQuaternion;
  57834. },
  57835. /**
  57836. * Legacy support, changed quaternion to rotationQuaternion
  57837. */
  57838. set: function (q) {
  57839. this.rotationQuaternion = q;
  57840. },
  57841. enumerable: true,
  57842. configurable: true
  57843. });
  57844. /**
  57845. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57846. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57847. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57848. * @returns true if it intersects
  57849. */
  57850. SolidParticle.prototype.intersectsMesh = function (target) {
  57851. if (!this._boundingInfo || !target._boundingInfo) {
  57852. return false;
  57853. }
  57854. if (this._sps._bSphereOnly) {
  57855. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57856. }
  57857. return this._boundingInfo.intersects(target._boundingInfo, false);
  57858. };
  57859. return SolidParticle;
  57860. }());
  57861. BABYLON.SolidParticle = SolidParticle;
  57862. /**
  57863. * Represents the shape of the model used by one particle of a solid particle system.
  57864. * SPS internal tool, don't use it manually.
  57865. */
  57866. var ModelShape = /** @class */ (function () {
  57867. /**
  57868. * 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.
  57869. * SPS internal tool, don't use it manually.
  57870. * @hidden
  57871. */
  57872. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57873. /**
  57874. * length of the shape in the model indices array (internal use)
  57875. */
  57876. this._indicesLength = 0;
  57877. this.shapeID = id;
  57878. this._shape = shape;
  57879. this._indicesLength = indicesLength;
  57880. this._shapeUV = shapeUV;
  57881. this._positionFunction = posFunction;
  57882. this._vertexFunction = vtxFunction;
  57883. }
  57884. return ModelShape;
  57885. }());
  57886. BABYLON.ModelShape = ModelShape;
  57887. /**
  57888. * Represents a Depth Sorted Particle in the solid particle system.
  57889. */
  57890. var DepthSortedParticle = /** @class */ (function () {
  57891. function DepthSortedParticle() {
  57892. /**
  57893. * Index of the particle in the "indices" array
  57894. */
  57895. this.ind = 0;
  57896. /**
  57897. * Length of the particle shape in the "indices" array
  57898. */
  57899. this.indicesLength = 0;
  57900. /**
  57901. * Squared distance from the particle to the camera
  57902. */
  57903. this.sqDistance = 0.0;
  57904. }
  57905. return DepthSortedParticle;
  57906. }());
  57907. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57908. })(BABYLON || (BABYLON = {}));
  57909. //# sourceMappingURL=babylon.solidParticle.js.map
  57910. var BABYLON;
  57911. (function (BABYLON) {
  57912. /**
  57913. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57914. *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.
  57915. * The SPS is also a particle system. It provides some methods to manage the particles.
  57916. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57917. *
  57918. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57919. */
  57920. var SolidParticleSystem = /** @class */ (function () {
  57921. /**
  57922. * Creates a SPS (Solid Particle System) object.
  57923. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57924. * @param scene (Scene) is the scene in which the SPS is added.
  57925. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57926. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57927. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57928. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57929. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57930. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57931. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57932. */
  57933. function SolidParticleSystem(name, scene, options) {
  57934. /**
  57935. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57936. * Example : var p = SPS.particles[i];
  57937. */
  57938. this.particles = new Array();
  57939. /**
  57940. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57941. */
  57942. this.nbParticles = 0;
  57943. /**
  57944. * If the particles must ever face the camera (default false). Useful for planar particles.
  57945. */
  57946. this.billboard = false;
  57947. /**
  57948. * Recompute normals when adding a shape
  57949. */
  57950. this.recomputeNormals = true;
  57951. /**
  57952. * This a counter ofr your own usage. It's not set by any SPS functions.
  57953. */
  57954. this.counter = 0;
  57955. /**
  57956. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57957. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57958. */
  57959. this.vars = {};
  57960. /**
  57961. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57962. */
  57963. this._bSphereOnly = false;
  57964. /**
  57965. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57966. */
  57967. this._bSphereRadiusFactor = 1.0;
  57968. this._positions = new Array();
  57969. this._indices = new Array();
  57970. this._normals = new Array();
  57971. this._colors = new Array();
  57972. this._uvs = new Array();
  57973. this._index = 0; // indices index
  57974. this._updatable = true;
  57975. this._pickable = false;
  57976. this._isVisibilityBoxLocked = false;
  57977. this._alwaysVisible = false;
  57978. this._depthSort = false;
  57979. this._shapeCounter = 0;
  57980. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57981. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57982. this._computeParticleColor = true;
  57983. this._computeParticleTexture = true;
  57984. this._computeParticleRotation = true;
  57985. this._computeParticleVertex = false;
  57986. this._computeBoundingBox = false;
  57987. this._depthSortParticles = true;
  57988. this._cam_axisZ = BABYLON.Vector3.Zero();
  57989. this._cam_axisY = BABYLON.Vector3.Zero();
  57990. this._cam_axisX = BABYLON.Vector3.Zero();
  57991. this._axisZ = BABYLON.Axis.Z;
  57992. this._camDir = BABYLON.Vector3.Zero();
  57993. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57994. this._rotMatrix = new BABYLON.Matrix();
  57995. this._invertMatrix = new BABYLON.Matrix();
  57996. this._rotated = BABYLON.Vector3.Zero();
  57997. this._quaternion = new BABYLON.Quaternion();
  57998. this._vertex = BABYLON.Vector3.Zero();
  57999. this._normal = BABYLON.Vector3.Zero();
  58000. this._yaw = 0.0;
  58001. this._pitch = 0.0;
  58002. this._roll = 0.0;
  58003. this._halfroll = 0.0;
  58004. this._halfpitch = 0.0;
  58005. this._halfyaw = 0.0;
  58006. this._sinRoll = 0.0;
  58007. this._cosRoll = 0.0;
  58008. this._sinPitch = 0.0;
  58009. this._cosPitch = 0.0;
  58010. this._sinYaw = 0.0;
  58011. this._cosYaw = 0.0;
  58012. this._mustUnrotateFixedNormals = false;
  58013. this._minimum = BABYLON.Vector3.Zero();
  58014. this._maximum = BABYLON.Vector3.Zero();
  58015. this._minBbox = BABYLON.Vector3.Zero();
  58016. this._maxBbox = BABYLON.Vector3.Zero();
  58017. this._particlesIntersect = false;
  58018. this._depthSortFunction = function (p1, p2) {
  58019. return (p2.sqDistance - p1.sqDistance);
  58020. };
  58021. this._needs32Bits = false;
  58022. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58023. this._scaledPivot = BABYLON.Vector3.Zero();
  58024. this._particleHasParent = false;
  58025. this.name = name;
  58026. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58027. this._camera = scene.activeCamera;
  58028. this._pickable = options ? options.isPickable : false;
  58029. this._depthSort = options ? options.enableDepthSort : false;
  58030. this._particlesIntersect = options ? options.particleIntersection : false;
  58031. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58032. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58033. if (options && options.updatable) {
  58034. this._updatable = options.updatable;
  58035. }
  58036. else {
  58037. this._updatable = true;
  58038. }
  58039. if (this._pickable) {
  58040. this.pickedParticles = [];
  58041. }
  58042. if (this._depthSort) {
  58043. this.depthSortedParticles = [];
  58044. }
  58045. }
  58046. /**
  58047. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58048. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58049. * @returns the created mesh
  58050. */
  58051. SolidParticleSystem.prototype.buildMesh = function () {
  58052. if (this.nbParticles === 0) {
  58053. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58054. this.addShape(triangle, 1);
  58055. triangle.dispose();
  58056. }
  58057. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58058. this._positions32 = new Float32Array(this._positions);
  58059. this._uvs32 = new Float32Array(this._uvs);
  58060. this._colors32 = new Float32Array(this._colors);
  58061. if (this.recomputeNormals) {
  58062. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58063. }
  58064. this._normals32 = new Float32Array(this._normals);
  58065. this._fixedNormal32 = new Float32Array(this._normals);
  58066. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58067. this._unrotateFixedNormals();
  58068. }
  58069. var vertexData = new BABYLON.VertexData();
  58070. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58071. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58072. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58073. if (this._uvs32) {
  58074. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58075. ;
  58076. }
  58077. if (this._colors32) {
  58078. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58079. }
  58080. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58081. vertexData.applyToMesh(mesh, this._updatable);
  58082. this.mesh = mesh;
  58083. this.mesh.isPickable = this._pickable;
  58084. // free memory
  58085. if (!this._depthSort) {
  58086. this._indices = null;
  58087. }
  58088. this._positions = null;
  58089. this._normals = null;
  58090. this._uvs = null;
  58091. this._colors = null;
  58092. if (!this._updatable) {
  58093. this.particles.length = 0;
  58094. }
  58095. return mesh;
  58096. };
  58097. /**
  58098. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58099. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58100. * Thus the particles generated from `digest()` have their property `position` set yet.
  58101. * @param mesh ( Mesh ) is the mesh to be digested
  58102. * @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
  58103. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58104. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58105. * @returns the current SPS
  58106. */
  58107. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58108. var size = (options && options.facetNb) || 1;
  58109. var number = (options && options.number) || 0;
  58110. var delta = (options && options.delta) || 0;
  58111. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58112. var meshInd = mesh.getIndices();
  58113. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58114. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58115. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58116. var f = 0; // facet counter
  58117. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58118. // compute size from number
  58119. if (number) {
  58120. number = (number > totalFacets) ? totalFacets : number;
  58121. size = Math.round(totalFacets / number);
  58122. delta = 0;
  58123. }
  58124. else {
  58125. size = (size > totalFacets) ? totalFacets : size;
  58126. }
  58127. var facetPos = []; // submesh positions
  58128. var facetInd = []; // submesh indices
  58129. var facetUV = []; // submesh UV
  58130. var facetCol = []; // submesh colors
  58131. var barycenter = BABYLON.Vector3.Zero();
  58132. var sizeO = size;
  58133. while (f < totalFacets) {
  58134. size = sizeO + Math.floor((1 + delta) * Math.random());
  58135. if (f > totalFacets - size) {
  58136. size = totalFacets - f;
  58137. }
  58138. // reset temp arrays
  58139. facetPos.length = 0;
  58140. facetInd.length = 0;
  58141. facetUV.length = 0;
  58142. facetCol.length = 0;
  58143. // iterate over "size" facets
  58144. var fi = 0;
  58145. for (var j = f * 3; j < (f + size) * 3; j++) {
  58146. facetInd.push(fi);
  58147. var i = meshInd[j];
  58148. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58149. if (meshUV) {
  58150. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58151. }
  58152. if (meshCol) {
  58153. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58154. }
  58155. fi++;
  58156. }
  58157. // create a model shape for each single particle
  58158. var idx = this.nbParticles;
  58159. var shape = this._posToShape(facetPos);
  58160. var shapeUV = this._uvsToShapeUV(facetUV);
  58161. // compute the barycenter of the shape
  58162. var v;
  58163. for (v = 0; v < shape.length; v++) {
  58164. barycenter.addInPlace(shape[v]);
  58165. }
  58166. barycenter.scaleInPlace(1 / shape.length);
  58167. // shift the shape from its barycenter to the origin
  58168. for (v = 0; v < shape.length; v++) {
  58169. shape[v].subtractInPlace(barycenter);
  58170. }
  58171. var bInfo;
  58172. if (this._particlesIntersect) {
  58173. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58174. }
  58175. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58176. // add the particle in the SPS
  58177. var currentPos = this._positions.length;
  58178. var currentInd = this._indices.length;
  58179. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58180. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58181. // initialize the particle position
  58182. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58183. this._index += shape.length;
  58184. idx++;
  58185. this.nbParticles++;
  58186. this._shapeCounter++;
  58187. f += size;
  58188. }
  58189. return this;
  58190. };
  58191. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58192. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58193. var index = 0;
  58194. var idx = 0;
  58195. for (var p = 0; p < this.particles.length; p++) {
  58196. this._particle = this.particles[p];
  58197. this._shape = this._particle._model._shape;
  58198. if (this._particle.rotationQuaternion) {
  58199. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58200. }
  58201. else {
  58202. this._yaw = this._particle.rotation.y;
  58203. this._pitch = this._particle.rotation.x;
  58204. this._roll = this._particle.rotation.z;
  58205. this._quaternionRotationYPR();
  58206. }
  58207. this._quaternionToRotationMatrix();
  58208. this._rotMatrix.invertToRef(this._invertMatrix);
  58209. for (var pt = 0; pt < this._shape.length; pt++) {
  58210. idx = index + pt * 3;
  58211. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58212. this._fixedNormal32[idx] = this._normal.x;
  58213. this._fixedNormal32[idx + 1] = this._normal.y;
  58214. this._fixedNormal32[idx + 2] = this._normal.z;
  58215. }
  58216. index = idx + 3;
  58217. }
  58218. };
  58219. //reset copy
  58220. SolidParticleSystem.prototype._resetCopy = function () {
  58221. this._copy.position.x = 0;
  58222. this._copy.position.y = 0;
  58223. this._copy.position.z = 0;
  58224. this._copy.rotation.x = 0;
  58225. this._copy.rotation.y = 0;
  58226. this._copy.rotation.z = 0;
  58227. this._copy.rotationQuaternion = null;
  58228. this._copy.scaling.x = 1.0;
  58229. this._copy.scaling.y = 1.0;
  58230. this._copy.scaling.z = 1.0;
  58231. this._copy.uvs.x = 0;
  58232. this._copy.uvs.y = 0;
  58233. this._copy.uvs.z = 1.0;
  58234. this._copy.uvs.w = 1.0;
  58235. this._copy.color = null;
  58236. this._copy.translateFromPivot = false;
  58237. };
  58238. // _meshBuilder : inserts the shape model in the global SPS mesh
  58239. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58240. var i;
  58241. var u = 0;
  58242. var c = 0;
  58243. var n = 0;
  58244. this._resetCopy();
  58245. if (options && options.positionFunction) { // call to custom positionFunction
  58246. options.positionFunction(this._copy, idx, idxInShape);
  58247. this._mustUnrotateFixedNormals = true;
  58248. }
  58249. if (this._copy.rotationQuaternion) {
  58250. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58251. }
  58252. else {
  58253. this._yaw = this._copy.rotation.y;
  58254. this._pitch = this._copy.rotation.x;
  58255. this._roll = this._copy.rotation.z;
  58256. this._quaternionRotationYPR();
  58257. }
  58258. this._quaternionToRotationMatrix();
  58259. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58260. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58261. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58262. if (this._copy.translateFromPivot) {
  58263. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58264. }
  58265. else {
  58266. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58267. }
  58268. for (i = 0; i < shape.length; i++) {
  58269. this._vertex.x = shape[i].x;
  58270. this._vertex.y = shape[i].y;
  58271. this._vertex.z = shape[i].z;
  58272. if (options && options.vertexFunction) {
  58273. options.vertexFunction(this._copy, this._vertex, i);
  58274. }
  58275. this._vertex.x *= this._copy.scaling.x;
  58276. this._vertex.y *= this._copy.scaling.y;
  58277. this._vertex.z *= this._copy.scaling.z;
  58278. this._vertex.x -= this._scaledPivot.x;
  58279. this._vertex.y -= this._scaledPivot.y;
  58280. this._vertex.z -= this._scaledPivot.z;
  58281. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58282. this._rotated.addInPlace(this._pivotBackTranslation);
  58283. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58284. if (meshUV) {
  58285. 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);
  58286. u += 2;
  58287. }
  58288. if (this._copy.color) {
  58289. this._color = this._copy.color;
  58290. }
  58291. else if (meshCol && meshCol[c] !== undefined) {
  58292. this._color.r = meshCol[c];
  58293. this._color.g = meshCol[c + 1];
  58294. this._color.b = meshCol[c + 2];
  58295. this._color.a = meshCol[c + 3];
  58296. }
  58297. else {
  58298. this._color.r = 1.0;
  58299. this._color.g = 1.0;
  58300. this._color.b = 1.0;
  58301. this._color.a = 1.0;
  58302. }
  58303. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58304. c += 4;
  58305. if (!this.recomputeNormals && meshNor) {
  58306. this._normal.x = meshNor[n];
  58307. this._normal.y = meshNor[n + 1];
  58308. this._normal.z = meshNor[n + 2];
  58309. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58310. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58311. n += 3;
  58312. }
  58313. }
  58314. for (i = 0; i < meshInd.length; i++) {
  58315. var current_ind = p + meshInd[i];
  58316. indices.push(current_ind);
  58317. if (current_ind > 65535) {
  58318. this._needs32Bits = true;
  58319. }
  58320. }
  58321. if (this._pickable) {
  58322. var nbfaces = meshInd.length / 3;
  58323. for (i = 0; i < nbfaces; i++) {
  58324. this.pickedParticles.push({ idx: idx, faceId: i });
  58325. }
  58326. }
  58327. if (this._depthSort) {
  58328. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58329. }
  58330. return this._copy;
  58331. };
  58332. // returns a shape array from positions array
  58333. SolidParticleSystem.prototype._posToShape = function (positions) {
  58334. var shape = [];
  58335. for (var i = 0; i < positions.length; i += 3) {
  58336. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58337. }
  58338. return shape;
  58339. };
  58340. // returns a shapeUV array from a Vector4 uvs
  58341. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58342. var shapeUV = [];
  58343. if (uvs) {
  58344. for (var i = 0; i < uvs.length; i++)
  58345. shapeUV.push(uvs[i]);
  58346. }
  58347. return shapeUV;
  58348. };
  58349. // adds a new particle object in the particles array
  58350. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58351. if (bInfo === void 0) { bInfo = null; }
  58352. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58353. this.particles.push(sp);
  58354. return sp;
  58355. };
  58356. /**
  58357. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58358. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58359. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58360. * @param nb (positive integer) the number of particles to be created from this model
  58361. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58362. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58363. * @returns the number of shapes in the system
  58364. */
  58365. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58366. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58367. var meshInd = mesh.getIndices();
  58368. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58369. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58370. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58371. var bbInfo;
  58372. if (this._particlesIntersect) {
  58373. bbInfo = mesh.getBoundingInfo();
  58374. }
  58375. var shape = this._posToShape(meshPos);
  58376. var shapeUV = this._uvsToShapeUV(meshUV);
  58377. var posfunc = options ? options.positionFunction : null;
  58378. var vtxfunc = options ? options.vertexFunction : null;
  58379. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58380. // particles
  58381. var sp;
  58382. var currentCopy;
  58383. var idx = this.nbParticles;
  58384. for (var i = 0; i < nb; i++) {
  58385. var currentPos = this._positions.length;
  58386. var currentInd = this._indices.length;
  58387. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58388. if (this._updatable) {
  58389. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58390. sp.position.copyFrom(currentCopy.position);
  58391. sp.rotation.copyFrom(currentCopy.rotation);
  58392. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58393. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58394. }
  58395. if (currentCopy.color && sp.color) {
  58396. sp.color.copyFrom(currentCopy.color);
  58397. }
  58398. sp.scaling.copyFrom(currentCopy.scaling);
  58399. sp.uvs.copyFrom(currentCopy.uvs);
  58400. }
  58401. this._index += shape.length;
  58402. idx++;
  58403. }
  58404. this.nbParticles += nb;
  58405. this._shapeCounter++;
  58406. return this._shapeCounter - 1;
  58407. };
  58408. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58409. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58410. this._resetCopy();
  58411. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58412. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58413. }
  58414. if (this._copy.rotationQuaternion) {
  58415. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58416. }
  58417. else {
  58418. this._yaw = this._copy.rotation.y;
  58419. this._pitch = this._copy.rotation.x;
  58420. this._roll = this._copy.rotation.z;
  58421. this._quaternionRotationYPR();
  58422. }
  58423. this._quaternionToRotationMatrix();
  58424. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58425. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58426. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58427. if (this._copy.translateFromPivot) {
  58428. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58429. }
  58430. else {
  58431. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58432. }
  58433. this._shape = particle._model._shape;
  58434. for (var pt = 0; pt < this._shape.length; pt++) {
  58435. this._vertex.x = this._shape[pt].x;
  58436. this._vertex.y = this._shape[pt].y;
  58437. this._vertex.z = this._shape[pt].z;
  58438. if (particle._model._vertexFunction) {
  58439. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58440. }
  58441. this._vertex.x *= this._copy.scaling.x;
  58442. this._vertex.y *= this._copy.scaling.y;
  58443. this._vertex.z *= this._copy.scaling.z;
  58444. this._vertex.x -= this._scaledPivot.x;
  58445. this._vertex.y -= this._scaledPivot.y;
  58446. this._vertex.z -= this._scaledPivot.z;
  58447. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58448. this._rotated.addInPlace(this._pivotBackTranslation);
  58449. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58450. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58451. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58452. }
  58453. particle.position.x = 0.0;
  58454. particle.position.y = 0.0;
  58455. particle.position.z = 0.0;
  58456. particle.rotation.x = 0.0;
  58457. particle.rotation.y = 0.0;
  58458. particle.rotation.z = 0.0;
  58459. particle.rotationQuaternion = null;
  58460. particle.scaling.x = 1.0;
  58461. particle.scaling.y = 1.0;
  58462. particle.scaling.z = 1.0;
  58463. particle.uvs.x = 0.0;
  58464. particle.uvs.y = 0.0;
  58465. particle.uvs.z = 1.0;
  58466. particle.uvs.w = 1.0;
  58467. particle.pivot.x = 0.0;
  58468. particle.pivot.y = 0.0;
  58469. particle.pivot.z = 0.0;
  58470. particle.translateFromPivot = false;
  58471. particle.parentId = null;
  58472. };
  58473. /**
  58474. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58475. * @returns the SPS.
  58476. */
  58477. SolidParticleSystem.prototype.rebuildMesh = function () {
  58478. for (var p = 0; p < this.particles.length; p++) {
  58479. this._rebuildParticle(this.particles[p]);
  58480. }
  58481. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58482. return this;
  58483. };
  58484. /**
  58485. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58486. * This method calls `updateParticle()` for each particle of the SPS.
  58487. * For an animated SPS, it is usually called within the render loop.
  58488. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58489. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58490. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58491. * @returns the SPS.
  58492. */
  58493. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58494. if (start === void 0) { start = 0; }
  58495. if (end === void 0) { end = this.nbParticles - 1; }
  58496. if (update === void 0) { update = true; }
  58497. if (!this._updatable) {
  58498. return this;
  58499. }
  58500. // custom beforeUpdate
  58501. this.beforeUpdateParticles(start, end, update);
  58502. this._cam_axisX.x = 1.0;
  58503. this._cam_axisX.y = 0.0;
  58504. this._cam_axisX.z = 0.0;
  58505. this._cam_axisY.x = 0.0;
  58506. this._cam_axisY.y = 1.0;
  58507. this._cam_axisY.z = 0.0;
  58508. this._cam_axisZ.x = 0.0;
  58509. this._cam_axisZ.y = 0.0;
  58510. this._cam_axisZ.z = 1.0;
  58511. // cases when the World Matrix is to be computed first
  58512. if (this.billboard || this._depthSort) {
  58513. this.mesh.computeWorldMatrix(true);
  58514. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58515. }
  58516. // if the particles will always face the camera
  58517. if (this.billboard) {
  58518. // compute the camera position and un-rotate it by the current mesh rotation
  58519. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58520. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58521. this._cam_axisZ.normalize();
  58522. // same for camera up vector extracted from the cam view matrix
  58523. var view = this._camera.getViewMatrix(true);
  58524. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58525. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58526. this._cam_axisY.normalize();
  58527. this._cam_axisX.normalize();
  58528. }
  58529. // if depthSort, compute the camera global position in the mesh local system
  58530. if (this._depthSort) {
  58531. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58532. }
  58533. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58534. var idx = 0; // current position index in the global array positions32
  58535. var index = 0; // position start index in the global array positions32 of the current particle
  58536. var colidx = 0; // current color index in the global array colors32
  58537. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58538. var uvidx = 0; // current uv index in the global array uvs32
  58539. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58540. var pt = 0; // current index in the particle model shape
  58541. if (this.mesh.isFacetDataEnabled) {
  58542. this._computeBoundingBox = true;
  58543. }
  58544. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58545. if (this._computeBoundingBox) {
  58546. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58547. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58548. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58549. }
  58550. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58551. if (this.mesh._boundingInfo) {
  58552. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58553. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58554. }
  58555. }
  58556. }
  58557. // particle loop
  58558. index = this.particles[start]._pos;
  58559. var vpos = (index / 3) | 0;
  58560. colorIndex = vpos * 4;
  58561. uvIndex = vpos * 2;
  58562. for (var p = start; p <= end; p++) {
  58563. this._particle = this.particles[p];
  58564. this._shape = this._particle._model._shape;
  58565. this._shapeUV = this._particle._model._shapeUV;
  58566. // call to custom user function to update the particle properties
  58567. this.updateParticle(this._particle);
  58568. // camera-particle distance for depth sorting
  58569. if (this._depthSort && this._depthSortParticles) {
  58570. var dsp = this.depthSortedParticles[p];
  58571. dsp.ind = this._particle._ind;
  58572. dsp.indicesLength = this._particle._model._indicesLength;
  58573. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58574. }
  58575. // skip the computations for inactive or already invisible particles
  58576. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58577. // increment indexes for the next particle
  58578. pt = this._shape.length;
  58579. index += pt * 3;
  58580. colorIndex += pt * 4;
  58581. uvIndex += pt * 2;
  58582. continue;
  58583. }
  58584. if (this._particle.isVisible) {
  58585. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58586. this._particleHasParent = (this._particle.parentId !== null);
  58587. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58588. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58589. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58590. // particle rotation matrix
  58591. if (this.billboard) {
  58592. this._particle.rotation.x = 0.0;
  58593. this._particle.rotation.y = 0.0;
  58594. }
  58595. if (this._computeParticleRotation || this.billboard) {
  58596. if (this._particle.rotationQuaternion) {
  58597. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58598. }
  58599. else {
  58600. this._yaw = this._particle.rotation.y;
  58601. this._pitch = this._particle.rotation.x;
  58602. this._roll = this._particle.rotation.z;
  58603. this._quaternionRotationYPR();
  58604. }
  58605. this._quaternionToRotationMatrix();
  58606. }
  58607. if (this._particleHasParent) {
  58608. this._parent = this.particles[this._particle.parentId];
  58609. 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];
  58610. 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];
  58611. 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];
  58612. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58613. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58614. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58615. if (this._computeParticleRotation || this.billboard) {
  58616. 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];
  58617. 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];
  58618. 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];
  58619. 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];
  58620. 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];
  58621. 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];
  58622. 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];
  58623. 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];
  58624. 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];
  58625. }
  58626. }
  58627. else {
  58628. this._particle._globalPosition.x = this._particle.position.x;
  58629. this._particle._globalPosition.y = this._particle.position.y;
  58630. this._particle._globalPosition.z = this._particle.position.z;
  58631. if (this._computeParticleRotation || this.billboard) {
  58632. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58633. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58634. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58635. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58636. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58637. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58638. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58639. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58640. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58641. }
  58642. }
  58643. if (this._particle.translateFromPivot) {
  58644. this._pivotBackTranslation.x = 0.0;
  58645. this._pivotBackTranslation.y = 0.0;
  58646. this._pivotBackTranslation.z = 0.0;
  58647. }
  58648. else {
  58649. this._pivotBackTranslation.x = this._scaledPivot.x;
  58650. this._pivotBackTranslation.y = this._scaledPivot.y;
  58651. this._pivotBackTranslation.z = this._scaledPivot.z;
  58652. }
  58653. // particle vertex loop
  58654. for (pt = 0; pt < this._shape.length; pt++) {
  58655. idx = index + pt * 3;
  58656. colidx = colorIndex + pt * 4;
  58657. uvidx = uvIndex + pt * 2;
  58658. this._vertex.x = this._shape[pt].x;
  58659. this._vertex.y = this._shape[pt].y;
  58660. this._vertex.z = this._shape[pt].z;
  58661. if (this._computeParticleVertex) {
  58662. this.updateParticleVertex(this._particle, this._vertex, pt);
  58663. }
  58664. // positions
  58665. this._vertex.x *= this._particle.scaling.x;
  58666. this._vertex.y *= this._particle.scaling.y;
  58667. this._vertex.z *= this._particle.scaling.z;
  58668. this._vertex.x -= this._scaledPivot.x;
  58669. this._vertex.y -= this._scaledPivot.y;
  58670. this._vertex.z -= this._scaledPivot.z;
  58671. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58672. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58673. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58674. this._rotated.x += this._pivotBackTranslation.x;
  58675. this._rotated.y += this._pivotBackTranslation.y;
  58676. this._rotated.z += this._pivotBackTranslation.z;
  58677. 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;
  58678. 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;
  58679. 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;
  58680. if (this._computeBoundingBox) {
  58681. if (this._positions32[idx] < this._minimum.x) {
  58682. this._minimum.x = this._positions32[idx];
  58683. }
  58684. if (this._positions32[idx] > this._maximum.x) {
  58685. this._maximum.x = this._positions32[idx];
  58686. }
  58687. if (this._positions32[idx + 1] < this._minimum.y) {
  58688. this._minimum.y = this._positions32[idx + 1];
  58689. }
  58690. if (this._positions32[idx + 1] > this._maximum.y) {
  58691. this._maximum.y = this._positions32[idx + 1];
  58692. }
  58693. if (this._positions32[idx + 2] < this._minimum.z) {
  58694. this._minimum.z = this._positions32[idx + 2];
  58695. }
  58696. if (this._positions32[idx + 2] > this._maximum.z) {
  58697. this._maximum.z = this._positions32[idx + 2];
  58698. }
  58699. }
  58700. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58701. if (!this._computeParticleVertex) {
  58702. this._normal.x = this._fixedNormal32[idx];
  58703. this._normal.y = this._fixedNormal32[idx + 1];
  58704. this._normal.z = this._fixedNormal32[idx + 2];
  58705. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58706. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58707. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58708. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58709. 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;
  58710. 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;
  58711. }
  58712. if (this._computeParticleColor && this._particle.color) {
  58713. this._colors32[colidx] = this._particle.color.r;
  58714. this._colors32[colidx + 1] = this._particle.color.g;
  58715. this._colors32[colidx + 2] = this._particle.color.b;
  58716. this._colors32[colidx + 3] = this._particle.color.a;
  58717. }
  58718. if (this._computeParticleTexture) {
  58719. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58720. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58721. }
  58722. }
  58723. }
  58724. // particle just set invisible : scaled to zero and positioned at the origin
  58725. else {
  58726. this._particle._stillInvisible = true; // mark the particle as invisible
  58727. for (pt = 0; pt < this._shape.length; pt++) {
  58728. idx = index + pt * 3;
  58729. colidx = colorIndex + pt * 4;
  58730. uvidx = uvIndex + pt * 2;
  58731. this._positions32[idx] = 0.0;
  58732. this._positions32[idx + 1] = 0.0;
  58733. this._positions32[idx + 2] = 0.0;
  58734. this._normals32[idx] = 0.0;
  58735. this._normals32[idx + 1] = 0.0;
  58736. this._normals32[idx + 2] = 0.0;
  58737. if (this._computeParticleColor && this._particle.color) {
  58738. this._colors32[colidx] = this._particle.color.r;
  58739. this._colors32[colidx + 1] = this._particle.color.g;
  58740. this._colors32[colidx + 2] = this._particle.color.b;
  58741. this._colors32[colidx + 3] = this._particle.color.a;
  58742. }
  58743. if (this._computeParticleTexture) {
  58744. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58745. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58746. }
  58747. }
  58748. }
  58749. // if the particle intersections must be computed : update the bbInfo
  58750. if (this._particlesIntersect) {
  58751. var bInfo = this._particle._boundingInfo;
  58752. var bBox = bInfo.boundingBox;
  58753. var bSphere = bInfo.boundingSphere;
  58754. if (!this._bSphereOnly) {
  58755. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58756. for (var b = 0; b < bBox.vectors.length; b++) {
  58757. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58758. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58759. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58760. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58761. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58762. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58763. 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;
  58764. 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;
  58765. 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;
  58766. }
  58767. bBox._update(this.mesh._worldMatrix);
  58768. }
  58769. // place and scale the particle bouding sphere in the SPS local system, then update it
  58770. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58771. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58772. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58773. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58774. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58775. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58776. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58777. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58778. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58779. 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));
  58780. bSphere._update(this.mesh._worldMatrix);
  58781. }
  58782. // increment indexes for the next particle
  58783. index = idx + 3;
  58784. colorIndex = colidx + 4;
  58785. uvIndex = uvidx + 2;
  58786. }
  58787. // if the VBO must be updated
  58788. if (update) {
  58789. if (this._computeParticleColor) {
  58790. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58791. }
  58792. if (this._computeParticleTexture) {
  58793. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58794. }
  58795. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58796. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58797. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58798. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58799. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58800. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58801. for (var i = 0; i < this._normals32.length; i++) {
  58802. this._fixedNormal32[i] = this._normals32[i];
  58803. }
  58804. }
  58805. if (!this.mesh.areNormalsFrozen) {
  58806. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58807. }
  58808. }
  58809. if (this._depthSort && this._depthSortParticles) {
  58810. this.depthSortedParticles.sort(this._depthSortFunction);
  58811. var dspl = this.depthSortedParticles.length;
  58812. var sorted = 0;
  58813. var lind = 0;
  58814. var sind = 0;
  58815. var sid = 0;
  58816. for (sorted = 0; sorted < dspl; sorted++) {
  58817. lind = this.depthSortedParticles[sorted].indicesLength;
  58818. sind = this.depthSortedParticles[sorted].ind;
  58819. for (var i = 0; i < lind; i++) {
  58820. this._indices32[sid] = this._indices[sind + i];
  58821. sid++;
  58822. }
  58823. }
  58824. this.mesh.updateIndices(this._indices32);
  58825. }
  58826. }
  58827. if (this._computeBoundingBox) {
  58828. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58829. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58830. }
  58831. this.afterUpdateParticles(start, end, update);
  58832. return this;
  58833. };
  58834. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58835. this._halfroll = this._roll * 0.5;
  58836. this._halfpitch = this._pitch * 0.5;
  58837. this._halfyaw = this._yaw * 0.5;
  58838. this._sinRoll = Math.sin(this._halfroll);
  58839. this._cosRoll = Math.cos(this._halfroll);
  58840. this._sinPitch = Math.sin(this._halfpitch);
  58841. this._cosPitch = Math.cos(this._halfpitch);
  58842. this._sinYaw = Math.sin(this._halfyaw);
  58843. this._cosYaw = Math.cos(this._halfyaw);
  58844. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58845. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58846. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58847. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58848. };
  58849. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58850. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58851. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58852. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58853. this._rotMatrix.m[3] = 0;
  58854. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58855. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58856. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58857. this._rotMatrix.m[7] = 0;
  58858. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58859. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58860. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58861. this._rotMatrix.m[11] = 0;
  58862. this._rotMatrix.m[12] = 0;
  58863. this._rotMatrix.m[13] = 0;
  58864. this._rotMatrix.m[14] = 0;
  58865. this._rotMatrix.m[15] = 1.0;
  58866. };
  58867. /**
  58868. * Disposes the SPS.
  58869. */
  58870. SolidParticleSystem.prototype.dispose = function () {
  58871. this.mesh.dispose();
  58872. this.vars = null;
  58873. // drop references to internal big arrays for the GC
  58874. this._positions = null;
  58875. this._indices = null;
  58876. this._normals = null;
  58877. this._uvs = null;
  58878. this._colors = null;
  58879. this._indices32 = null;
  58880. this._positions32 = null;
  58881. this._normals32 = null;
  58882. this._fixedNormal32 = null;
  58883. this._uvs32 = null;
  58884. this._colors32 = null;
  58885. this.pickedParticles = null;
  58886. };
  58887. /**
  58888. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58889. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58890. * @returns the SPS.
  58891. */
  58892. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58893. if (!this._isVisibilityBoxLocked) {
  58894. this.mesh.refreshBoundingInfo();
  58895. }
  58896. return this;
  58897. };
  58898. /**
  58899. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58900. * @param size the size (float) of the visibility box
  58901. * note : this doesn't lock the SPS mesh bounding box.
  58902. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58903. */
  58904. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58905. var vis = size / 2;
  58906. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58907. };
  58908. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58909. /**
  58910. * Gets whether the SPS as always visible or not
  58911. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58912. */
  58913. get: function () {
  58914. return this._alwaysVisible;
  58915. },
  58916. /**
  58917. * Sets the SPS as always visible or not
  58918. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58919. */
  58920. set: function (val) {
  58921. this._alwaysVisible = val;
  58922. this.mesh.alwaysSelectAsActiveMesh = val;
  58923. },
  58924. enumerable: true,
  58925. configurable: true
  58926. });
  58927. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58928. /**
  58929. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58930. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58931. */
  58932. get: function () {
  58933. return this._isVisibilityBoxLocked;
  58934. },
  58935. /**
  58936. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58937. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58938. */
  58939. set: function (val) {
  58940. this._isVisibilityBoxLocked = val;
  58941. var boundingInfo = this.mesh.getBoundingInfo();
  58942. boundingInfo.isLocked = val;
  58943. },
  58944. enumerable: true,
  58945. configurable: true
  58946. });
  58947. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58948. /**
  58949. * Gets if `setParticles()` computes the particle rotations or not.
  58950. * Default value : true. The SPS is faster when it's set to false.
  58951. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58952. */
  58953. get: function () {
  58954. return this._computeParticleRotation;
  58955. },
  58956. /**
  58957. * Tells to `setParticles()` to compute the particle rotations or not.
  58958. * Default value : true. The SPS is faster when it's set to false.
  58959. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58960. */
  58961. set: function (val) {
  58962. this._computeParticleRotation = val;
  58963. },
  58964. enumerable: true,
  58965. configurable: true
  58966. });
  58967. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58968. /**
  58969. * Gets if `setParticles()` computes the particle colors or not.
  58970. * Default value : true. The SPS is faster when it's set to false.
  58971. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58972. */
  58973. get: function () {
  58974. return this._computeParticleColor;
  58975. },
  58976. /**
  58977. * Tells to `setParticles()` to compute the particle colors or not.
  58978. * Default value : true. The SPS is faster when it's set to false.
  58979. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58980. */
  58981. set: function (val) {
  58982. this._computeParticleColor = val;
  58983. },
  58984. enumerable: true,
  58985. configurable: true
  58986. });
  58987. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58988. /**
  58989. * Gets if `setParticles()` computes the particle textures or not.
  58990. * Default value : true. The SPS is faster when it's set to false.
  58991. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58992. */
  58993. get: function () {
  58994. return this._computeParticleTexture;
  58995. },
  58996. set: function (val) {
  58997. this._computeParticleTexture = val;
  58998. },
  58999. enumerable: true,
  59000. configurable: true
  59001. });
  59002. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59003. /**
  59004. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59005. * Default value : false. The SPS is faster when it's set to false.
  59006. * Note : the particle custom vertex positions aren't stored values.
  59007. */
  59008. get: function () {
  59009. return this._computeParticleVertex;
  59010. },
  59011. /**
  59012. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59013. * Default value : false. The SPS is faster when it's set to false.
  59014. * Note : the particle custom vertex positions aren't stored values.
  59015. */
  59016. set: function (val) {
  59017. this._computeParticleVertex = val;
  59018. },
  59019. enumerable: true,
  59020. configurable: true
  59021. });
  59022. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59023. /**
  59024. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59025. */
  59026. get: function () {
  59027. return this._computeBoundingBox;
  59028. },
  59029. /**
  59030. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59031. */
  59032. set: function (val) {
  59033. this._computeBoundingBox = val;
  59034. },
  59035. enumerable: true,
  59036. configurable: true
  59037. });
  59038. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59039. /**
  59040. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59041. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59042. * Default : `true`
  59043. */
  59044. get: function () {
  59045. return this._depthSortParticles;
  59046. },
  59047. /**
  59048. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59049. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59050. * Default : `true`
  59051. */
  59052. set: function (val) {
  59053. this._depthSortParticles = val;
  59054. },
  59055. enumerable: true,
  59056. configurable: true
  59057. });
  59058. // =======================================================================
  59059. // Particle behavior logic
  59060. // these following methods may be overwritten by the user to fit his needs
  59061. /**
  59062. * This function does nothing. It may be overwritten to set all the particle first values.
  59063. * The SPS doesn't call this function, you may have to call it by your own.
  59064. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59065. */
  59066. SolidParticleSystem.prototype.initParticles = function () {
  59067. };
  59068. /**
  59069. * This function does nothing. It may be overwritten to recycle a particle.
  59070. * The SPS doesn't call this function, you may have to call it by your own.
  59071. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59072. * @param particle The particle to recycle
  59073. * @returns the recycled particle
  59074. */
  59075. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59076. return particle;
  59077. };
  59078. /**
  59079. * Updates a particle : this function should be overwritten by the user.
  59080. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59081. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59082. * @example : just set a particle position or velocity and recycle conditions
  59083. * @param particle The particle to update
  59084. * @returns the updated particle
  59085. */
  59086. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59087. return particle;
  59088. };
  59089. /**
  59090. * Updates a vertex of a particle : it can be overwritten by the user.
  59091. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59092. * @param particle the current particle
  59093. * @param vertex the current index of the current particle
  59094. * @param pt the index of the current vertex in the particle shape
  59095. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59096. * @example : just set a vertex particle position
  59097. * @returns the updated vertex
  59098. */
  59099. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59100. return vertex;
  59101. };
  59102. /**
  59103. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59104. * This does nothing and may be overwritten by the user.
  59105. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59106. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59107. * @param update the boolean update value actually passed to setParticles()
  59108. */
  59109. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59110. };
  59111. /**
  59112. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59113. * This will be passed three parameters.
  59114. * This does nothing and may be overwritten by the user.
  59115. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59116. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59117. * @param update the boolean update value actually passed to setParticles()
  59118. */
  59119. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59120. };
  59121. return SolidParticleSystem;
  59122. }());
  59123. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59124. })(BABYLON || (BABYLON = {}));
  59125. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59126. var BABYLON;
  59127. (function (BABYLON) {
  59128. var ShaderMaterial = /** @class */ (function (_super) {
  59129. __extends(ShaderMaterial, _super);
  59130. function ShaderMaterial(name, scene, shaderPath, options) {
  59131. var _this = _super.call(this, name, scene) || this;
  59132. _this._textures = {};
  59133. _this._textureArrays = {};
  59134. _this._floats = {};
  59135. _this._ints = {};
  59136. _this._floatsArrays = {};
  59137. _this._colors3 = {};
  59138. _this._colors3Arrays = {};
  59139. _this._colors4 = {};
  59140. _this._vectors2 = {};
  59141. _this._vectors3 = {};
  59142. _this._vectors4 = {};
  59143. _this._matrices = {};
  59144. _this._matrices3x3 = {};
  59145. _this._matrices2x2 = {};
  59146. _this._vectors2Arrays = {};
  59147. _this._vectors3Arrays = {};
  59148. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59149. _this._shaderPath = shaderPath;
  59150. options.needAlphaBlending = options.needAlphaBlending || false;
  59151. options.needAlphaTesting = options.needAlphaTesting || false;
  59152. options.attributes = options.attributes || ["position", "normal", "uv"];
  59153. options.uniforms = options.uniforms || ["worldViewProjection"];
  59154. options.uniformBuffers = options.uniformBuffers || [];
  59155. options.samplers = options.samplers || [];
  59156. options.defines = options.defines || [];
  59157. _this._options = options;
  59158. return _this;
  59159. }
  59160. ShaderMaterial.prototype.getClassName = function () {
  59161. return "ShaderMaterial";
  59162. };
  59163. ShaderMaterial.prototype.needAlphaBlending = function () {
  59164. return this._options.needAlphaBlending;
  59165. };
  59166. ShaderMaterial.prototype.needAlphaTesting = function () {
  59167. return this._options.needAlphaTesting;
  59168. };
  59169. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59170. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59171. this._options.uniforms.push(uniformName);
  59172. }
  59173. };
  59174. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59175. if (this._options.samplers.indexOf(name) === -1) {
  59176. this._options.samplers.push(name);
  59177. }
  59178. this._textures[name] = texture;
  59179. return this;
  59180. };
  59181. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59182. if (this._options.samplers.indexOf(name) === -1) {
  59183. this._options.samplers.push(name);
  59184. }
  59185. this._checkUniform(name);
  59186. this._textureArrays[name] = textures;
  59187. return this;
  59188. };
  59189. ShaderMaterial.prototype.setFloat = function (name, value) {
  59190. this._checkUniform(name);
  59191. this._floats[name] = value;
  59192. return this;
  59193. };
  59194. ShaderMaterial.prototype.setInt = function (name, value) {
  59195. this._checkUniform(name);
  59196. this._ints[name] = value;
  59197. return this;
  59198. };
  59199. ShaderMaterial.prototype.setFloats = function (name, value) {
  59200. this._checkUniform(name);
  59201. this._floatsArrays[name] = value;
  59202. return this;
  59203. };
  59204. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59205. this._checkUniform(name);
  59206. this._colors3[name] = value;
  59207. return this;
  59208. };
  59209. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59210. this._checkUniform(name);
  59211. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59212. color.toArray(arr, arr.length);
  59213. return arr;
  59214. }, []);
  59215. return this;
  59216. };
  59217. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59218. this._checkUniform(name);
  59219. this._colors4[name] = value;
  59220. return this;
  59221. };
  59222. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59223. this._checkUniform(name);
  59224. this._vectors2[name] = value;
  59225. return this;
  59226. };
  59227. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59228. this._checkUniform(name);
  59229. this._vectors3[name] = value;
  59230. return this;
  59231. };
  59232. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59233. this._checkUniform(name);
  59234. this._vectors4[name] = value;
  59235. return this;
  59236. };
  59237. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59238. this._checkUniform(name);
  59239. this._matrices[name] = value;
  59240. return this;
  59241. };
  59242. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59243. this._checkUniform(name);
  59244. this._matrices3x3[name] = value;
  59245. return this;
  59246. };
  59247. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59248. this._checkUniform(name);
  59249. this._matrices2x2[name] = value;
  59250. return this;
  59251. };
  59252. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59253. this._checkUniform(name);
  59254. this._vectors2Arrays[name] = value;
  59255. return this;
  59256. };
  59257. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59258. this._checkUniform(name);
  59259. this._vectors3Arrays[name] = value;
  59260. return this;
  59261. };
  59262. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59263. if (!mesh) {
  59264. return true;
  59265. }
  59266. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59267. return false;
  59268. }
  59269. return false;
  59270. };
  59271. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59272. var scene = this.getScene();
  59273. var engine = scene.getEngine();
  59274. if (!this.checkReadyOnEveryCall) {
  59275. if (this._renderId === scene.getRenderId()) {
  59276. if (this._checkCache(scene, mesh, useInstances)) {
  59277. return true;
  59278. }
  59279. }
  59280. }
  59281. // Instances
  59282. var defines = [];
  59283. var attribs = [];
  59284. var fallbacks = new BABYLON.EffectFallbacks();
  59285. if (useInstances) {
  59286. defines.push("#define INSTANCES");
  59287. }
  59288. for (var index = 0; index < this._options.defines.length; index++) {
  59289. defines.push(this._options.defines[index]);
  59290. }
  59291. for (var index = 0; index < this._options.attributes.length; index++) {
  59292. attribs.push(this._options.attributes[index]);
  59293. }
  59294. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59295. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59296. defines.push("#define VERTEXCOLOR");
  59297. }
  59298. // Bones
  59299. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59300. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59301. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59302. if (mesh.numBoneInfluencers > 4) {
  59303. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59304. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59305. }
  59306. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59307. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59308. fallbacks.addCPUSkinningFallback(0, mesh);
  59309. if (this._options.uniforms.indexOf("mBones") === -1) {
  59310. this._options.uniforms.push("mBones");
  59311. }
  59312. }
  59313. else {
  59314. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59315. }
  59316. // Textures
  59317. for (var name in this._textures) {
  59318. if (!this._textures[name].isReady()) {
  59319. return false;
  59320. }
  59321. }
  59322. // Alpha test
  59323. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59324. defines.push("#define ALPHATEST");
  59325. }
  59326. var previousEffect = this._effect;
  59327. var join = defines.join("\n");
  59328. this._effect = engine.createEffect(this._shaderPath, {
  59329. attributes: attribs,
  59330. uniformsNames: this._options.uniforms,
  59331. uniformBuffersNames: this._options.uniformBuffers,
  59332. samplers: this._options.samplers,
  59333. defines: join,
  59334. fallbacks: fallbacks,
  59335. onCompiled: this.onCompiled,
  59336. onError: this.onError
  59337. }, engine);
  59338. if (!this._effect.isReady()) {
  59339. return false;
  59340. }
  59341. if (previousEffect !== this._effect) {
  59342. scene.resetCachedMaterial();
  59343. }
  59344. this._renderId = scene.getRenderId();
  59345. return true;
  59346. };
  59347. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59348. var scene = this.getScene();
  59349. if (!this._effect) {
  59350. return;
  59351. }
  59352. if (this._options.uniforms.indexOf("world") !== -1) {
  59353. this._effect.setMatrix("world", world);
  59354. }
  59355. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59356. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59357. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59358. }
  59359. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59360. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59361. }
  59362. };
  59363. ShaderMaterial.prototype.bind = function (world, mesh) {
  59364. // Std values
  59365. this.bindOnlyWorldMatrix(world);
  59366. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59367. if (this._options.uniforms.indexOf("view") !== -1) {
  59368. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59369. }
  59370. if (this._options.uniforms.indexOf("projection") !== -1) {
  59371. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59372. }
  59373. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59374. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59375. }
  59376. // Bones
  59377. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59378. var name;
  59379. // Texture
  59380. for (name in this._textures) {
  59381. this._effect.setTexture(name, this._textures[name]);
  59382. }
  59383. // Texture arrays
  59384. for (name in this._textureArrays) {
  59385. this._effect.setTextureArray(name, this._textureArrays[name]);
  59386. }
  59387. // Int
  59388. for (name in this._ints) {
  59389. this._effect.setInt(name, this._ints[name]);
  59390. }
  59391. // Float
  59392. for (name in this._floats) {
  59393. this._effect.setFloat(name, this._floats[name]);
  59394. }
  59395. // Floats
  59396. for (name in this._floatsArrays) {
  59397. this._effect.setArray(name, this._floatsArrays[name]);
  59398. }
  59399. // Color3
  59400. for (name in this._colors3) {
  59401. this._effect.setColor3(name, this._colors3[name]);
  59402. }
  59403. for (name in this._colors3Arrays) {
  59404. this._effect.setArray3(name, this._colors3Arrays[name]);
  59405. }
  59406. // Color4
  59407. for (name in this._colors4) {
  59408. var color = this._colors4[name];
  59409. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59410. }
  59411. // Vector2
  59412. for (name in this._vectors2) {
  59413. this._effect.setVector2(name, this._vectors2[name]);
  59414. }
  59415. // Vector3
  59416. for (name in this._vectors3) {
  59417. this._effect.setVector3(name, this._vectors3[name]);
  59418. }
  59419. // Vector4
  59420. for (name in this._vectors4) {
  59421. this._effect.setVector4(name, this._vectors4[name]);
  59422. }
  59423. // Matrix
  59424. for (name in this._matrices) {
  59425. this._effect.setMatrix(name, this._matrices[name]);
  59426. }
  59427. // Matrix 3x3
  59428. for (name in this._matrices3x3) {
  59429. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59430. }
  59431. // Matrix 2x2
  59432. for (name in this._matrices2x2) {
  59433. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59434. }
  59435. // Vector2Array
  59436. for (name in this._vectors2Arrays) {
  59437. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59438. }
  59439. // Vector3Array
  59440. for (name in this._vectors3Arrays) {
  59441. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59442. }
  59443. }
  59444. this._afterBind(mesh);
  59445. };
  59446. ShaderMaterial.prototype.getActiveTextures = function () {
  59447. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59448. for (var name in this._textures) {
  59449. activeTextures.push(this._textures[name]);
  59450. }
  59451. for (var name in this._textureArrays) {
  59452. var array = this._textureArrays[name];
  59453. for (var index = 0; index < array.length; index++) {
  59454. activeTextures.push(array[index]);
  59455. }
  59456. }
  59457. return activeTextures;
  59458. };
  59459. ShaderMaterial.prototype.hasTexture = function (texture) {
  59460. if (_super.prototype.hasTexture.call(this, texture)) {
  59461. return true;
  59462. }
  59463. for (var name in this._textures) {
  59464. if (this._textures[name] === texture) {
  59465. return true;
  59466. }
  59467. }
  59468. for (var name in this._textureArrays) {
  59469. var array = this._textureArrays[name];
  59470. for (var index = 0; index < array.length; index++) {
  59471. if (array[index] === texture) {
  59472. return true;
  59473. }
  59474. }
  59475. }
  59476. return false;
  59477. };
  59478. ShaderMaterial.prototype.clone = function (name) {
  59479. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59480. return newShaderMaterial;
  59481. };
  59482. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59483. if (forceDisposeTextures) {
  59484. var name;
  59485. for (name in this._textures) {
  59486. this._textures[name].dispose();
  59487. }
  59488. for (name in this._textureArrays) {
  59489. var array = this._textureArrays[name];
  59490. for (var index = 0; index < array.length; index++) {
  59491. array[index].dispose();
  59492. }
  59493. }
  59494. }
  59495. this._textures = {};
  59496. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59497. };
  59498. ShaderMaterial.prototype.serialize = function () {
  59499. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59500. serializationObject.customType = "BABYLON.ShaderMaterial";
  59501. serializationObject.options = this._options;
  59502. serializationObject.shaderPath = this._shaderPath;
  59503. var name;
  59504. // Texture
  59505. serializationObject.textures = {};
  59506. for (name in this._textures) {
  59507. serializationObject.textures[name] = this._textures[name].serialize();
  59508. }
  59509. // Texture arrays
  59510. serializationObject.textureArrays = {};
  59511. for (name in this._textureArrays) {
  59512. serializationObject.textureArrays[name] = [];
  59513. var array = this._textureArrays[name];
  59514. for (var index = 0; index < array.length; index++) {
  59515. serializationObject.textureArrays[name].push(array[index].serialize());
  59516. }
  59517. }
  59518. // Float
  59519. serializationObject.floats = {};
  59520. for (name in this._floats) {
  59521. serializationObject.floats[name] = this._floats[name];
  59522. }
  59523. // Float s
  59524. serializationObject.FloatArrays = {};
  59525. for (name in this._floatsArrays) {
  59526. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59527. }
  59528. // Color3
  59529. serializationObject.colors3 = {};
  59530. for (name in this._colors3) {
  59531. serializationObject.colors3[name] = this._colors3[name].asArray();
  59532. }
  59533. // Color3 array
  59534. serializationObject.colors3Arrays = {};
  59535. for (name in this._colors3Arrays) {
  59536. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59537. }
  59538. // Color4
  59539. serializationObject.colors4 = {};
  59540. for (name in this._colors4) {
  59541. serializationObject.colors4[name] = this._colors4[name].asArray();
  59542. }
  59543. // Vector2
  59544. serializationObject.vectors2 = {};
  59545. for (name in this._vectors2) {
  59546. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59547. }
  59548. // Vector3
  59549. serializationObject.vectors3 = {};
  59550. for (name in this._vectors3) {
  59551. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59552. }
  59553. // Vector4
  59554. serializationObject.vectors4 = {};
  59555. for (name in this._vectors4) {
  59556. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59557. }
  59558. // Matrix
  59559. serializationObject.matrices = {};
  59560. for (name in this._matrices) {
  59561. serializationObject.matrices[name] = this._matrices[name].asArray();
  59562. }
  59563. // Matrix 3x3
  59564. serializationObject.matrices3x3 = {};
  59565. for (name in this._matrices3x3) {
  59566. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59567. }
  59568. // Matrix 2x2
  59569. serializationObject.matrices2x2 = {};
  59570. for (name in this._matrices2x2) {
  59571. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59572. }
  59573. // Vector2Array
  59574. serializationObject.vectors2Arrays = {};
  59575. for (name in this._vectors2Arrays) {
  59576. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59577. }
  59578. // Vector3Array
  59579. serializationObject.vectors3Arrays = {};
  59580. for (name in this._vectors3Arrays) {
  59581. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59582. }
  59583. return serializationObject;
  59584. };
  59585. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59586. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59587. var name;
  59588. // Texture
  59589. for (name in source.textures) {
  59590. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59591. }
  59592. // Texture arrays
  59593. for (name in source.textureArrays) {
  59594. var array = source.textureArrays[name];
  59595. var textureArray = new Array();
  59596. for (var index = 0; index < array.length; index++) {
  59597. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59598. }
  59599. material.setTextureArray(name, textureArray);
  59600. }
  59601. // Float
  59602. for (name in source.floats) {
  59603. material.setFloat(name, source.floats[name]);
  59604. }
  59605. // Float s
  59606. for (name in source.floatsArrays) {
  59607. material.setFloats(name, source.floatsArrays[name]);
  59608. }
  59609. // Color3
  59610. for (name in source.colors3) {
  59611. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59612. }
  59613. // Color3 arrays
  59614. for (name in source.colors3Arrays) {
  59615. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59616. if (i % 3 === 0) {
  59617. arr.push([num]);
  59618. }
  59619. else {
  59620. arr[arr.length - 1].push(num);
  59621. }
  59622. return arr;
  59623. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59624. material.setColor3Array(name, colors);
  59625. }
  59626. // Color4
  59627. for (name in source.colors4) {
  59628. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59629. }
  59630. // Vector2
  59631. for (name in source.vectors2) {
  59632. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59633. }
  59634. // Vector3
  59635. for (name in source.vectors3) {
  59636. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59637. }
  59638. // Vector4
  59639. for (name in source.vectors4) {
  59640. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59641. }
  59642. // Matrix
  59643. for (name in source.matrices) {
  59644. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59645. }
  59646. // Matrix 3x3
  59647. for (name in source.matrices3x3) {
  59648. material.setMatrix3x3(name, source.matrices3x3[name]);
  59649. }
  59650. // Matrix 2x2
  59651. for (name in source.matrices2x2) {
  59652. material.setMatrix2x2(name, source.matrices2x2[name]);
  59653. }
  59654. // Vector2Array
  59655. for (name in source.vectors2Arrays) {
  59656. material.setArray2(name, source.vectors2Arrays[name]);
  59657. }
  59658. // Vector3Array
  59659. for (name in source.vectors3Arrays) {
  59660. material.setArray3(name, source.vectors3Arrays[name]);
  59661. }
  59662. return material;
  59663. };
  59664. return ShaderMaterial;
  59665. }(BABYLON.Material));
  59666. BABYLON.ShaderMaterial = ShaderMaterial;
  59667. })(BABYLON || (BABYLON = {}));
  59668. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59669. var BABYLON;
  59670. (function (BABYLON) {
  59671. var GroundMesh = /** @class */ (function (_super) {
  59672. __extends(GroundMesh, _super);
  59673. function GroundMesh(name, scene) {
  59674. var _this = _super.call(this, name, scene) || this;
  59675. _this.generateOctree = false;
  59676. return _this;
  59677. }
  59678. GroundMesh.prototype.getClassName = function () {
  59679. return "GroundMesh";
  59680. };
  59681. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59682. get: function () {
  59683. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59684. },
  59685. enumerable: true,
  59686. configurable: true
  59687. });
  59688. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59689. get: function () {
  59690. return this._subdivisionsX;
  59691. },
  59692. enumerable: true,
  59693. configurable: true
  59694. });
  59695. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59696. get: function () {
  59697. return this._subdivisionsY;
  59698. },
  59699. enumerable: true,
  59700. configurable: true
  59701. });
  59702. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59703. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59704. this._subdivisionsX = chunksCount;
  59705. this._subdivisionsY = chunksCount;
  59706. this.subdivide(chunksCount);
  59707. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59708. };
  59709. /**
  59710. * Returns a height (y) value in the Worl system :
  59711. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59712. * Returns the ground y position if (x, z) are outside the ground surface.
  59713. */
  59714. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59715. var world = this.getWorldMatrix();
  59716. var invMat = BABYLON.Tmp.Matrix[5];
  59717. world.invertToRef(invMat);
  59718. var tmpVect = BABYLON.Tmp.Vector3[8];
  59719. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59720. x = tmpVect.x;
  59721. z = tmpVect.z;
  59722. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59723. return this.position.y;
  59724. }
  59725. if (!this._heightQuads || this._heightQuads.length == 0) {
  59726. this._initHeightQuads();
  59727. this._computeHeightQuads();
  59728. }
  59729. var facet = this._getFacetAt(x, z);
  59730. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59731. // return y in the World system
  59732. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59733. return tmpVect.y;
  59734. };
  59735. /**
  59736. * Returns a normalized vector (Vector3) orthogonal to the ground
  59737. * at the ground coordinates (x, z) expressed in the World system.
  59738. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59739. */
  59740. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59741. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59742. this.getNormalAtCoordinatesToRef(x, z, normal);
  59743. return normal;
  59744. };
  59745. /**
  59746. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59747. * at the ground coordinates (x, z) expressed in the World system.
  59748. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59749. * Returns the GroundMesh.
  59750. */
  59751. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59752. var world = this.getWorldMatrix();
  59753. var tmpMat = BABYLON.Tmp.Matrix[5];
  59754. world.invertToRef(tmpMat);
  59755. var tmpVect = BABYLON.Tmp.Vector3[8];
  59756. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59757. x = tmpVect.x;
  59758. z = tmpVect.z;
  59759. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59760. return this;
  59761. }
  59762. if (!this._heightQuads || this._heightQuads.length == 0) {
  59763. this._initHeightQuads();
  59764. this._computeHeightQuads();
  59765. }
  59766. var facet = this._getFacetAt(x, z);
  59767. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59768. return this;
  59769. };
  59770. /**
  59771. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59772. * if the ground has been updated.
  59773. * This can be used in the render loop.
  59774. * Returns the GroundMesh.
  59775. */
  59776. GroundMesh.prototype.updateCoordinateHeights = function () {
  59777. if (!this._heightQuads || this._heightQuads.length == 0) {
  59778. this._initHeightQuads();
  59779. }
  59780. this._computeHeightQuads();
  59781. return this;
  59782. };
  59783. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59784. GroundMesh.prototype._getFacetAt = function (x, z) {
  59785. // retrieve col and row from x, z coordinates in the ground local system
  59786. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59787. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59788. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59789. var facet;
  59790. if (z < quad.slope.x * x + quad.slope.y) {
  59791. facet = quad.facet1;
  59792. }
  59793. else {
  59794. facet = quad.facet2;
  59795. }
  59796. return facet;
  59797. };
  59798. // Creates and populates the heightMap array with "facet" elements :
  59799. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59800. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59801. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59802. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59803. // Returns the GroundMesh.
  59804. GroundMesh.prototype._initHeightQuads = function () {
  59805. var subdivisionsX = this._subdivisionsX;
  59806. var subdivisionsY = this._subdivisionsY;
  59807. this._heightQuads = new Array();
  59808. for (var row = 0; row < subdivisionsY; row++) {
  59809. for (var col = 0; col < subdivisionsX; col++) {
  59810. 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) };
  59811. this._heightQuads[row * subdivisionsX + col] = quad;
  59812. }
  59813. }
  59814. return this;
  59815. };
  59816. // Compute each quad element values and update the the heightMap array :
  59817. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59818. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59819. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59820. // Returns the GroundMesh.
  59821. GroundMesh.prototype._computeHeightQuads = function () {
  59822. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59823. if (!positions) {
  59824. return this;
  59825. }
  59826. var v1 = BABYLON.Tmp.Vector3[3];
  59827. var v2 = BABYLON.Tmp.Vector3[2];
  59828. var v3 = BABYLON.Tmp.Vector3[1];
  59829. var v4 = BABYLON.Tmp.Vector3[0];
  59830. var v1v2 = BABYLON.Tmp.Vector3[4];
  59831. var v1v3 = BABYLON.Tmp.Vector3[5];
  59832. var v1v4 = BABYLON.Tmp.Vector3[6];
  59833. var norm1 = BABYLON.Tmp.Vector3[7];
  59834. var norm2 = BABYLON.Tmp.Vector3[8];
  59835. var i = 0;
  59836. var j = 0;
  59837. var k = 0;
  59838. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59839. var h = 0;
  59840. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59841. var d2 = 0;
  59842. var subdivisionsX = this._subdivisionsX;
  59843. var subdivisionsY = this._subdivisionsY;
  59844. for (var row = 0; row < subdivisionsY; row++) {
  59845. for (var col = 0; col < subdivisionsX; col++) {
  59846. i = col * 3;
  59847. j = row * (subdivisionsX + 1) * 3;
  59848. k = (row + 1) * (subdivisionsX + 1) * 3;
  59849. v1.x = positions[j + i];
  59850. v1.y = positions[j + i + 1];
  59851. v1.z = positions[j + i + 2];
  59852. v2.x = positions[j + i + 3];
  59853. v2.y = positions[j + i + 4];
  59854. v2.z = positions[j + i + 5];
  59855. v3.x = positions[k + i];
  59856. v3.y = positions[k + i + 1];
  59857. v3.z = positions[k + i + 2];
  59858. v4.x = positions[k + i + 3];
  59859. v4.y = positions[k + i + 4];
  59860. v4.z = positions[k + i + 5];
  59861. // 2D slope V1V4
  59862. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59863. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59864. // facet equations :
  59865. // we compute each facet normal vector
  59866. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59867. // we compute the value d by applying the equation to v1 which belongs to the plane
  59868. // then we store the facet equation in a Vector4
  59869. v2.subtractToRef(v1, v1v2);
  59870. v3.subtractToRef(v1, v1v3);
  59871. v4.subtractToRef(v1, v1v4);
  59872. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59873. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59874. norm1.normalize();
  59875. norm2.normalize();
  59876. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59877. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59878. var quad = this._heightQuads[row * subdivisionsX + col];
  59879. quad.slope.copyFromFloats(cd, h);
  59880. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59881. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59882. }
  59883. }
  59884. return this;
  59885. };
  59886. GroundMesh.prototype.serialize = function (serializationObject) {
  59887. _super.prototype.serialize.call(this, serializationObject);
  59888. serializationObject.subdivisionsX = this._subdivisionsX;
  59889. serializationObject.subdivisionsY = this._subdivisionsY;
  59890. serializationObject.minX = this._minX;
  59891. serializationObject.maxX = this._maxX;
  59892. serializationObject.minZ = this._minZ;
  59893. serializationObject.maxZ = this._maxZ;
  59894. serializationObject.width = this._width;
  59895. serializationObject.height = this._height;
  59896. };
  59897. GroundMesh.Parse = function (parsedMesh, scene) {
  59898. var result = new GroundMesh(parsedMesh.name, scene);
  59899. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59900. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59901. result._minX = parsedMesh.minX;
  59902. result._maxX = parsedMesh.maxX;
  59903. result._minZ = parsedMesh.minZ;
  59904. result._maxZ = parsedMesh.maxZ;
  59905. result._width = parsedMesh.width;
  59906. result._height = parsedMesh.height;
  59907. return result;
  59908. };
  59909. return GroundMesh;
  59910. }(BABYLON.Mesh));
  59911. BABYLON.GroundMesh = GroundMesh;
  59912. })(BABYLON || (BABYLON = {}));
  59913. //# sourceMappingURL=babylon.groundMesh.js.map
  59914. var BABYLON;
  59915. (function (BABYLON) {
  59916. /**
  59917. * Creates an instance based on a source mesh.
  59918. */
  59919. var InstancedMesh = /** @class */ (function (_super) {
  59920. __extends(InstancedMesh, _super);
  59921. function InstancedMesh(name, source) {
  59922. var _this = _super.call(this, name, source.getScene()) || this;
  59923. source.instances.push(_this);
  59924. _this._sourceMesh = source;
  59925. _this.position.copyFrom(source.position);
  59926. _this.rotation.copyFrom(source.rotation);
  59927. _this.scaling.copyFrom(source.scaling);
  59928. if (source.rotationQuaternion) {
  59929. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59930. }
  59931. _this.infiniteDistance = source.infiniteDistance;
  59932. _this.setPivotMatrix(source.getPivotMatrix());
  59933. _this.refreshBoundingInfo();
  59934. _this._syncSubMeshes();
  59935. return _this;
  59936. }
  59937. /**
  59938. * Returns the string "InstancedMesh".
  59939. */
  59940. InstancedMesh.prototype.getClassName = function () {
  59941. return "InstancedMesh";
  59942. };
  59943. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59944. // Methods
  59945. get: function () {
  59946. return this._sourceMesh.receiveShadows;
  59947. },
  59948. enumerable: true,
  59949. configurable: true
  59950. });
  59951. Object.defineProperty(InstancedMesh.prototype, "material", {
  59952. get: function () {
  59953. return this._sourceMesh.material;
  59954. },
  59955. enumerable: true,
  59956. configurable: true
  59957. });
  59958. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59959. get: function () {
  59960. return this._sourceMesh.visibility;
  59961. },
  59962. enumerable: true,
  59963. configurable: true
  59964. });
  59965. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59966. get: function () {
  59967. return this._sourceMesh.skeleton;
  59968. },
  59969. enumerable: true,
  59970. configurable: true
  59971. });
  59972. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59973. get: function () {
  59974. return this._sourceMesh.renderingGroupId;
  59975. },
  59976. set: function (value) {
  59977. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59978. return;
  59979. }
  59980. //no-op with warning
  59981. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59982. },
  59983. enumerable: true,
  59984. configurable: true
  59985. });
  59986. /**
  59987. * Returns the total number of vertices (integer).
  59988. */
  59989. InstancedMesh.prototype.getTotalVertices = function () {
  59990. return this._sourceMesh.getTotalVertices();
  59991. };
  59992. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59993. get: function () {
  59994. return this._sourceMesh;
  59995. },
  59996. enumerable: true,
  59997. configurable: true
  59998. });
  59999. /**
  60000. * Is this node ready to be used/rendered
  60001. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60002. * @return {boolean} is it ready
  60003. */
  60004. InstancedMesh.prototype.isReady = function (completeCheck) {
  60005. if (completeCheck === void 0) { completeCheck = false; }
  60006. return this._sourceMesh.isReady(completeCheck, true);
  60007. };
  60008. /**
  60009. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60010. */
  60011. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60012. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60013. };
  60014. /**
  60015. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60016. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60017. * The `data` are either a numeric array either a Float32Array.
  60018. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60019. * 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).
  60020. * Note that a new underlying VertexBuffer object is created each call.
  60021. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60022. *
  60023. * Possible `kind` values :
  60024. * - BABYLON.VertexBuffer.PositionKind
  60025. * - BABYLON.VertexBuffer.UVKind
  60026. * - BABYLON.VertexBuffer.UV2Kind
  60027. * - BABYLON.VertexBuffer.UV3Kind
  60028. * - BABYLON.VertexBuffer.UV4Kind
  60029. * - BABYLON.VertexBuffer.UV5Kind
  60030. * - BABYLON.VertexBuffer.UV6Kind
  60031. * - BABYLON.VertexBuffer.ColorKind
  60032. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60033. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60034. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60035. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60036. *
  60037. * Returns the Mesh.
  60038. */
  60039. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60040. if (this.sourceMesh) {
  60041. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60042. }
  60043. return this.sourceMesh;
  60044. };
  60045. /**
  60046. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60047. * If the mesh has no geometry, it is simply returned as it is.
  60048. * The `data` are either a numeric array either a Float32Array.
  60049. * No new underlying VertexBuffer object is created.
  60050. * 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.
  60051. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60052. *
  60053. * Possible `kind` values :
  60054. * - BABYLON.VertexBuffer.PositionKind
  60055. * - BABYLON.VertexBuffer.UVKind
  60056. * - BABYLON.VertexBuffer.UV2Kind
  60057. * - BABYLON.VertexBuffer.UV3Kind
  60058. * - BABYLON.VertexBuffer.UV4Kind
  60059. * - BABYLON.VertexBuffer.UV5Kind
  60060. * - BABYLON.VertexBuffer.UV6Kind
  60061. * - BABYLON.VertexBuffer.ColorKind
  60062. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60063. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60064. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60065. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60066. *
  60067. * Returns the Mesh.
  60068. */
  60069. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60070. if (this.sourceMesh) {
  60071. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60072. }
  60073. return this.sourceMesh;
  60074. };
  60075. /**
  60076. * Sets the mesh indices.
  60077. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60078. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60079. * This method creates a new index buffer each call.
  60080. * Returns the Mesh.
  60081. */
  60082. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60083. if (totalVertices === void 0) { totalVertices = null; }
  60084. if (this.sourceMesh) {
  60085. this.sourceMesh.setIndices(indices, totalVertices);
  60086. }
  60087. return this.sourceMesh;
  60088. };
  60089. /**
  60090. * Boolean : True if the mesh owns the requested kind of data.
  60091. */
  60092. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60093. return this._sourceMesh.isVerticesDataPresent(kind);
  60094. };
  60095. /**
  60096. * Returns an array of indices (IndicesArray).
  60097. */
  60098. InstancedMesh.prototype.getIndices = function () {
  60099. return this._sourceMesh.getIndices();
  60100. };
  60101. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60102. get: function () {
  60103. return this._sourceMesh._positions;
  60104. },
  60105. enumerable: true,
  60106. configurable: true
  60107. });
  60108. /**
  60109. * Sets a new updated BoundingInfo to the mesh.
  60110. * Returns the mesh.
  60111. */
  60112. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60113. var meshBB = this._sourceMesh.getBoundingInfo();
  60114. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60115. this._updateBoundingInfo();
  60116. return this;
  60117. };
  60118. InstancedMesh.prototype._preActivate = function () {
  60119. if (this._currentLOD) {
  60120. this._currentLOD._preActivate();
  60121. }
  60122. return this;
  60123. };
  60124. InstancedMesh.prototype._activate = function (renderId) {
  60125. if (this._currentLOD) {
  60126. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60127. }
  60128. return this;
  60129. };
  60130. /**
  60131. * Returns the current associated LOD AbstractMesh.
  60132. */
  60133. InstancedMesh.prototype.getLOD = function (camera) {
  60134. if (!camera) {
  60135. return this;
  60136. }
  60137. var boundingInfo = this.getBoundingInfo();
  60138. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60139. if (this._currentLOD === this.sourceMesh) {
  60140. return this;
  60141. }
  60142. return this._currentLOD;
  60143. };
  60144. InstancedMesh.prototype._syncSubMeshes = function () {
  60145. this.releaseSubMeshes();
  60146. if (this._sourceMesh.subMeshes) {
  60147. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60148. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60149. }
  60150. }
  60151. return this;
  60152. };
  60153. InstancedMesh.prototype._generatePointsArray = function () {
  60154. return this._sourceMesh._generatePointsArray();
  60155. };
  60156. /**
  60157. * Creates a new InstancedMesh from the current mesh.
  60158. * - name (string) : the cloned mesh name
  60159. * - newParent (optional Node) : the optional Node to parent the clone to.
  60160. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60161. *
  60162. * Returns the clone.
  60163. */
  60164. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60165. var result = this._sourceMesh.createInstance(name);
  60166. // Deep copy
  60167. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60168. // Bounding info
  60169. this.refreshBoundingInfo();
  60170. // Parent
  60171. if (newParent) {
  60172. result.parent = newParent;
  60173. }
  60174. if (!doNotCloneChildren) {
  60175. // Children
  60176. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60177. var mesh = this.getScene().meshes[index];
  60178. if (mesh.parent === this) {
  60179. mesh.clone(mesh.name, result);
  60180. }
  60181. }
  60182. }
  60183. result.computeWorldMatrix(true);
  60184. return result;
  60185. };
  60186. /**
  60187. * Disposes the InstancedMesh.
  60188. * Returns nothing.
  60189. */
  60190. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60191. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60192. // Remove from mesh
  60193. var index = this._sourceMesh.instances.indexOf(this);
  60194. this._sourceMesh.instances.splice(index, 1);
  60195. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60196. };
  60197. return InstancedMesh;
  60198. }(BABYLON.AbstractMesh));
  60199. BABYLON.InstancedMesh = InstancedMesh;
  60200. })(BABYLON || (BABYLON = {}));
  60201. //# sourceMappingURL=babylon.instancedMesh.js.map
  60202. var BABYLON;
  60203. (function (BABYLON) {
  60204. var LinesMesh = /** @class */ (function (_super) {
  60205. __extends(LinesMesh, _super);
  60206. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60207. if (scene === void 0) { scene = null; }
  60208. if (parent === void 0) { parent = null; }
  60209. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60210. _this.useVertexColor = useVertexColor;
  60211. _this.useVertexAlpha = useVertexAlpha;
  60212. _this.color = new BABYLON.Color3(1, 1, 1);
  60213. _this.alpha = 1;
  60214. if (source) {
  60215. _this.color = source.color.clone();
  60216. _this.alpha = source.alpha;
  60217. _this.useVertexColor = source.useVertexColor;
  60218. _this.useVertexAlpha = source.useVertexAlpha;
  60219. }
  60220. _this._intersectionThreshold = 0.1;
  60221. var defines = [];
  60222. var options = {
  60223. attributes: [BABYLON.VertexBuffer.PositionKind],
  60224. uniforms: ["world", "viewProjection"],
  60225. needAlphaBlending: true,
  60226. defines: defines
  60227. };
  60228. if (useVertexAlpha === false) {
  60229. options.needAlphaBlending = false;
  60230. }
  60231. if (!useVertexColor) {
  60232. options.uniforms.push("color");
  60233. }
  60234. else {
  60235. options.defines.push("#define VERTEXCOLOR");
  60236. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60237. }
  60238. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60239. return _this;
  60240. }
  60241. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60242. /**
  60243. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60244. * This margin is expressed in world space coordinates, so its value may vary.
  60245. * Default value is 0.1
  60246. * @returns the intersection Threshold value.
  60247. */
  60248. get: function () {
  60249. return this._intersectionThreshold;
  60250. },
  60251. /**
  60252. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60253. * This margin is expressed in world space coordinates, so its value may vary.
  60254. * @param value the new threshold to apply
  60255. */
  60256. set: function (value) {
  60257. if (this._intersectionThreshold === value) {
  60258. return;
  60259. }
  60260. this._intersectionThreshold = value;
  60261. if (this.geometry) {
  60262. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60263. }
  60264. },
  60265. enumerable: true,
  60266. configurable: true
  60267. });
  60268. /**
  60269. * Returns the string "LineMesh"
  60270. */
  60271. LinesMesh.prototype.getClassName = function () {
  60272. return "LinesMesh";
  60273. };
  60274. Object.defineProperty(LinesMesh.prototype, "material", {
  60275. get: function () {
  60276. return this._colorShader;
  60277. },
  60278. set: function (value) {
  60279. // Do nothing
  60280. },
  60281. enumerable: true,
  60282. configurable: true
  60283. });
  60284. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60285. get: function () {
  60286. return false;
  60287. },
  60288. enumerable: true,
  60289. configurable: true
  60290. });
  60291. LinesMesh.prototype.createInstance = function (name) {
  60292. throw new Error("LinesMeshes do not support createInstance.");
  60293. };
  60294. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60295. if (!this._geometry) {
  60296. return this;
  60297. }
  60298. // VBOs
  60299. this._geometry._bind(this._colorShader.getEffect());
  60300. // Color
  60301. if (!this.useVertexColor) {
  60302. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60303. }
  60304. return this;
  60305. };
  60306. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60307. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60308. return this;
  60309. }
  60310. var engine = this.getScene().getEngine();
  60311. // Draw order
  60312. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60313. return this;
  60314. };
  60315. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60316. this._colorShader.dispose();
  60317. _super.prototype.dispose.call(this, doNotRecurse);
  60318. };
  60319. /**
  60320. * Returns a new LineMesh object cloned from the current one.
  60321. */
  60322. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60323. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60324. };
  60325. return LinesMesh;
  60326. }(BABYLON.Mesh));
  60327. BABYLON.LinesMesh = LinesMesh;
  60328. })(BABYLON || (BABYLON = {}));
  60329. //# sourceMappingURL=babylon.linesMesh.js.map
  60330. var BABYLON;
  60331. (function (BABYLON) {
  60332. /**
  60333. * Class containing static functions to help procedurally build meshes
  60334. */
  60335. var MeshBuilder = /** @class */ (function () {
  60336. function MeshBuilder() {
  60337. }
  60338. MeshBuilder.updateSideOrientation = function (orientation) {
  60339. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60340. return BABYLON.Mesh.DOUBLESIDE;
  60341. }
  60342. if (orientation === undefined || orientation === null) {
  60343. return BABYLON.Mesh.FRONTSIDE;
  60344. }
  60345. return orientation;
  60346. };
  60347. /**
  60348. * Creates a box mesh
  60349. * * The parameter `size` sets the size (float) of each box side (default 1)
  60350. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60351. * * 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)
  60352. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60353. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60354. * * 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
  60355. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60356. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60357. * @param name defines the name of the mesh
  60358. * @param options defines the options used to create the mesh
  60359. * @param scene defines the hosting scene
  60360. * @returns the box mesh
  60361. */
  60362. MeshBuilder.CreateBox = function (name, options, scene) {
  60363. if (scene === void 0) { scene = null; }
  60364. var box = new BABYLON.Mesh(name, scene);
  60365. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60366. box._originalBuilderSideOrientation = options.sideOrientation;
  60367. var vertexData = BABYLON.VertexData.CreateBox(options);
  60368. vertexData.applyToMesh(box, options.updatable);
  60369. return box;
  60370. };
  60371. /**
  60372. * Creates a sphere mesh
  60373. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60374. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  60375. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60376. * * 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
  60377. * * 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)
  60378. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60379. * * 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
  60380. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60381. * @param name defines the name of the mesh
  60382. * @param options defines the options used to create the mesh
  60383. * @param scene defines the hosting scene
  60384. * @returns the sphere mesh
  60385. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60386. */
  60387. MeshBuilder.CreateSphere = function (name, options, scene) {
  60388. var sphere = new BABYLON.Mesh(name, scene);
  60389. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60390. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60391. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60392. vertexData.applyToMesh(sphere, options.updatable);
  60393. return sphere;
  60394. };
  60395. /**
  60396. * Creates a plane polygonal mesh. By default, this is a disc
  60397. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60398. * * 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
  60399. * * 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
  60400. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60401. * * 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
  60402. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60403. * @param name defines the name of the mesh
  60404. * @param options defines the options used to create the mesh
  60405. * @param scene defines the hosting scene
  60406. * @returns the plane polygonal mesh
  60407. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60408. */
  60409. MeshBuilder.CreateDisc = function (name, options, scene) {
  60410. if (scene === void 0) { scene = null; }
  60411. var disc = new BABYLON.Mesh(name, scene);
  60412. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60413. disc._originalBuilderSideOrientation = options.sideOrientation;
  60414. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60415. vertexData.applyToMesh(disc, options.updatable);
  60416. return disc;
  60417. };
  60418. /**
  60419. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60420. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60421. * * 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`)
  60422. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60423. * * 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
  60424. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60425. * * 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
  60426. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60427. * @param name defines the name of the mesh
  60428. * @param options defines the options used to create the mesh
  60429. * @param scene defines the hosting scene
  60430. * @returns the icosahedron mesh
  60431. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60432. */
  60433. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60434. var sphere = new BABYLON.Mesh(name, scene);
  60435. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60436. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60437. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60438. vertexData.applyToMesh(sphere, options.updatable);
  60439. return sphere;
  60440. };
  60441. ;
  60442. /**
  60443. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60444. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60445. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60446. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60447. * * 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
  60448. * * 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
  60449. * * 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
  60450. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60451. * * 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
  60452. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60453. * * 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
  60454. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60455. * * 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
  60456. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60457. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60458. * @param name defines the name of the mesh
  60459. * @param options defines the options used to create the mesh
  60460. * @param scene defines the hosting scene
  60461. * @returns the ribbon mesh
  60462. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60463. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60464. */
  60465. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60466. if (scene === void 0) { scene = null; }
  60467. var pathArray = options.pathArray;
  60468. var closeArray = options.closeArray;
  60469. var closePath = options.closePath;
  60470. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60471. var instance = options.instance;
  60472. var updatable = options.updatable;
  60473. if (instance) { // existing ribbon instance update
  60474. // positionFunction : ribbon case
  60475. // only pathArray and sideOrientation parameters are taken into account for positions update
  60476. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60477. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60478. var positionFunction = function (positions) {
  60479. var minlg = pathArray[0].length;
  60480. var i = 0;
  60481. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60482. for (var si = 1; si <= ns; si++) {
  60483. for (var p = 0; p < pathArray.length; p++) {
  60484. var path = pathArray[p];
  60485. var l = path.length;
  60486. minlg = (minlg < l) ? minlg : l;
  60487. var j = 0;
  60488. while (j < minlg) {
  60489. positions[i] = path[j].x;
  60490. positions[i + 1] = path[j].y;
  60491. positions[i + 2] = path[j].z;
  60492. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60493. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60494. }
  60495. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60496. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60497. }
  60498. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60499. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60500. }
  60501. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60502. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60503. }
  60504. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60505. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60506. }
  60507. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60508. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60509. }
  60510. j++;
  60511. i += 3;
  60512. }
  60513. if (instance._closePath) {
  60514. positions[i] = path[0].x;
  60515. positions[i + 1] = path[0].y;
  60516. positions[i + 2] = path[0].z;
  60517. i += 3;
  60518. }
  60519. }
  60520. }
  60521. };
  60522. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60523. positionFunction(positions);
  60524. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60525. instance._boundingInfo.update(instance._worldMatrix);
  60526. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60527. if (options.colors) {
  60528. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60529. for (var c = 0; c < options.colors.length; c++) {
  60530. colors[c * 4] = options.colors[c].r;
  60531. colors[c * 4 + 1] = options.colors[c].g;
  60532. colors[c * 4 + 2] = options.colors[c].b;
  60533. colors[c * 4 + 3] = options.colors[c].a;
  60534. }
  60535. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60536. }
  60537. if (options.uvs) {
  60538. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60539. for (var i = 0; i < options.uvs.length; i++) {
  60540. uvs[i * 2] = options.uvs[i].x;
  60541. uvs[i * 2 + 1] = options.uvs[i].y;
  60542. }
  60543. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60544. }
  60545. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60546. var indices = instance.getIndices();
  60547. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60548. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60549. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60550. if (instance._closePath) {
  60551. var indexFirst = 0;
  60552. var indexLast = 0;
  60553. for (var p = 0; p < pathArray.length; p++) {
  60554. indexFirst = instance._idx[p] * 3;
  60555. if (p + 1 < pathArray.length) {
  60556. indexLast = (instance._idx[p + 1] - 1) * 3;
  60557. }
  60558. else {
  60559. indexLast = normals.length - 3;
  60560. }
  60561. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60562. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60563. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60564. normals[indexLast] = normals[indexFirst];
  60565. normals[indexLast + 1] = normals[indexFirst + 1];
  60566. normals[indexLast + 2] = normals[indexFirst + 2];
  60567. }
  60568. }
  60569. if (!(instance.areNormalsFrozen)) {
  60570. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60571. }
  60572. }
  60573. return instance;
  60574. }
  60575. else { // new ribbon creation
  60576. var ribbon = new BABYLON.Mesh(name, scene);
  60577. ribbon._originalBuilderSideOrientation = sideOrientation;
  60578. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60579. if (closePath) {
  60580. ribbon._idx = vertexData._idx;
  60581. }
  60582. ribbon._closePath = closePath;
  60583. ribbon._closeArray = closeArray;
  60584. vertexData.applyToMesh(ribbon, updatable);
  60585. return ribbon;
  60586. }
  60587. };
  60588. /**
  60589. * Creates a cylinder or a cone mesh
  60590. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60591. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60592. * * 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.
  60593. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60594. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60595. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60596. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60597. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60598. * * 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).
  60599. * * 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
  60600. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60601. * * 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
  60602. * * 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.
  60603. * * If `enclose` is false, a ring surface is one element.
  60604. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60605. * * 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
  60606. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60607. * * 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
  60608. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60609. * @param name defines the name of the mesh
  60610. * @param options defines the options used to create the mesh
  60611. * @param scene defines the hosting scene
  60612. * @returns the cylinder mesh
  60613. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60614. */
  60615. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60616. var cylinder = new BABYLON.Mesh(name, scene);
  60617. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60618. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60619. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60620. vertexData.applyToMesh(cylinder, options.updatable);
  60621. return cylinder;
  60622. };
  60623. /**
  60624. * Creates a torus mesh
  60625. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60626. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60627. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60628. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60629. * * 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
  60630. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60631. * @param name defines the name of the mesh
  60632. * @param options defines the options used to create the mesh
  60633. * @param scene defines the hosting scene
  60634. * @returns the torus mesh
  60635. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60636. */
  60637. MeshBuilder.CreateTorus = function (name, options, scene) {
  60638. var torus = new BABYLON.Mesh(name, scene);
  60639. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60640. torus._originalBuilderSideOrientation = options.sideOrientation;
  60641. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60642. vertexData.applyToMesh(torus, options.updatable);
  60643. return torus;
  60644. };
  60645. /**
  60646. * Creates a torus knot mesh
  60647. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60648. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60649. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60650. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60651. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60652. * * 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
  60653. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60654. * @param name defines the name of the mesh
  60655. * @param options defines the options used to create the mesh
  60656. * @param scene defines the hosting scene
  60657. * @returns the torus knot mesh
  60658. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60659. */
  60660. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60661. var torusKnot = new BABYLON.Mesh(name, scene);
  60662. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60663. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60664. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60665. vertexData.applyToMesh(torusKnot, options.updatable);
  60666. return torusKnot;
  60667. };
  60668. /**
  60669. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60670. * * 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
  60671. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60672. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60673. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60674. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60675. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60676. * * 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
  60677. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60678. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60679. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60680. * @param name defines the name of the new line system
  60681. * @param options defines the options used to create the line system
  60682. * @param scene defines the hosting scene
  60683. * @returns a new line system mesh
  60684. */
  60685. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60686. var instance = options.instance;
  60687. var lines = options.lines;
  60688. var colors = options.colors;
  60689. if (instance) { // lines update
  60690. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60691. var vertexColor;
  60692. var lineColors;
  60693. if (colors) {
  60694. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60695. }
  60696. var i = 0;
  60697. var c = 0;
  60698. for (var l = 0; l < lines.length; l++) {
  60699. var points = lines[l];
  60700. for (var p = 0; p < points.length; p++) {
  60701. positions[i] = points[p].x;
  60702. positions[i + 1] = points[p].y;
  60703. positions[i + 2] = points[p].z;
  60704. if (colors && vertexColor) {
  60705. lineColors = colors[l];
  60706. vertexColor[c] = lineColors[p].r;
  60707. vertexColor[c + 1] = lineColors[p].g;
  60708. vertexColor[c + 2] = lineColors[p].b;
  60709. vertexColor[c + 3] = lineColors[p].a;
  60710. c += 4;
  60711. }
  60712. i += 3;
  60713. }
  60714. }
  60715. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60716. if (colors && vertexColor) {
  60717. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60718. }
  60719. return instance;
  60720. }
  60721. // line system creation
  60722. var useVertexColor = (colors) ? true : false;
  60723. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60724. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60725. vertexData.applyToMesh(lineSystem, options.updatable);
  60726. return lineSystem;
  60727. };
  60728. /**
  60729. * Creates a line mesh
  60730. * 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
  60731. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60732. * * The parameter `points` is an array successive Vector3
  60733. * * 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
  60734. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60735. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60736. * * When updating an instance, remember that only point positions can change, not the number of points
  60737. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60738. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60739. * @param name defines the name of the new line system
  60740. * @param options defines the options used to create the line system
  60741. * @param scene defines the hosting scene
  60742. * @returns a new line mesh
  60743. */
  60744. MeshBuilder.CreateLines = function (name, options, scene) {
  60745. if (scene === void 0) { scene = null; }
  60746. var colors = (options.colors) ? [options.colors] : null;
  60747. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60748. return lines;
  60749. };
  60750. /**
  60751. * Creates a dashed line mesh
  60752. * * 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
  60753. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60754. * * The parameter `points` is an array successive Vector3
  60755. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60756. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60757. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60758. * * 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
  60759. * * When updating an instance, remember that only point positions can change, not the number of points
  60760. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60761. * @param name defines the name of the mesh
  60762. * @param options defines the options used to create the mesh
  60763. * @param scene defines the hosting scene
  60764. * @returns the dashed line mesh
  60765. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60766. */
  60767. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60768. if (scene === void 0) { scene = null; }
  60769. var points = options.points;
  60770. var instance = options.instance;
  60771. var gapSize = options.gapSize || 1;
  60772. var dashSize = options.dashSize || 3;
  60773. if (instance) { // dashed lines update
  60774. var positionFunction = function (positions) {
  60775. var curvect = BABYLON.Vector3.Zero();
  60776. var nbSeg = positions.length / 6;
  60777. var lg = 0;
  60778. var nb = 0;
  60779. var shft = 0;
  60780. var dashshft = 0;
  60781. var curshft = 0;
  60782. var p = 0;
  60783. var i = 0;
  60784. var j = 0;
  60785. for (i = 0; i < points.length - 1; i++) {
  60786. points[i + 1].subtractToRef(points[i], curvect);
  60787. lg += curvect.length();
  60788. }
  60789. shft = lg / nbSeg;
  60790. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60791. for (i = 0; i < points.length - 1; i++) {
  60792. points[i + 1].subtractToRef(points[i], curvect);
  60793. nb = Math.floor(curvect.length() / shft);
  60794. curvect.normalize();
  60795. j = 0;
  60796. while (j < nb && p < positions.length) {
  60797. curshft = shft * j;
  60798. positions[p] = points[i].x + curshft * curvect.x;
  60799. positions[p + 1] = points[i].y + curshft * curvect.y;
  60800. positions[p + 2] = points[i].z + curshft * curvect.z;
  60801. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60802. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60803. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60804. p += 6;
  60805. j++;
  60806. }
  60807. }
  60808. while (p < positions.length) {
  60809. positions[p] = points[i].x;
  60810. positions[p + 1] = points[i].y;
  60811. positions[p + 2] = points[i].z;
  60812. p += 3;
  60813. }
  60814. };
  60815. instance.updateMeshPositions(positionFunction, false);
  60816. return instance;
  60817. }
  60818. // dashed lines creation
  60819. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60820. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60821. vertexData.applyToMesh(dashedLines, options.updatable);
  60822. dashedLines.dashSize = dashSize;
  60823. dashedLines.gapSize = gapSize;
  60824. return dashedLines;
  60825. };
  60826. /**
  60827. * 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.
  60828. * * 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.
  60829. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60830. * * 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.
  60831. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60832. * * 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
  60833. * * 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
  60834. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60835. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60836. * * 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
  60837. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60838. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60839. * @param name defines the name of the mesh
  60840. * @param options defines the options used to create the mesh
  60841. * @param scene defines the hosting scene
  60842. * @returns the extruded shape mesh
  60843. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60844. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60845. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60846. */
  60847. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60848. if (scene === void 0) { scene = null; }
  60849. var path = options.path;
  60850. var shape = options.shape;
  60851. var scale = options.scale || 1;
  60852. var rotation = options.rotation || 0;
  60853. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60854. var updatable = options.updatable;
  60855. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60856. var instance = options.instance || null;
  60857. var invertUV = options.invertUV || false;
  60858. 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);
  60859. };
  60860. /**
  60861. * Creates an custom extruded shape mesh.
  60862. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60863. * * 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.
  60864. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60865. * * 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
  60866. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60867. * * 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
  60868. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60869. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60870. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60871. * * 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
  60872. * * 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
  60873. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60874. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60875. * * 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
  60876. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60877. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60878. * @param name defines the name of the mesh
  60879. * @param options defines the options used to create the mesh
  60880. * @param scene defines the hosting scene
  60881. * @returns the custom extruded shape mesh
  60882. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60883. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60884. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60885. */
  60886. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60887. var path = options.path;
  60888. var shape = options.shape;
  60889. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60890. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60891. var ribbonCloseArray = options.ribbonCloseArray || false;
  60892. var ribbonClosePath = options.ribbonClosePath || false;
  60893. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60894. var updatable = options.updatable;
  60895. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60896. var instance = options.instance;
  60897. var invertUV = options.invertUV || false;
  60898. 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);
  60899. };
  60900. /**
  60901. * Creates lathe mesh.
  60902. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60903. * * 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
  60904. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60905. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60906. * * 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
  60907. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60908. * * 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
  60909. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60910. * * 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
  60911. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60912. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60913. * @param name defines the name of the mesh
  60914. * @param options defines the options used to create the mesh
  60915. * @param scene defines the hosting scene
  60916. * @returns the lathe mesh
  60917. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60918. */
  60919. MeshBuilder.CreateLathe = function (name, options, scene) {
  60920. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60921. var closed = (options.closed === undefined) ? true : options.closed;
  60922. var shape = options.shape;
  60923. var radius = options.radius || 1;
  60924. var tessellation = options.tessellation || 64;
  60925. var updatable = options.updatable;
  60926. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60927. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60928. var pi2 = Math.PI * 2;
  60929. var paths = new Array();
  60930. var invertUV = options.invertUV || false;
  60931. var i = 0;
  60932. var p = 0;
  60933. var step = pi2 / tessellation * arc;
  60934. var rotated;
  60935. var path = new Array();
  60936. ;
  60937. for (i = 0; i <= tessellation; i++) {
  60938. var path = [];
  60939. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60940. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60941. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60942. }
  60943. for (p = 0; p < shape.length; p++) {
  60944. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60945. path.push(rotated);
  60946. }
  60947. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60948. 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));
  60949. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60950. }
  60951. paths.push(path);
  60952. }
  60953. // lathe ribbon
  60954. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60955. return lathe;
  60956. };
  60957. /**
  60958. * Creates a plane mesh
  60959. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60960. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60961. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60962. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60963. * * 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
  60964. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60965. * @param name defines the name of the mesh
  60966. * @param options defines the options used to create the mesh
  60967. * @param scene defines the hosting scene
  60968. * @returns the plane mesh
  60969. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60970. */
  60971. MeshBuilder.CreatePlane = function (name, options, scene) {
  60972. var plane = new BABYLON.Mesh(name, scene);
  60973. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60974. plane._originalBuilderSideOrientation = options.sideOrientation;
  60975. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60976. vertexData.applyToMesh(plane, options.updatable);
  60977. if (options.sourcePlane) {
  60978. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60979. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60980. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60981. plane.rotate(vectorProduct, product);
  60982. }
  60983. return plane;
  60984. };
  60985. /**
  60986. * Creates a ground mesh
  60987. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60988. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60989. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60990. * @param name defines the name of the mesh
  60991. * @param options defines the options used to create the mesh
  60992. * @param scene defines the hosting scene
  60993. * @returns the ground mesh
  60994. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60995. */
  60996. MeshBuilder.CreateGround = function (name, options, scene) {
  60997. var ground = new BABYLON.GroundMesh(name, scene);
  60998. ground._setReady(false);
  60999. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61000. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61001. ground._width = options.width || 1;
  61002. ground._height = options.height || 1;
  61003. ground._maxX = ground._width / 2;
  61004. ground._maxZ = ground._height / 2;
  61005. ground._minX = -ground._maxX;
  61006. ground._minZ = -ground._maxZ;
  61007. var vertexData = BABYLON.VertexData.CreateGround(options);
  61008. vertexData.applyToMesh(ground, options.updatable);
  61009. ground._setReady(true);
  61010. return ground;
  61011. };
  61012. /**
  61013. * Creates a tiled ground mesh
  61014. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61015. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61016. * * 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
  61017. * * 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
  61018. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61019. * @param name defines the name of the mesh
  61020. * @param options defines the options used to create the mesh
  61021. * @param scene defines the hosting scene
  61022. * @returns the tiled ground mesh
  61023. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61024. */
  61025. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61026. var tiledGround = new BABYLON.Mesh(name, scene);
  61027. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61028. vertexData.applyToMesh(tiledGround, options.updatable);
  61029. return tiledGround;
  61030. };
  61031. /**
  61032. * Creates a ground mesh from a height map
  61033. * * The parameter `url` sets the URL of the height map image resource.
  61034. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61035. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61036. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61037. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61038. * * 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.
  61039. * * 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).
  61040. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61041. * @param name defines the name of the mesh
  61042. * @param url defines the url to the height map
  61043. * @param options defines the options used to create the mesh
  61044. * @param scene defines the hosting scene
  61045. * @returns the ground mesh
  61046. * @see http://doc.babylonjs.com/babylon101/height_map
  61047. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61048. */
  61049. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61050. var width = options.width || 10.0;
  61051. var height = options.height || 10.0;
  61052. var subdivisions = options.subdivisions || 1 | 0;
  61053. var minHeight = options.minHeight || 0.0;
  61054. var maxHeight = options.maxHeight || 1.0;
  61055. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61056. var updatable = options.updatable;
  61057. var onReady = options.onReady;
  61058. var ground = new BABYLON.GroundMesh(name, scene);
  61059. ground._subdivisionsX = subdivisions;
  61060. ground._subdivisionsY = subdivisions;
  61061. ground._width = width;
  61062. ground._height = height;
  61063. ground._maxX = ground._width / 2.0;
  61064. ground._maxZ = ground._height / 2.0;
  61065. ground._minX = -ground._maxX;
  61066. ground._minZ = -ground._maxZ;
  61067. ground._setReady(false);
  61068. var onload = function (img) {
  61069. // Getting height map data
  61070. var canvas = document.createElement("canvas");
  61071. var context = canvas.getContext("2d");
  61072. if (!context) {
  61073. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61074. }
  61075. if (scene.isDisposed) {
  61076. return;
  61077. }
  61078. var bufferWidth = img.width;
  61079. var bufferHeight = img.height;
  61080. canvas.width = bufferWidth;
  61081. canvas.height = bufferHeight;
  61082. context.drawImage(img, 0, 0);
  61083. // Create VertexData from map data
  61084. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61085. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61086. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61087. width: width, height: height,
  61088. subdivisions: subdivisions,
  61089. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61090. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61091. });
  61092. vertexData.applyToMesh(ground, updatable);
  61093. //execute ready callback, if set
  61094. if (onReady) {
  61095. onReady(ground);
  61096. }
  61097. ground._setReady(true);
  61098. };
  61099. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61100. return ground;
  61101. };
  61102. /**
  61103. * Creates a polygon mesh
  61104. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61105. * * 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
  61106. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61107. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61108. * * 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)
  61109. * * Remember you can only change the shape positions, not their number when updating a polygon
  61110. * @param name defines the name of the mesh
  61111. * @param options defines the options used to create the mesh
  61112. * @param scene defines the hosting scene
  61113. * @returns the polygon mesh
  61114. */
  61115. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61116. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61117. var shape = options.shape;
  61118. var holes = options.holes || [];
  61119. var depth = options.depth || 0;
  61120. var contours = [];
  61121. var hole = [];
  61122. for (var i = 0; i < shape.length; i++) {
  61123. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61124. }
  61125. var epsilon = 0.00000001;
  61126. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61127. contours.pop();
  61128. }
  61129. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61130. for (var hNb = 0; hNb < holes.length; hNb++) {
  61131. hole = [];
  61132. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61133. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61134. }
  61135. polygonTriangulation.addHole(hole);
  61136. }
  61137. var polygon = polygonTriangulation.build(options.updatable, depth);
  61138. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61139. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61140. vertexData.applyToMesh(polygon, options.updatable);
  61141. return polygon;
  61142. };
  61143. ;
  61144. /**
  61145. * Creates an extruded polygon mesh, with depth in the Y direction.
  61146. * * 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)
  61147. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61148. * @param name defines the name of the mesh
  61149. * @param options defines the options used to create the mesh
  61150. * @param scene defines the hosting scene
  61151. * @returns the polygon mesh
  61152. */
  61153. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61154. return MeshBuilder.CreatePolygon(name, options, scene);
  61155. };
  61156. ;
  61157. /**
  61158. * Creates a tube mesh.
  61159. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61160. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61161. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61162. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61163. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61164. * * 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)
  61165. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61166. * * 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
  61167. * * 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
  61168. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61169. * * 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
  61170. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61171. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61172. * @param name defines the name of the mesh
  61173. * @param options defines the options used to create the mesh
  61174. * @param scene defines the hosting scene
  61175. * @returns the tube mesh
  61176. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61177. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61178. */
  61179. MeshBuilder.CreateTube = function (name, options, scene) {
  61180. var path = options.path;
  61181. var instance = options.instance;
  61182. var radius = 1.0;
  61183. if (instance) {
  61184. radius = instance.radius;
  61185. }
  61186. if (options.radius !== undefined) {
  61187. radius = options.radius;
  61188. }
  61189. ;
  61190. var tessellation = options.tessellation || 64 | 0;
  61191. var radiusFunction = options.radiusFunction || null;
  61192. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61193. var invertUV = options.invertUV || false;
  61194. var updatable = options.updatable;
  61195. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61196. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61197. // tube geometry
  61198. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61199. var tangents = path3D.getTangents();
  61200. var normals = path3D.getNormals();
  61201. var distances = path3D.getDistances();
  61202. var pi2 = Math.PI * 2;
  61203. var step = pi2 / tessellation * arc;
  61204. var returnRadius = function () { return radius; };
  61205. var radiusFunctionFinal = radiusFunction || returnRadius;
  61206. var circlePath;
  61207. var rad;
  61208. var normal;
  61209. var rotated;
  61210. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61211. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61212. for (var i = 0; i < path.length; i++) {
  61213. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61214. circlePath = Array(); // current circle array
  61215. normal = normals[i]; // current normal
  61216. for (var t = 0; t < tessellation; t++) {
  61217. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61218. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61219. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61220. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61221. circlePath[t] = rotated;
  61222. }
  61223. circlePaths[index] = circlePath;
  61224. index++;
  61225. }
  61226. // cap
  61227. var capPath = function (nbPoints, pathIndex) {
  61228. var pointCap = Array();
  61229. for (var i = 0; i < nbPoints; i++) {
  61230. pointCap.push(path[pathIndex]);
  61231. }
  61232. return pointCap;
  61233. };
  61234. switch (cap) {
  61235. case BABYLON.Mesh.NO_CAP:
  61236. break;
  61237. case BABYLON.Mesh.CAP_START:
  61238. circlePaths[0] = capPath(tessellation, 0);
  61239. circlePaths[1] = circlePaths[2].slice(0);
  61240. break;
  61241. case BABYLON.Mesh.CAP_END:
  61242. circlePaths[index] = circlePaths[index - 1].slice(0);
  61243. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61244. break;
  61245. case BABYLON.Mesh.CAP_ALL:
  61246. circlePaths[0] = capPath(tessellation, 0);
  61247. circlePaths[1] = circlePaths[2].slice(0);
  61248. circlePaths[index] = circlePaths[index - 1].slice(0);
  61249. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61250. break;
  61251. default:
  61252. break;
  61253. }
  61254. return circlePaths;
  61255. };
  61256. var path3D;
  61257. var pathArray;
  61258. if (instance) { // tube update
  61259. var arc = options.arc || instance.arc;
  61260. path3D = (instance.path3D).update(path);
  61261. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61262. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61263. instance.path3D = path3D;
  61264. instance.pathArray = pathArray;
  61265. instance.arc = arc;
  61266. instance.radius = radius;
  61267. return instance;
  61268. }
  61269. // tube creation
  61270. path3D = new BABYLON.Path3D(path);
  61271. var newPathArray = new Array();
  61272. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61273. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61274. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61275. tube.pathArray = pathArray;
  61276. tube.path3D = path3D;
  61277. tube.tessellation = tessellation;
  61278. tube.cap = cap;
  61279. tube.arc = options.arc;
  61280. tube.radius = radius;
  61281. return tube;
  61282. };
  61283. /**
  61284. * Creates a polyhedron mesh
  61285. * * 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
  61286. * * The parameter `size` (positive float, default 1) sets the polygon size
  61287. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61288. * * 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`
  61289. * * 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
  61290. * * 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)`)
  61291. * * 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
  61292. * * 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
  61293. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61294. * * 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
  61295. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61296. * @param name defines the name of the mesh
  61297. * @param options defines the options used to create the mesh
  61298. * @param scene defines the hosting scene
  61299. * @returns the polyhedron mesh
  61300. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61301. */
  61302. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61303. var polyhedron = new BABYLON.Mesh(name, scene);
  61304. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61305. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61306. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61307. vertexData.applyToMesh(polyhedron, options.updatable);
  61308. return polyhedron;
  61309. };
  61310. /**
  61311. * Creates a decal mesh.
  61312. * 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
  61313. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61314. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61315. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61316. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61317. * @param name defines the name of the mesh
  61318. * @param sourceMesh defines the mesh where the decal must be applied
  61319. * @param options defines the options used to create the mesh
  61320. * @param scene defines the hosting scene
  61321. * @returns the decal mesh
  61322. * @see http://doc.babylonjs.com/how_to/decals
  61323. */
  61324. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61325. var indices = sourceMesh.getIndices();
  61326. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61327. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61328. var position = options.position || BABYLON.Vector3.Zero();
  61329. var normal = options.normal || BABYLON.Vector3.Up();
  61330. var size = options.size || BABYLON.Vector3.One();
  61331. var angle = options.angle || 0;
  61332. // Getting correct rotation
  61333. if (!normal) {
  61334. var target = new BABYLON.Vector3(0, 0, 1);
  61335. var camera = sourceMesh.getScene().activeCamera;
  61336. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61337. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61338. }
  61339. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61340. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61341. var pitch = Math.atan2(normal.y, len);
  61342. // Matrix
  61343. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61344. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61345. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61346. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61347. var vertexData = new BABYLON.VertexData();
  61348. vertexData.indices = [];
  61349. vertexData.positions = [];
  61350. vertexData.normals = [];
  61351. vertexData.uvs = [];
  61352. var currentVertexDataIndex = 0;
  61353. var extractDecalVector3 = function (indexId) {
  61354. var result = new BABYLON.PositionNormalVertex();
  61355. if (!indices || !positions || !normals) {
  61356. return result;
  61357. }
  61358. var vertexId = indices[indexId];
  61359. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61360. // Send vector to decal local world
  61361. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61362. // Get normal
  61363. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61364. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61365. return result;
  61366. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61367. var clip = function (vertices, axis) {
  61368. if (vertices.length === 0) {
  61369. return vertices;
  61370. }
  61371. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61372. var clipVertices = function (v0, v1) {
  61373. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61374. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61375. };
  61376. var result = new Array();
  61377. for (var index = 0; index < vertices.length; index += 3) {
  61378. var v1Out;
  61379. var v2Out;
  61380. var v3Out;
  61381. var total = 0;
  61382. var nV1 = null;
  61383. var nV2 = null;
  61384. var nV3 = null;
  61385. var nV4 = null;
  61386. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61387. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61388. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61389. v1Out = d1 > 0;
  61390. v2Out = d2 > 0;
  61391. v3Out = d3 > 0;
  61392. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61393. switch (total) {
  61394. case 0:
  61395. result.push(vertices[index]);
  61396. result.push(vertices[index + 1]);
  61397. result.push(vertices[index + 2]);
  61398. break;
  61399. case 1:
  61400. if (v1Out) {
  61401. nV1 = vertices[index + 1];
  61402. nV2 = vertices[index + 2];
  61403. nV3 = clipVertices(vertices[index], nV1);
  61404. nV4 = clipVertices(vertices[index], nV2);
  61405. }
  61406. if (v2Out) {
  61407. nV1 = vertices[index];
  61408. nV2 = vertices[index + 2];
  61409. nV3 = clipVertices(vertices[index + 1], nV1);
  61410. nV4 = clipVertices(vertices[index + 1], nV2);
  61411. result.push(nV3);
  61412. result.push(nV2.clone());
  61413. result.push(nV1.clone());
  61414. result.push(nV2.clone());
  61415. result.push(nV3.clone());
  61416. result.push(nV4);
  61417. break;
  61418. }
  61419. if (v3Out) {
  61420. nV1 = vertices[index];
  61421. nV2 = vertices[index + 1];
  61422. nV3 = clipVertices(vertices[index + 2], nV1);
  61423. nV4 = clipVertices(vertices[index + 2], nV2);
  61424. }
  61425. if (nV1 && nV2 && nV3 && nV4) {
  61426. result.push(nV1.clone());
  61427. result.push(nV2.clone());
  61428. result.push(nV3);
  61429. result.push(nV4);
  61430. result.push(nV3.clone());
  61431. result.push(nV2.clone());
  61432. }
  61433. break;
  61434. case 2:
  61435. if (!v1Out) {
  61436. nV1 = vertices[index].clone();
  61437. nV2 = clipVertices(nV1, vertices[index + 1]);
  61438. nV3 = clipVertices(nV1, vertices[index + 2]);
  61439. result.push(nV1);
  61440. result.push(nV2);
  61441. result.push(nV3);
  61442. }
  61443. if (!v2Out) {
  61444. nV1 = vertices[index + 1].clone();
  61445. nV2 = clipVertices(nV1, vertices[index + 2]);
  61446. nV3 = clipVertices(nV1, vertices[index]);
  61447. result.push(nV1);
  61448. result.push(nV2);
  61449. result.push(nV3);
  61450. }
  61451. if (!v3Out) {
  61452. nV1 = vertices[index + 2].clone();
  61453. nV2 = clipVertices(nV1, vertices[index]);
  61454. nV3 = clipVertices(nV1, vertices[index + 1]);
  61455. result.push(nV1);
  61456. result.push(nV2);
  61457. result.push(nV3);
  61458. }
  61459. break;
  61460. case 3:
  61461. break;
  61462. }
  61463. }
  61464. return result;
  61465. };
  61466. for (var index = 0; index < indices.length; index += 3) {
  61467. var faceVertices = new Array();
  61468. faceVertices.push(extractDecalVector3(index));
  61469. faceVertices.push(extractDecalVector3(index + 1));
  61470. faceVertices.push(extractDecalVector3(index + 2));
  61471. // Clip
  61472. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61473. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61474. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61475. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61476. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61477. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61478. if (faceVertices.length === 0) {
  61479. continue;
  61480. }
  61481. // Add UVs and get back to world
  61482. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61483. var vertex = faceVertices[vIndex];
  61484. //TODO check for Int32Array | Uint32Array | Uint16Array
  61485. vertexData.indices.push(currentVertexDataIndex);
  61486. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61487. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61488. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61489. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61490. currentVertexDataIndex++;
  61491. }
  61492. }
  61493. // Return mesh
  61494. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61495. vertexData.applyToMesh(decal);
  61496. decal.position = position.clone();
  61497. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61498. return decal;
  61499. };
  61500. // Privates
  61501. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61502. // extrusion geometry
  61503. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61504. var tangents = path3D.getTangents();
  61505. var normals = path3D.getNormals();
  61506. var binormals = path3D.getBinormals();
  61507. var distances = path3D.getDistances();
  61508. var angle = 0;
  61509. var returnScale = function () { return scale !== null ? scale : 1; };
  61510. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61511. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61512. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61513. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61514. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61515. for (var i = 0; i < curve.length; i++) {
  61516. var shapePath = new Array();
  61517. var angleStep = rotate(i, distances[i]);
  61518. var scaleRatio = scl(i, distances[i]);
  61519. for (var p = 0; p < shape.length; p++) {
  61520. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61521. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61522. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61523. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61524. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61525. shapePath[p] = rotated;
  61526. }
  61527. shapePaths[index] = shapePath;
  61528. angle += angleStep;
  61529. index++;
  61530. }
  61531. // cap
  61532. var capPath = function (shapePath) {
  61533. var pointCap = Array();
  61534. var barycenter = BABYLON.Vector3.Zero();
  61535. var i;
  61536. for (i = 0; i < shapePath.length; i++) {
  61537. barycenter.addInPlace(shapePath[i]);
  61538. }
  61539. barycenter.scaleInPlace(1.0 / shapePath.length);
  61540. for (i = 0; i < shapePath.length; i++) {
  61541. pointCap.push(barycenter);
  61542. }
  61543. return pointCap;
  61544. };
  61545. switch (cap) {
  61546. case BABYLON.Mesh.NO_CAP:
  61547. break;
  61548. case BABYLON.Mesh.CAP_START:
  61549. shapePaths[0] = capPath(shapePaths[2]);
  61550. shapePaths[1] = shapePaths[2];
  61551. break;
  61552. case BABYLON.Mesh.CAP_END:
  61553. shapePaths[index] = shapePaths[index - 1];
  61554. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61555. break;
  61556. case BABYLON.Mesh.CAP_ALL:
  61557. shapePaths[0] = capPath(shapePaths[2]);
  61558. shapePaths[1] = shapePaths[2];
  61559. shapePaths[index] = shapePaths[index - 1];
  61560. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61561. break;
  61562. default:
  61563. break;
  61564. }
  61565. return shapePaths;
  61566. };
  61567. var path3D;
  61568. var pathArray;
  61569. if (instance) { // instance update
  61570. path3D = (instance.path3D).update(curve);
  61571. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61572. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61573. return instance;
  61574. }
  61575. // extruded shape creation
  61576. path3D = new BABYLON.Path3D(curve);
  61577. var newShapePaths = new Array();
  61578. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61579. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61580. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61581. extrudedGeneric.pathArray = pathArray;
  61582. extrudedGeneric.path3D = path3D;
  61583. extrudedGeneric.cap = cap;
  61584. return extrudedGeneric;
  61585. };
  61586. return MeshBuilder;
  61587. }());
  61588. BABYLON.MeshBuilder = MeshBuilder;
  61589. })(BABYLON || (BABYLON = {}));
  61590. //# sourceMappingURL=babylon.meshBuilder.js.map
  61591. var BABYLON;
  61592. (function (BABYLON) {
  61593. /**
  61594. * Draco compression (https://google.github.io/draco/)
  61595. */
  61596. var DracoCompression = /** @class */ (function () {
  61597. /**
  61598. * Constructor
  61599. */
  61600. function DracoCompression() {
  61601. }
  61602. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61603. /**
  61604. * Returns true if the decoder is available.
  61605. */
  61606. get: function () {
  61607. if (typeof DracoDecoderModule !== "undefined") {
  61608. return true;
  61609. }
  61610. var decoder = DracoCompression.Configuration.decoder;
  61611. if (decoder) {
  61612. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61613. return true;
  61614. }
  61615. if (decoder.fallbackUrl) {
  61616. return true;
  61617. }
  61618. }
  61619. return false;
  61620. },
  61621. enumerable: true,
  61622. configurable: true
  61623. });
  61624. /**
  61625. * Stop all async operations and release resources.
  61626. */
  61627. DracoCompression.prototype.dispose = function () {
  61628. };
  61629. /**
  61630. * Decode Draco compressed mesh data to vertex data.
  61631. * @param data The array buffer view for the Draco compression data
  61632. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61633. * @returns A promise that resolves with the decoded vertex data
  61634. */
  61635. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61636. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61637. var module = wrappedModule.module;
  61638. var vertexData = new BABYLON.VertexData();
  61639. var buffer = new module.DecoderBuffer();
  61640. buffer.Init(data, data.byteLength);
  61641. var decoder = new module.Decoder();
  61642. var geometry;
  61643. var status;
  61644. try {
  61645. var type = decoder.GetEncodedGeometryType(buffer);
  61646. switch (type) {
  61647. case module.TRIANGULAR_MESH:
  61648. geometry = new module.Mesh();
  61649. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61650. break;
  61651. case module.POINT_CLOUD:
  61652. geometry = new module.PointCloud();
  61653. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61654. break;
  61655. default:
  61656. throw new Error("Invalid geometry type " + type);
  61657. }
  61658. if (!status.ok() || !geometry.ptr) {
  61659. throw new Error(status.error_msg());
  61660. }
  61661. var numPoints = geometry.num_points();
  61662. if (type === module.TRIANGULAR_MESH) {
  61663. var numFaces = geometry.num_faces();
  61664. var faceIndices = new module.DracoInt32Array();
  61665. try {
  61666. var indices = new Uint32Array(numFaces * 3);
  61667. for (var i = 0; i < numFaces; i++) {
  61668. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61669. var offset = i * 3;
  61670. indices[offset + 0] = faceIndices.GetValue(0);
  61671. indices[offset + 1] = faceIndices.GetValue(1);
  61672. indices[offset + 2] = faceIndices.GetValue(2);
  61673. }
  61674. vertexData.indices = indices;
  61675. }
  61676. finally {
  61677. module.destroy(faceIndices);
  61678. }
  61679. }
  61680. for (var kind in attributes) {
  61681. var uniqueId = attributes[kind];
  61682. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61683. var dracoData = new module.DracoFloat32Array();
  61684. try {
  61685. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61686. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61687. for (var i = 0; i < babylonData.length; i++) {
  61688. babylonData[i] = dracoData.GetValue(i);
  61689. }
  61690. vertexData.set(babylonData, kind);
  61691. }
  61692. finally {
  61693. module.destroy(dracoData);
  61694. }
  61695. }
  61696. }
  61697. finally {
  61698. if (geometry) {
  61699. module.destroy(geometry);
  61700. }
  61701. module.destroy(decoder);
  61702. module.destroy(buffer);
  61703. }
  61704. return vertexData;
  61705. });
  61706. };
  61707. DracoCompression._GetDecoderModule = function () {
  61708. if (!DracoCompression._DecoderModulePromise) {
  61709. var promise = null;
  61710. var config_1 = {};
  61711. if (typeof DracoDecoderModule !== "undefined") {
  61712. promise = Promise.resolve();
  61713. }
  61714. else {
  61715. var decoder = DracoCompression.Configuration.decoder;
  61716. if (decoder) {
  61717. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61718. promise = Promise.all([
  61719. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61720. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61721. config_1.wasmBinary = data;
  61722. })
  61723. ]);
  61724. }
  61725. else if (decoder.fallbackUrl) {
  61726. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61727. }
  61728. }
  61729. }
  61730. if (!promise) {
  61731. throw new Error("Draco decoder module is not available");
  61732. }
  61733. DracoCompression._DecoderModulePromise = promise.then(function () {
  61734. return new Promise(function (resolve) {
  61735. config_1.onModuleLoaded = function (decoderModule) {
  61736. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61737. resolve({ module: decoderModule });
  61738. };
  61739. DracoDecoderModule(config_1);
  61740. });
  61741. });
  61742. }
  61743. return DracoCompression._DecoderModulePromise;
  61744. };
  61745. DracoCompression._LoadScriptAsync = function (url) {
  61746. return new Promise(function (resolve, reject) {
  61747. BABYLON.Tools.LoadScript(url, function () {
  61748. resolve();
  61749. }, function (message) {
  61750. reject(new Error(message));
  61751. });
  61752. });
  61753. };
  61754. DracoCompression._LoadFileAsync = function (url) {
  61755. return new Promise(function (resolve, reject) {
  61756. BABYLON.Tools.LoadFile(url, function (data) {
  61757. resolve(data);
  61758. }, undefined, undefined, true, function (request, exception) {
  61759. reject(exception);
  61760. });
  61761. });
  61762. };
  61763. /**
  61764. * The configuration.
  61765. */
  61766. DracoCompression.Configuration = {
  61767. decoder: {
  61768. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61769. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61770. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61771. }
  61772. };
  61773. return DracoCompression;
  61774. }());
  61775. BABYLON.DracoCompression = DracoCompression;
  61776. })(BABYLON || (BABYLON = {}));
  61777. //# sourceMappingURL=babylon.dracoCompression.js.map
  61778. var BABYLON;
  61779. (function (BABYLON) {
  61780. var AudioEngine = /** @class */ (function () {
  61781. function AudioEngine() {
  61782. this._audioContext = null;
  61783. this._audioContextInitialized = false;
  61784. this.canUseWebAudio = false;
  61785. this.WarnedWebAudioUnsupported = false;
  61786. this.unlocked = false;
  61787. this.isMP3supported = false;
  61788. this.isOGGsupported = false;
  61789. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61790. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61791. this.canUseWebAudio = true;
  61792. }
  61793. var audioElem = document.createElement('audio');
  61794. try {
  61795. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61796. this.isMP3supported = true;
  61797. }
  61798. }
  61799. catch (e) {
  61800. // protect error during capability check.
  61801. }
  61802. try {
  61803. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61804. this.isOGGsupported = true;
  61805. }
  61806. }
  61807. catch (e) {
  61808. // protect error during capability check.
  61809. }
  61810. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61811. this._unlockiOSaudio();
  61812. }
  61813. else {
  61814. this.unlocked = true;
  61815. }
  61816. }
  61817. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61818. get: function () {
  61819. if (!this._audioContextInitialized) {
  61820. this._initializeAudioContext();
  61821. }
  61822. return this._audioContext;
  61823. },
  61824. enumerable: true,
  61825. configurable: true
  61826. });
  61827. AudioEngine.prototype._unlockiOSaudio = function () {
  61828. var _this = this;
  61829. var unlockaudio = function () {
  61830. if (!_this.audioContext) {
  61831. return;
  61832. }
  61833. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61834. var source = _this.audioContext.createBufferSource();
  61835. source.buffer = buffer;
  61836. source.connect(_this.audioContext.destination);
  61837. source.start(0);
  61838. setTimeout(function () {
  61839. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61840. _this.unlocked = true;
  61841. window.removeEventListener('touchend', unlockaudio, false);
  61842. if (_this.onAudioUnlocked) {
  61843. _this.onAudioUnlocked();
  61844. }
  61845. }
  61846. }, 0);
  61847. };
  61848. window.addEventListener('touchend', unlockaudio, false);
  61849. };
  61850. AudioEngine.prototype._initializeAudioContext = function () {
  61851. try {
  61852. if (this.canUseWebAudio) {
  61853. this._audioContext = new AudioContext();
  61854. // create a global volume gain node
  61855. this.masterGain = this._audioContext.createGain();
  61856. this.masterGain.gain.value = 1;
  61857. this.masterGain.connect(this._audioContext.destination);
  61858. this._audioContextInitialized = true;
  61859. }
  61860. }
  61861. catch (e) {
  61862. this.canUseWebAudio = false;
  61863. BABYLON.Tools.Error("Web Audio: " + e.message);
  61864. }
  61865. };
  61866. AudioEngine.prototype.dispose = function () {
  61867. if (this.canUseWebAudio && this._audioContextInitialized) {
  61868. if (this._connectedAnalyser && this._audioContext) {
  61869. this._connectedAnalyser.stopDebugCanvas();
  61870. this._connectedAnalyser.dispose();
  61871. this.masterGain.disconnect();
  61872. this.masterGain.connect(this._audioContext.destination);
  61873. this._connectedAnalyser = null;
  61874. }
  61875. this.masterGain.gain.value = 1;
  61876. }
  61877. this.WarnedWebAudioUnsupported = false;
  61878. };
  61879. AudioEngine.prototype.getGlobalVolume = function () {
  61880. if (this.canUseWebAudio && this._audioContextInitialized) {
  61881. return this.masterGain.gain.value;
  61882. }
  61883. else {
  61884. return -1;
  61885. }
  61886. };
  61887. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61888. if (this.canUseWebAudio && this._audioContextInitialized) {
  61889. this.masterGain.gain.value = newVolume;
  61890. }
  61891. };
  61892. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61893. if (this._connectedAnalyser) {
  61894. this._connectedAnalyser.stopDebugCanvas();
  61895. }
  61896. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61897. this._connectedAnalyser = analyser;
  61898. this.masterGain.disconnect();
  61899. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61900. }
  61901. };
  61902. return AudioEngine;
  61903. }());
  61904. BABYLON.AudioEngine = AudioEngine;
  61905. })(BABYLON || (BABYLON = {}));
  61906. //# sourceMappingURL=babylon.audioEngine.js.map
  61907. var BABYLON;
  61908. (function (BABYLON) {
  61909. var Sound = /** @class */ (function () {
  61910. /**
  61911. * Create a sound and attach it to a scene
  61912. * @param name Name of your sound
  61913. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61914. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61915. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61916. */
  61917. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61918. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61919. var _this = this;
  61920. this.autoplay = false;
  61921. this.loop = false;
  61922. this.useCustomAttenuation = false;
  61923. this.spatialSound = false;
  61924. this.refDistance = 1;
  61925. this.rolloffFactor = 1;
  61926. this.maxDistance = 100;
  61927. this.distanceModel = "linear";
  61928. this._panningModel = "equalpower";
  61929. this._playbackRate = 1;
  61930. this._streaming = false;
  61931. this._startTime = 0;
  61932. this._startOffset = 0;
  61933. this._position = BABYLON.Vector3.Zero();
  61934. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61935. this._volume = 1;
  61936. this._isReadyToPlay = false;
  61937. this.isPlaying = false;
  61938. this.isPaused = false;
  61939. this._isDirectional = false;
  61940. // Used if you'd like to create a directional sound.
  61941. // If not set, the sound will be omnidirectional
  61942. this._coneInnerAngle = 360;
  61943. this._coneOuterAngle = 360;
  61944. this._coneOuterGain = 0;
  61945. this._isOutputConnected = false;
  61946. this._urlType = "Unknown";
  61947. this.name = name;
  61948. this._scene = scene;
  61949. this._readyToPlayCallback = readyToPlayCallback;
  61950. // Default custom attenuation function is a linear attenuation
  61951. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61952. if (currentDistance < maxDistance) {
  61953. return currentVolume * (1 - currentDistance / maxDistance);
  61954. }
  61955. else {
  61956. return 0;
  61957. }
  61958. };
  61959. if (options) {
  61960. this.autoplay = options.autoplay || false;
  61961. this.loop = options.loop || false;
  61962. // if volume === 0, we need another way to check this option
  61963. if (options.volume !== undefined) {
  61964. this._volume = options.volume;
  61965. }
  61966. this.spatialSound = options.spatialSound || false;
  61967. this.maxDistance = options.maxDistance || 100;
  61968. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61969. this.rolloffFactor = options.rolloffFactor || 1;
  61970. this.refDistance = options.refDistance || 1;
  61971. this.distanceModel = options.distanceModel || "linear";
  61972. this._playbackRate = options.playbackRate || 1;
  61973. this._streaming = options.streaming || false;
  61974. }
  61975. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61976. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61977. this._soundGain.gain.value = this._volume;
  61978. this._inputAudioNode = this._soundGain;
  61979. this._ouputAudioNode = this._soundGain;
  61980. if (this.spatialSound) {
  61981. this._createSpatialParameters();
  61982. }
  61983. this._scene.mainSoundTrack.AddSound(this);
  61984. var validParameter = true;
  61985. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61986. if (urlOrArrayBuffer) {
  61987. try {
  61988. if (typeof (urlOrArrayBuffer) === "string")
  61989. this._urlType = "String";
  61990. if (Array.isArray(urlOrArrayBuffer))
  61991. this._urlType = "Array";
  61992. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61993. this._urlType = "ArrayBuffer";
  61994. var urls = [];
  61995. var codecSupportedFound = false;
  61996. switch (this._urlType) {
  61997. case "ArrayBuffer":
  61998. if (urlOrArrayBuffer.byteLength > 0) {
  61999. codecSupportedFound = true;
  62000. this._soundLoaded(urlOrArrayBuffer);
  62001. }
  62002. break;
  62003. case "String":
  62004. urls.push(urlOrArrayBuffer);
  62005. case "Array":
  62006. if (urls.length === 0)
  62007. urls = urlOrArrayBuffer;
  62008. // If we found a supported format, we load it immediately and stop the loop
  62009. for (var i = 0; i < urls.length; i++) {
  62010. var url = urls[i];
  62011. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62012. codecSupportedFound = true;
  62013. }
  62014. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62015. codecSupportedFound = true;
  62016. }
  62017. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62018. codecSupportedFound = true;
  62019. }
  62020. if (url.indexOf("blob:") !== -1) {
  62021. codecSupportedFound = true;
  62022. }
  62023. if (codecSupportedFound) {
  62024. // Loading sound using XHR2
  62025. if (!this._streaming) {
  62026. this._scene._loadFile(url, function (data) {
  62027. _this._soundLoaded(data);
  62028. }, undefined, true, true, function (exception) {
  62029. if (exception) {
  62030. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62031. }
  62032. BABYLON.Tools.Error("Sound creation aborted.");
  62033. _this._scene.mainSoundTrack.RemoveSound(_this);
  62034. });
  62035. }
  62036. // Streaming sound using HTML5 Audio tag
  62037. else {
  62038. this._htmlAudioElement = new Audio(url);
  62039. this._htmlAudioElement.controls = false;
  62040. this._htmlAudioElement.loop = this.loop;
  62041. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62042. this._htmlAudioElement.preload = "auto";
  62043. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62044. _this._isReadyToPlay = true;
  62045. if (_this.autoplay) {
  62046. _this.play();
  62047. }
  62048. if (_this._readyToPlayCallback) {
  62049. _this._readyToPlayCallback();
  62050. }
  62051. });
  62052. document.body.appendChild(this._htmlAudioElement);
  62053. }
  62054. break;
  62055. }
  62056. }
  62057. break;
  62058. default:
  62059. validParameter = false;
  62060. break;
  62061. }
  62062. if (!validParameter) {
  62063. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62064. }
  62065. else {
  62066. if (!codecSupportedFound) {
  62067. this._isReadyToPlay = true;
  62068. // Simulating a ready to play event to avoid breaking code path
  62069. if (this._readyToPlayCallback) {
  62070. window.setTimeout(function () {
  62071. if (_this._readyToPlayCallback) {
  62072. _this._readyToPlayCallback();
  62073. }
  62074. }, 1000);
  62075. }
  62076. }
  62077. }
  62078. }
  62079. catch (ex) {
  62080. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62081. this._scene.mainSoundTrack.RemoveSound(this);
  62082. }
  62083. }
  62084. }
  62085. else {
  62086. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62087. this._scene.mainSoundTrack.AddSound(this);
  62088. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62089. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62090. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62091. }
  62092. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62093. if (this._readyToPlayCallback) {
  62094. window.setTimeout(function () {
  62095. if (_this._readyToPlayCallback) {
  62096. _this._readyToPlayCallback();
  62097. }
  62098. }, 1000);
  62099. }
  62100. }
  62101. }
  62102. Sound.prototype.dispose = function () {
  62103. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62104. if (this.isPlaying) {
  62105. this.stop();
  62106. }
  62107. this._isReadyToPlay = false;
  62108. if (this.soundTrackId === -1) {
  62109. this._scene.mainSoundTrack.RemoveSound(this);
  62110. }
  62111. else {
  62112. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62113. }
  62114. if (this._soundGain) {
  62115. this._soundGain.disconnect();
  62116. this._soundGain = null;
  62117. }
  62118. if (this._soundPanner) {
  62119. this._soundPanner.disconnect();
  62120. this._soundPanner = null;
  62121. }
  62122. if (this._soundSource) {
  62123. this._soundSource.disconnect();
  62124. this._soundSource = null;
  62125. }
  62126. this._audioBuffer = null;
  62127. if (this._htmlAudioElement) {
  62128. this._htmlAudioElement.pause();
  62129. this._htmlAudioElement.src = "";
  62130. document.body.removeChild(this._htmlAudioElement);
  62131. }
  62132. if (this._connectedMesh && this._registerFunc) {
  62133. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62134. this._connectedMesh = null;
  62135. }
  62136. }
  62137. };
  62138. Sound.prototype.isReady = function () {
  62139. return this._isReadyToPlay;
  62140. };
  62141. Sound.prototype._soundLoaded = function (audioData) {
  62142. var _this = this;
  62143. if (!BABYLON.Engine.audioEngine.audioContext) {
  62144. return;
  62145. }
  62146. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62147. _this._audioBuffer = buffer;
  62148. _this._isReadyToPlay = true;
  62149. if (_this.autoplay) {
  62150. _this.play();
  62151. }
  62152. if (_this._readyToPlayCallback) {
  62153. _this._readyToPlayCallback();
  62154. }
  62155. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62156. };
  62157. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62158. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62159. this._audioBuffer = audioBuffer;
  62160. this._isReadyToPlay = true;
  62161. }
  62162. };
  62163. Sound.prototype.updateOptions = function (options) {
  62164. if (options) {
  62165. this.loop = options.loop || this.loop;
  62166. this.maxDistance = options.maxDistance || this.maxDistance;
  62167. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62168. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62169. this.refDistance = options.refDistance || this.refDistance;
  62170. this.distanceModel = options.distanceModel || this.distanceModel;
  62171. this._playbackRate = options.playbackRate || this._playbackRate;
  62172. this._updateSpatialParameters();
  62173. if (this.isPlaying) {
  62174. if (this._streaming) {
  62175. this._htmlAudioElement.playbackRate = this._playbackRate;
  62176. }
  62177. else {
  62178. if (this._soundSource) {
  62179. this._soundSource.playbackRate.value = this._playbackRate;
  62180. }
  62181. }
  62182. }
  62183. }
  62184. };
  62185. Sound.prototype._createSpatialParameters = function () {
  62186. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62187. if (this._scene.headphone) {
  62188. this._panningModel = "HRTF";
  62189. }
  62190. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62191. this._updateSpatialParameters();
  62192. this._soundPanner.connect(this._ouputAudioNode);
  62193. this._inputAudioNode = this._soundPanner;
  62194. }
  62195. };
  62196. Sound.prototype._updateSpatialParameters = function () {
  62197. if (this.spatialSound && this._soundPanner) {
  62198. if (this.useCustomAttenuation) {
  62199. // Tricks to disable in a way embedded Web Audio attenuation
  62200. this._soundPanner.distanceModel = "linear";
  62201. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62202. this._soundPanner.refDistance = 1;
  62203. this._soundPanner.rolloffFactor = 1;
  62204. this._soundPanner.panningModel = this._panningModel;
  62205. }
  62206. else {
  62207. this._soundPanner.distanceModel = this.distanceModel;
  62208. this._soundPanner.maxDistance = this.maxDistance;
  62209. this._soundPanner.refDistance = this.refDistance;
  62210. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62211. this._soundPanner.panningModel = this._panningModel;
  62212. }
  62213. }
  62214. };
  62215. Sound.prototype.switchPanningModelToHRTF = function () {
  62216. this._panningModel = "HRTF";
  62217. this._switchPanningModel();
  62218. };
  62219. Sound.prototype.switchPanningModelToEqualPower = function () {
  62220. this._panningModel = "equalpower";
  62221. this._switchPanningModel();
  62222. };
  62223. Sound.prototype._switchPanningModel = function () {
  62224. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62225. this._soundPanner.panningModel = this._panningModel;
  62226. }
  62227. };
  62228. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62229. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62230. if (this._isOutputConnected) {
  62231. this._ouputAudioNode.disconnect();
  62232. }
  62233. this._ouputAudioNode.connect(soundTrackAudioNode);
  62234. this._isOutputConnected = true;
  62235. }
  62236. };
  62237. /**
  62238. * Transform this sound into a directional source
  62239. * @param coneInnerAngle Size of the inner cone in degree
  62240. * @param coneOuterAngle Size of the outer cone in degree
  62241. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62242. */
  62243. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62244. if (coneOuterAngle < coneInnerAngle) {
  62245. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62246. return;
  62247. }
  62248. this._coneInnerAngle = coneInnerAngle;
  62249. this._coneOuterAngle = coneOuterAngle;
  62250. this._coneOuterGain = coneOuterGain;
  62251. this._isDirectional = true;
  62252. if (this.isPlaying && this.loop) {
  62253. this.stop();
  62254. this.play();
  62255. }
  62256. };
  62257. Sound.prototype.setPosition = function (newPosition) {
  62258. this._position = newPosition;
  62259. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62260. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62261. }
  62262. };
  62263. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62264. this._localDirection = newLocalDirection;
  62265. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62266. this._updateDirection();
  62267. }
  62268. };
  62269. Sound.prototype._updateDirection = function () {
  62270. if (!this._connectedMesh || !this._soundPanner) {
  62271. return;
  62272. }
  62273. var mat = this._connectedMesh.getWorldMatrix();
  62274. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62275. direction.normalize();
  62276. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62277. };
  62278. Sound.prototype.updateDistanceFromListener = function () {
  62279. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62280. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62281. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62282. }
  62283. };
  62284. Sound.prototype.setAttenuationFunction = function (callback) {
  62285. this._customAttenuationFunction = callback;
  62286. };
  62287. /**
  62288. * Play the sound
  62289. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62290. * @param offset (optional) Start the sound setting it at a specific time
  62291. */
  62292. Sound.prototype.play = function (time, offset) {
  62293. var _this = this;
  62294. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62295. try {
  62296. if (this._startOffset < 0) {
  62297. time = -this._startOffset;
  62298. this._startOffset = 0;
  62299. }
  62300. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62301. if (!this._soundSource || !this._streamingSource) {
  62302. if (this.spatialSound && this._soundPanner) {
  62303. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62304. if (this._isDirectional) {
  62305. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62306. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62307. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62308. if (this._connectedMesh) {
  62309. this._updateDirection();
  62310. }
  62311. else {
  62312. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62313. }
  62314. }
  62315. }
  62316. }
  62317. if (this._streaming) {
  62318. if (!this._streamingSource) {
  62319. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62320. this._htmlAudioElement.onended = function () { _this._onended(); };
  62321. this._htmlAudioElement.playbackRate = this._playbackRate;
  62322. }
  62323. this._streamingSource.disconnect();
  62324. this._streamingSource.connect(this._inputAudioNode);
  62325. this._htmlAudioElement.play();
  62326. }
  62327. else {
  62328. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62329. this._soundSource.buffer = this._audioBuffer;
  62330. this._soundSource.connect(this._inputAudioNode);
  62331. this._soundSource.loop = this.loop;
  62332. this._soundSource.playbackRate.value = this._playbackRate;
  62333. this._soundSource.onended = function () { _this._onended(); };
  62334. if (this._soundSource.buffer) {
  62335. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62336. }
  62337. }
  62338. this._startTime = startTime;
  62339. this.isPlaying = true;
  62340. this.isPaused = false;
  62341. }
  62342. catch (ex) {
  62343. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62344. }
  62345. }
  62346. };
  62347. Sound.prototype._onended = function () {
  62348. this.isPlaying = false;
  62349. if (this.onended) {
  62350. this.onended();
  62351. }
  62352. };
  62353. /**
  62354. * Stop the sound
  62355. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62356. */
  62357. Sound.prototype.stop = function (time) {
  62358. if (this.isPlaying) {
  62359. if (this._streaming) {
  62360. this._htmlAudioElement.pause();
  62361. // Test needed for Firefox or it will generate an Invalid State Error
  62362. if (this._htmlAudioElement.currentTime > 0) {
  62363. this._htmlAudioElement.currentTime = 0;
  62364. }
  62365. }
  62366. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62367. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62368. this._soundSource.stop(stopTime);
  62369. this._soundSource.onended = function () { };
  62370. if (!this.isPaused) {
  62371. this._startOffset = 0;
  62372. }
  62373. }
  62374. this.isPlaying = false;
  62375. }
  62376. };
  62377. Sound.prototype.pause = function () {
  62378. if (this.isPlaying) {
  62379. this.isPaused = true;
  62380. if (this._streaming) {
  62381. this._htmlAudioElement.pause();
  62382. }
  62383. else if (BABYLON.Engine.audioEngine.audioContext) {
  62384. this.stop(0);
  62385. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62386. }
  62387. }
  62388. };
  62389. Sound.prototype.setVolume = function (newVolume, time) {
  62390. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62391. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62392. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62393. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62394. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62395. }
  62396. else {
  62397. this._soundGain.gain.value = newVolume;
  62398. }
  62399. }
  62400. this._volume = newVolume;
  62401. };
  62402. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62403. this._playbackRate = newPlaybackRate;
  62404. if (this.isPlaying) {
  62405. if (this._streaming) {
  62406. this._htmlAudioElement.playbackRate = this._playbackRate;
  62407. }
  62408. else if (this._soundSource) {
  62409. this._soundSource.playbackRate.value = this._playbackRate;
  62410. }
  62411. }
  62412. };
  62413. Sound.prototype.getVolume = function () {
  62414. return this._volume;
  62415. };
  62416. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62417. var _this = this;
  62418. if (this._connectedMesh && this._registerFunc) {
  62419. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62420. this._registerFunc = null;
  62421. }
  62422. this._connectedMesh = meshToConnectTo;
  62423. if (!this.spatialSound) {
  62424. this.spatialSound = true;
  62425. this._createSpatialParameters();
  62426. if (this.isPlaying && this.loop) {
  62427. this.stop();
  62428. this.play();
  62429. }
  62430. }
  62431. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62432. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62433. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62434. };
  62435. Sound.prototype.detachFromMesh = function () {
  62436. if (this._connectedMesh && this._registerFunc) {
  62437. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62438. this._registerFunc = null;
  62439. this._connectedMesh = null;
  62440. }
  62441. };
  62442. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62443. if (!node.getBoundingInfo) {
  62444. return;
  62445. }
  62446. var mesh = node;
  62447. var boundingInfo = mesh.getBoundingInfo();
  62448. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62449. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62450. this._updateDirection();
  62451. }
  62452. };
  62453. Sound.prototype.clone = function () {
  62454. var _this = this;
  62455. if (!this._streaming) {
  62456. var setBufferAndRun = function () {
  62457. if (_this._isReadyToPlay) {
  62458. clonedSound._audioBuffer = _this.getAudioBuffer();
  62459. clonedSound._isReadyToPlay = true;
  62460. if (clonedSound.autoplay) {
  62461. clonedSound.play();
  62462. }
  62463. }
  62464. else {
  62465. window.setTimeout(setBufferAndRun, 300);
  62466. }
  62467. };
  62468. var currentOptions = {
  62469. autoplay: this.autoplay, loop: this.loop,
  62470. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62471. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62472. refDistance: this.refDistance, distanceModel: this.distanceModel
  62473. };
  62474. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62475. if (this.useCustomAttenuation) {
  62476. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62477. }
  62478. clonedSound.setPosition(this._position);
  62479. clonedSound.setPlaybackRate(this._playbackRate);
  62480. setBufferAndRun();
  62481. return clonedSound;
  62482. }
  62483. // Can't clone a streaming sound
  62484. else {
  62485. return null;
  62486. }
  62487. };
  62488. Sound.prototype.getAudioBuffer = function () {
  62489. return this._audioBuffer;
  62490. };
  62491. Sound.prototype.serialize = function () {
  62492. var serializationObject = {
  62493. name: this.name,
  62494. url: this.name,
  62495. autoplay: this.autoplay,
  62496. loop: this.loop,
  62497. volume: this._volume,
  62498. spatialSound: this.spatialSound,
  62499. maxDistance: this.maxDistance,
  62500. rolloffFactor: this.rolloffFactor,
  62501. refDistance: this.refDistance,
  62502. distanceModel: this.distanceModel,
  62503. playbackRate: this._playbackRate,
  62504. panningModel: this._panningModel,
  62505. soundTrackId: this.soundTrackId
  62506. };
  62507. if (this.spatialSound) {
  62508. if (this._connectedMesh)
  62509. serializationObject.connectedMeshId = this._connectedMesh.id;
  62510. serializationObject.position = this._position.asArray();
  62511. serializationObject.refDistance = this.refDistance;
  62512. serializationObject.distanceModel = this.distanceModel;
  62513. serializationObject.isDirectional = this._isDirectional;
  62514. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62515. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62516. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62517. serializationObject.coneOuterGain = this._coneOuterGain;
  62518. }
  62519. return serializationObject;
  62520. };
  62521. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62522. var soundName = parsedSound.name;
  62523. var soundUrl;
  62524. if (parsedSound.url) {
  62525. soundUrl = rootUrl + parsedSound.url;
  62526. }
  62527. else {
  62528. soundUrl = rootUrl + soundName;
  62529. }
  62530. var options = {
  62531. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62532. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62533. rolloffFactor: parsedSound.rolloffFactor,
  62534. refDistance: parsedSound.refDistance,
  62535. distanceModel: parsedSound.distanceModel,
  62536. playbackRate: parsedSound.playbackRate
  62537. };
  62538. var newSound;
  62539. if (!sourceSound) {
  62540. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62541. scene._addPendingData(newSound);
  62542. }
  62543. else {
  62544. var setBufferAndRun = function () {
  62545. if (sourceSound._isReadyToPlay) {
  62546. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62547. newSound._isReadyToPlay = true;
  62548. if (newSound.autoplay) {
  62549. newSound.play();
  62550. }
  62551. }
  62552. else {
  62553. window.setTimeout(setBufferAndRun, 300);
  62554. }
  62555. };
  62556. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62557. setBufferAndRun();
  62558. }
  62559. if (parsedSound.position) {
  62560. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62561. newSound.setPosition(soundPosition);
  62562. }
  62563. if (parsedSound.isDirectional) {
  62564. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62565. if (parsedSound.localDirectionToMesh) {
  62566. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62567. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62568. }
  62569. }
  62570. if (parsedSound.connectedMeshId) {
  62571. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62572. if (connectedMesh) {
  62573. newSound.attachToMesh(connectedMesh);
  62574. }
  62575. }
  62576. return newSound;
  62577. };
  62578. return Sound;
  62579. }());
  62580. BABYLON.Sound = Sound;
  62581. })(BABYLON || (BABYLON = {}));
  62582. //# sourceMappingURL=babylon.sound.js.map
  62583. var BABYLON;
  62584. (function (BABYLON) {
  62585. var SoundTrack = /** @class */ (function () {
  62586. function SoundTrack(scene, options) {
  62587. this.id = -1;
  62588. this._isMainTrack = false;
  62589. this._isInitialized = false;
  62590. this._scene = scene;
  62591. this.soundCollection = new Array();
  62592. this._options = options;
  62593. if (!this._isMainTrack) {
  62594. this._scene.soundTracks.push(this);
  62595. this.id = this._scene.soundTracks.length - 1;
  62596. }
  62597. }
  62598. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62599. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62600. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62601. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62602. if (this._options) {
  62603. if (this._options.volume) {
  62604. this._outputAudioNode.gain.value = this._options.volume;
  62605. }
  62606. if (this._options.mainTrack) {
  62607. this._isMainTrack = this._options.mainTrack;
  62608. }
  62609. }
  62610. this._isInitialized = true;
  62611. }
  62612. };
  62613. SoundTrack.prototype.dispose = function () {
  62614. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62615. if (this._connectedAnalyser) {
  62616. this._connectedAnalyser.stopDebugCanvas();
  62617. }
  62618. while (this.soundCollection.length) {
  62619. this.soundCollection[0].dispose();
  62620. }
  62621. if (this._outputAudioNode) {
  62622. this._outputAudioNode.disconnect();
  62623. }
  62624. this._outputAudioNode = null;
  62625. }
  62626. };
  62627. SoundTrack.prototype.AddSound = function (sound) {
  62628. if (!this._isInitialized) {
  62629. this._initializeSoundTrackAudioGraph();
  62630. }
  62631. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62632. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62633. }
  62634. if (sound.soundTrackId) {
  62635. if (sound.soundTrackId === -1) {
  62636. this._scene.mainSoundTrack.RemoveSound(sound);
  62637. }
  62638. else {
  62639. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62640. }
  62641. }
  62642. this.soundCollection.push(sound);
  62643. sound.soundTrackId = this.id;
  62644. };
  62645. SoundTrack.prototype.RemoveSound = function (sound) {
  62646. var index = this.soundCollection.indexOf(sound);
  62647. if (index !== -1) {
  62648. this.soundCollection.splice(index, 1);
  62649. }
  62650. };
  62651. SoundTrack.prototype.setVolume = function (newVolume) {
  62652. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62653. this._outputAudioNode.gain.value = newVolume;
  62654. }
  62655. };
  62656. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62657. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62658. for (var i = 0; i < this.soundCollection.length; i++) {
  62659. this.soundCollection[i].switchPanningModelToHRTF();
  62660. }
  62661. }
  62662. };
  62663. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62664. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62665. for (var i = 0; i < this.soundCollection.length; i++) {
  62666. this.soundCollection[i].switchPanningModelToEqualPower();
  62667. }
  62668. }
  62669. };
  62670. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62671. if (this._connectedAnalyser) {
  62672. this._connectedAnalyser.stopDebugCanvas();
  62673. }
  62674. this._connectedAnalyser = analyser;
  62675. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62676. this._outputAudioNode.disconnect();
  62677. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62678. }
  62679. };
  62680. return SoundTrack;
  62681. }());
  62682. BABYLON.SoundTrack = SoundTrack;
  62683. })(BABYLON || (BABYLON = {}));
  62684. //# sourceMappingURL=babylon.soundtrack.js.map
  62685. var BABYLON;
  62686. (function (BABYLON) {
  62687. /**
  62688. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62689. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62690. */
  62691. var Analyser = /** @class */ (function () {
  62692. /**
  62693. * Creates a new analyser
  62694. * @param scene defines hosting scene
  62695. */
  62696. function Analyser(scene) {
  62697. /**
  62698. * Gets or sets the smoothing
  62699. * @ignorenaming
  62700. */
  62701. this.SMOOTHING = 0.75;
  62702. /**
  62703. * Gets or sets the FFT table size
  62704. * @ignorenaming
  62705. */
  62706. this.FFT_SIZE = 512;
  62707. /**
  62708. * Gets or sets the bar graph amplitude
  62709. * @ignorenaming
  62710. */
  62711. this.BARGRAPHAMPLITUDE = 256;
  62712. /**
  62713. * Gets or sets the position of the debug canvas
  62714. * @ignorenaming
  62715. */
  62716. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62717. /**
  62718. * Gets or sets the debug canvas size
  62719. * @ignorenaming
  62720. */
  62721. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62722. this._scene = scene;
  62723. this._audioEngine = BABYLON.Engine.audioEngine;
  62724. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62725. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62726. this._webAudioAnalyser.minDecibels = -140;
  62727. this._webAudioAnalyser.maxDecibels = 0;
  62728. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62729. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62730. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62731. }
  62732. }
  62733. /**
  62734. * Get the number of data values you will have to play with for the visualization
  62735. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62736. * @returns a number
  62737. */
  62738. Analyser.prototype.getFrequencyBinCount = function () {
  62739. if (this._audioEngine.canUseWebAudio) {
  62740. return this._webAudioAnalyser.frequencyBinCount;
  62741. }
  62742. else {
  62743. return 0;
  62744. }
  62745. };
  62746. /**
  62747. * Gets the current frequency data as a byte array
  62748. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62749. * @returns a Uint8Array
  62750. */
  62751. Analyser.prototype.getByteFrequencyData = function () {
  62752. if (this._audioEngine.canUseWebAudio) {
  62753. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62754. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62755. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62756. }
  62757. return this._byteFreqs;
  62758. };
  62759. /**
  62760. * Gets the current waveform as a byte array
  62761. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62762. * @returns a Uint8Array
  62763. */
  62764. Analyser.prototype.getByteTimeDomainData = function () {
  62765. if (this._audioEngine.canUseWebAudio) {
  62766. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62767. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62768. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62769. }
  62770. return this._byteTime;
  62771. };
  62772. /**
  62773. * Gets the current frequency data as a float array
  62774. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62775. * @returns a Float32Array
  62776. */
  62777. Analyser.prototype.getFloatFrequencyData = function () {
  62778. if (this._audioEngine.canUseWebAudio) {
  62779. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62780. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62781. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62782. }
  62783. return this._floatFreqs;
  62784. };
  62785. /**
  62786. * Renders the debug canvas
  62787. */
  62788. Analyser.prototype.drawDebugCanvas = function () {
  62789. var _this = this;
  62790. if (this._audioEngine.canUseWebAudio) {
  62791. if (!this._debugCanvas) {
  62792. this._debugCanvas = document.createElement("canvas");
  62793. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62794. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62795. this._debugCanvas.style.position = "absolute";
  62796. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62797. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62798. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62799. document.body.appendChild(this._debugCanvas);
  62800. this._registerFunc = function () {
  62801. _this.drawDebugCanvas();
  62802. };
  62803. this._scene.registerBeforeRender(this._registerFunc);
  62804. }
  62805. if (this._registerFunc && this._debugCanvasContext) {
  62806. var workingArray = this.getByteFrequencyData();
  62807. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62808. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62809. // Draw the frequency domain chart.
  62810. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62811. var value = workingArray[i];
  62812. var percent = value / this.BARGRAPHAMPLITUDE;
  62813. var height = this.DEBUGCANVASSIZE.height * percent;
  62814. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62815. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62816. var hue = i / this.getFrequencyBinCount() * 360;
  62817. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62818. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62819. }
  62820. }
  62821. }
  62822. };
  62823. /**
  62824. * Stops rendering the debug canvas and removes it
  62825. */
  62826. Analyser.prototype.stopDebugCanvas = function () {
  62827. if (this._debugCanvas) {
  62828. if (this._registerFunc) {
  62829. this._scene.unregisterBeforeRender(this._registerFunc);
  62830. this._registerFunc = null;
  62831. }
  62832. document.body.removeChild(this._debugCanvas);
  62833. this._debugCanvas = null;
  62834. this._debugCanvasContext = null;
  62835. }
  62836. };
  62837. /**
  62838. * Connects two audio nodes
  62839. * @param inputAudioNode defines first node to connect
  62840. * @param outputAudioNode defines second node to connect
  62841. */
  62842. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62843. if (this._audioEngine.canUseWebAudio) {
  62844. inputAudioNode.connect(this._webAudioAnalyser);
  62845. this._webAudioAnalyser.connect(outputAudioNode);
  62846. }
  62847. };
  62848. /**
  62849. * Releases all associated resources
  62850. */
  62851. Analyser.prototype.dispose = function () {
  62852. if (this._audioEngine.canUseWebAudio) {
  62853. this._webAudioAnalyser.disconnect();
  62854. }
  62855. };
  62856. return Analyser;
  62857. }());
  62858. BABYLON.Analyser = Analyser;
  62859. })(BABYLON || (BABYLON = {}));
  62860. //# sourceMappingURL=babylon.analyser.js.map
  62861. var BABYLON;
  62862. (function (BABYLON) {
  62863. var CubeTexture = /** @class */ (function (_super) {
  62864. __extends(CubeTexture, _super);
  62865. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62866. if (extensions === void 0) { extensions = null; }
  62867. if (noMipmap === void 0) { noMipmap = false; }
  62868. if (files === void 0) { files = null; }
  62869. if (onLoad === void 0) { onLoad = null; }
  62870. if (onError === void 0) { onError = null; }
  62871. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62872. if (prefiltered === void 0) { prefiltered = false; }
  62873. if (forcedExtension === void 0) { forcedExtension = null; }
  62874. var _this = _super.call(this, scene) || this;
  62875. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62876. /**
  62877. * Gets or sets the center of the bounding box associated with the cube texture
  62878. * It must define where the camera used to render the texture was set
  62879. */
  62880. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62881. _this._rotationY = 0;
  62882. _this.name = rootUrl;
  62883. _this.url = rootUrl;
  62884. _this._noMipmap = noMipmap;
  62885. _this.hasAlpha = false;
  62886. _this._format = format;
  62887. _this._prefiltered = prefiltered;
  62888. _this.isCube = true;
  62889. _this._textureMatrix = BABYLON.Matrix.Identity();
  62890. if (prefiltered) {
  62891. _this.gammaSpace = false;
  62892. }
  62893. if (!rootUrl && !files) {
  62894. return _this;
  62895. }
  62896. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62897. var lastDot = rootUrl.lastIndexOf(".");
  62898. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62899. var isDDS = (extension === ".dds");
  62900. if (!files) {
  62901. if (!isDDS && !extensions) {
  62902. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62903. }
  62904. files = [];
  62905. if (extensions) {
  62906. for (var index = 0; index < extensions.length; index++) {
  62907. files.push(rootUrl + extensions[index]);
  62908. }
  62909. }
  62910. }
  62911. _this._files = files;
  62912. if (!_this._texture) {
  62913. if (!scene.useDelayedTextureLoading) {
  62914. if (prefiltered) {
  62915. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62916. }
  62917. else {
  62918. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62919. }
  62920. }
  62921. else {
  62922. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62923. }
  62924. }
  62925. else if (onLoad) {
  62926. if (_this._texture.isReady) {
  62927. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62928. }
  62929. else {
  62930. _this._texture.onLoadedObservable.add(onLoad);
  62931. }
  62932. }
  62933. return _this;
  62934. }
  62935. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62936. get: function () {
  62937. return this._boundingBoxSize;
  62938. },
  62939. /**
  62940. * Gets or sets the size of the bounding box associated with the cube texture
  62941. * When defined, the cubemap will switch to local mode
  62942. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62943. * @example https://www.babylonjs-playground.com/#RNASML
  62944. */
  62945. set: function (value) {
  62946. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62947. return;
  62948. }
  62949. this._boundingBoxSize = value;
  62950. var scene = this.getScene();
  62951. if (scene) {
  62952. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62953. }
  62954. },
  62955. enumerable: true,
  62956. configurable: true
  62957. });
  62958. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62959. /**
  62960. * Gets texture matrix rotation angle around Y axis radians.
  62961. */
  62962. get: function () {
  62963. return this._rotationY;
  62964. },
  62965. /**
  62966. * Sets texture matrix rotation angle around Y axis in radians.
  62967. */
  62968. set: function (value) {
  62969. this._rotationY = value;
  62970. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62971. },
  62972. enumerable: true,
  62973. configurable: true
  62974. });
  62975. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62976. var rootUrlKey = "";
  62977. files.forEach(function (url) { return rootUrlKey += url; });
  62978. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62979. };
  62980. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62981. if (forcedExtension === void 0) { forcedExtension = null; }
  62982. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62983. };
  62984. // Methods
  62985. CubeTexture.prototype.delayLoad = function () {
  62986. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62987. return;
  62988. }
  62989. var scene = this.getScene();
  62990. if (!scene) {
  62991. return;
  62992. }
  62993. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62994. this._texture = this._getFromCache(this.url, this._noMipmap);
  62995. if (!this._texture) {
  62996. if (this._prefiltered) {
  62997. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  62998. }
  62999. else {
  63000. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63001. }
  63002. }
  63003. };
  63004. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63005. return this._textureMatrix;
  63006. };
  63007. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63008. this._textureMatrix = value;
  63009. };
  63010. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63011. var texture = BABYLON.SerializationHelper.Parse(function () {
  63012. var prefiltered = false;
  63013. if (parsedTexture.prefiltered) {
  63014. prefiltered = parsedTexture.prefiltered;
  63015. }
  63016. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63017. }, parsedTexture, scene);
  63018. // Local Cubemaps
  63019. if (parsedTexture.boundingBoxPosition) {
  63020. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63021. }
  63022. if (parsedTexture.boundingBoxSize) {
  63023. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63024. }
  63025. // Animations
  63026. if (parsedTexture.animations) {
  63027. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63028. var parsedAnimation = parsedTexture.animations[animationIndex];
  63029. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63030. }
  63031. }
  63032. return texture;
  63033. };
  63034. CubeTexture.prototype.clone = function () {
  63035. var _this = this;
  63036. return BABYLON.SerializationHelper.Clone(function () {
  63037. var scene = _this.getScene();
  63038. if (!scene) {
  63039. return _this;
  63040. }
  63041. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63042. }, this);
  63043. };
  63044. __decorate([
  63045. BABYLON.serialize("rotationY")
  63046. ], CubeTexture.prototype, "_rotationY", void 0);
  63047. return CubeTexture;
  63048. }(BABYLON.BaseTexture));
  63049. BABYLON.CubeTexture = CubeTexture;
  63050. })(BABYLON || (BABYLON = {}));
  63051. //# sourceMappingURL=babylon.cubeTexture.js.map
  63052. var BABYLON;
  63053. (function (BABYLON) {
  63054. var RenderTargetTexture = /** @class */ (function (_super) {
  63055. __extends(RenderTargetTexture, _super);
  63056. /**
  63057. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63058. * or used a shadow, depth texture...
  63059. * @param name The friendly name of the texture
  63060. * @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)
  63061. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63062. * @param generateMipMaps True if mip maps need to be generated after render.
  63063. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63064. * @param type The type of the buffer in the RTT (int, half float, float...)
  63065. * @param isCube True if a cube texture needs to be created
  63066. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63067. * @param generateDepthBuffer True to generate a depth buffer
  63068. * @param generateStencilBuffer True to generate a stencil buffer
  63069. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63070. */
  63071. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63072. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63073. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63074. if (isCube === void 0) { isCube = false; }
  63075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63076. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63077. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63078. if (isMulti === void 0) { isMulti = false; }
  63079. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63080. _this.isCube = isCube;
  63081. /**
  63082. * Use this list to define the list of mesh you want to render.
  63083. */
  63084. _this.renderList = new Array();
  63085. _this.renderParticles = true;
  63086. _this.renderSprites = false;
  63087. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63088. _this.ignoreCameraViewport = false;
  63089. // Events
  63090. /**
  63091. * An event triggered when the texture is unbind.
  63092. */
  63093. _this.onBeforeBindObservable = new BABYLON.Observable();
  63094. /**
  63095. * An event triggered when the texture is unbind.
  63096. */
  63097. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63098. /**
  63099. * An event triggered before rendering the texture
  63100. */
  63101. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63102. /**
  63103. * An event triggered after rendering the texture
  63104. */
  63105. _this.onAfterRenderObservable = new BABYLON.Observable();
  63106. /**
  63107. * An event triggered after the texture clear
  63108. */
  63109. _this.onClearObservable = new BABYLON.Observable();
  63110. _this._currentRefreshId = -1;
  63111. _this._refreshRate = 1;
  63112. _this._samples = 1;
  63113. /**
  63114. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63115. * It must define where the camera used to render the texture is set
  63116. */
  63117. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63118. scene = _this.getScene();
  63119. if (!scene) {
  63120. return _this;
  63121. }
  63122. _this._engine = scene.getEngine();
  63123. _this.name = name;
  63124. _this.isRenderTarget = true;
  63125. _this._initialSizeParameter = size;
  63126. _this._processSizeParameter(size);
  63127. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63128. });
  63129. _this._generateMipMaps = generateMipMaps ? true : false;
  63130. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63131. // Rendering groups
  63132. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63133. if (isMulti) {
  63134. return _this;
  63135. }
  63136. _this._renderTargetOptions = {
  63137. generateMipMaps: generateMipMaps,
  63138. type: type,
  63139. samplingMode: samplingMode,
  63140. generateDepthBuffer: generateDepthBuffer,
  63141. generateStencilBuffer: generateStencilBuffer
  63142. };
  63143. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63144. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63145. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63146. }
  63147. if (isCube) {
  63148. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63149. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63150. _this._textureMatrix = BABYLON.Matrix.Identity();
  63151. }
  63152. else {
  63153. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63154. }
  63155. return _this;
  63156. }
  63157. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63158. get: function () {
  63159. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63160. },
  63161. enumerable: true,
  63162. configurable: true
  63163. });
  63164. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63165. get: function () {
  63166. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63167. },
  63168. enumerable: true,
  63169. configurable: true
  63170. });
  63171. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63172. get: function () {
  63173. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63174. },
  63175. enumerable: true,
  63176. configurable: true
  63177. });
  63178. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63179. set: function (callback) {
  63180. if (this._onAfterUnbindObserver) {
  63181. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63182. }
  63183. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63184. },
  63185. enumerable: true,
  63186. configurable: true
  63187. });
  63188. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63189. set: function (callback) {
  63190. if (this._onBeforeRenderObserver) {
  63191. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63192. }
  63193. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63194. },
  63195. enumerable: true,
  63196. configurable: true
  63197. });
  63198. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63199. set: function (callback) {
  63200. if (this._onAfterRenderObserver) {
  63201. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63202. }
  63203. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63204. },
  63205. enumerable: true,
  63206. configurable: true
  63207. });
  63208. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63209. set: function (callback) {
  63210. if (this._onClearObserver) {
  63211. this.onClearObservable.remove(this._onClearObserver);
  63212. }
  63213. this._onClearObserver = this.onClearObservable.add(callback);
  63214. },
  63215. enumerable: true,
  63216. configurable: true
  63217. });
  63218. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63219. get: function () {
  63220. return this._renderTargetOptions;
  63221. },
  63222. enumerable: true,
  63223. configurable: true
  63224. });
  63225. RenderTargetTexture.prototype._onRatioRescale = function () {
  63226. if (this._sizeRatio) {
  63227. this.resize(this._initialSizeParameter);
  63228. }
  63229. };
  63230. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63231. get: function () {
  63232. return this._boundingBoxSize;
  63233. },
  63234. /**
  63235. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63236. * When defined, the cubemap will switch to local mode
  63237. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63238. * @example https://www.babylonjs-playground.com/#RNASML
  63239. */
  63240. set: function (value) {
  63241. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63242. return;
  63243. }
  63244. this._boundingBoxSize = value;
  63245. var scene = this.getScene();
  63246. if (scene) {
  63247. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63248. }
  63249. },
  63250. enumerable: true,
  63251. configurable: true
  63252. });
  63253. /**
  63254. * Creates a depth stencil texture.
  63255. * This is only available in WebGL 2 or with the depth texture extension available.
  63256. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63257. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63258. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63259. */
  63260. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63261. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63262. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63263. if (generateStencil === void 0) { generateStencil = false; }
  63264. if (!this.getScene()) {
  63265. return;
  63266. }
  63267. var engine = this.getScene().getEngine();
  63268. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63269. bilinearFiltering: bilinearFiltering,
  63270. comparisonFunction: comparisonFunction,
  63271. generateStencil: generateStencil,
  63272. isCube: this.isCube
  63273. });
  63274. engine.setFrameBufferDepthStencilTexture(this);
  63275. };
  63276. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63277. if (size.ratio) {
  63278. this._sizeRatio = size.ratio;
  63279. this._size = {
  63280. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63281. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63282. };
  63283. }
  63284. else {
  63285. this._size = size;
  63286. }
  63287. };
  63288. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63289. get: function () {
  63290. return this._samples;
  63291. },
  63292. set: function (value) {
  63293. if (this._samples === value) {
  63294. return;
  63295. }
  63296. var scene = this.getScene();
  63297. if (!scene) {
  63298. return;
  63299. }
  63300. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63301. },
  63302. enumerable: true,
  63303. configurable: true
  63304. });
  63305. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63306. this._currentRefreshId = -1;
  63307. };
  63308. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63309. get: function () {
  63310. return this._refreshRate;
  63311. },
  63312. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63313. set: function (value) {
  63314. this._refreshRate = value;
  63315. this.resetRefreshCounter();
  63316. },
  63317. enumerable: true,
  63318. configurable: true
  63319. });
  63320. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63321. if (!this._postProcessManager) {
  63322. var scene = this.getScene();
  63323. if (!scene) {
  63324. return;
  63325. }
  63326. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63327. this._postProcesses = new Array();
  63328. }
  63329. this._postProcesses.push(postProcess);
  63330. this._postProcesses[0].autoClear = false;
  63331. };
  63332. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63333. if (!this._postProcesses) {
  63334. return;
  63335. }
  63336. if (dispose) {
  63337. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63338. var postProcess = _a[_i];
  63339. postProcess.dispose();
  63340. }
  63341. }
  63342. this._postProcesses = [];
  63343. };
  63344. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63345. if (!this._postProcesses) {
  63346. return;
  63347. }
  63348. var index = this._postProcesses.indexOf(postProcess);
  63349. if (index === -1) {
  63350. return;
  63351. }
  63352. this._postProcesses.splice(index, 1);
  63353. if (this._postProcesses.length > 0) {
  63354. this._postProcesses[0].autoClear = false;
  63355. }
  63356. };
  63357. RenderTargetTexture.prototype._shouldRender = function () {
  63358. if (this._currentRefreshId === -1) { // At least render once
  63359. this._currentRefreshId = 1;
  63360. return true;
  63361. }
  63362. if (this.refreshRate === this._currentRefreshId) {
  63363. this._currentRefreshId = 1;
  63364. return true;
  63365. }
  63366. this._currentRefreshId++;
  63367. return false;
  63368. };
  63369. RenderTargetTexture.prototype.getRenderSize = function () {
  63370. if (this._size.width) {
  63371. return this._size.width;
  63372. }
  63373. return this._size;
  63374. };
  63375. RenderTargetTexture.prototype.getRenderWidth = function () {
  63376. if (this._size.width) {
  63377. return this._size.width;
  63378. }
  63379. return this._size;
  63380. };
  63381. RenderTargetTexture.prototype.getRenderHeight = function () {
  63382. if (this._size.width) {
  63383. return this._size.height;
  63384. }
  63385. return this._size;
  63386. };
  63387. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63388. get: function () {
  63389. return true;
  63390. },
  63391. enumerable: true,
  63392. configurable: true
  63393. });
  63394. RenderTargetTexture.prototype.scale = function (ratio) {
  63395. var newSize = this.getRenderSize() * ratio;
  63396. this.resize(newSize);
  63397. };
  63398. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63399. if (this.isCube) {
  63400. return this._textureMatrix;
  63401. }
  63402. return _super.prototype.getReflectionTextureMatrix.call(this);
  63403. };
  63404. RenderTargetTexture.prototype.resize = function (size) {
  63405. this.releaseInternalTexture();
  63406. var scene = this.getScene();
  63407. if (!scene) {
  63408. return;
  63409. }
  63410. this._processSizeParameter(size);
  63411. if (this.isCube) {
  63412. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63413. }
  63414. else {
  63415. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63416. }
  63417. };
  63418. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63419. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63420. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63421. var scene = this.getScene();
  63422. if (!scene) {
  63423. return;
  63424. }
  63425. var engine = scene.getEngine();
  63426. if (this.useCameraPostProcesses !== undefined) {
  63427. useCameraPostProcess = this.useCameraPostProcesses;
  63428. }
  63429. if (this._waitingRenderList) {
  63430. this.renderList = [];
  63431. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63432. var id = this._waitingRenderList[index];
  63433. var mesh_1 = scene.getMeshByID(id);
  63434. if (mesh_1) {
  63435. this.renderList.push(mesh_1);
  63436. }
  63437. }
  63438. delete this._waitingRenderList;
  63439. }
  63440. // Is predicate defined?
  63441. if (this.renderListPredicate) {
  63442. if (this.renderList) {
  63443. this.renderList.splice(0); // Clear previous renderList
  63444. }
  63445. else {
  63446. this.renderList = [];
  63447. }
  63448. var scene = this.getScene();
  63449. if (!scene) {
  63450. return;
  63451. }
  63452. var sceneMeshes = scene.meshes;
  63453. for (var index = 0; index < sceneMeshes.length; index++) {
  63454. var mesh = sceneMeshes[index];
  63455. if (this.renderListPredicate(mesh)) {
  63456. this.renderList.push(mesh);
  63457. }
  63458. }
  63459. }
  63460. this.onBeforeBindObservable.notifyObservers(this);
  63461. // Set custom projection.
  63462. // Needs to be before binding to prevent changing the aspect ratio.
  63463. var camera;
  63464. if (this.activeCamera) {
  63465. camera = this.activeCamera;
  63466. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63467. if (this.activeCamera !== scene.activeCamera) {
  63468. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63469. }
  63470. }
  63471. else {
  63472. camera = scene.activeCamera;
  63473. if (camera) {
  63474. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63475. }
  63476. }
  63477. // Prepare renderingManager
  63478. this._renderingManager.reset();
  63479. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63480. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63481. var sceneRenderId = scene.getRenderId();
  63482. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63483. var mesh = currentRenderList[meshIndex];
  63484. if (mesh) {
  63485. if (!mesh.isReady(this.refreshRate === 0)) {
  63486. this.resetRefreshCounter();
  63487. continue;
  63488. }
  63489. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63490. var isMasked = void 0;
  63491. if (!this.renderList && camera) {
  63492. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63493. }
  63494. else {
  63495. isMasked = false;
  63496. }
  63497. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63498. mesh._activate(sceneRenderId);
  63499. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63500. var subMesh = mesh.subMeshes[subIndex];
  63501. scene._activeIndices.addCount(subMesh.indexCount, false);
  63502. this._renderingManager.dispatch(subMesh, mesh);
  63503. }
  63504. }
  63505. }
  63506. }
  63507. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63508. var particleSystem = scene.particleSystems[particleIndex];
  63509. var emitter = particleSystem.emitter;
  63510. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63511. continue;
  63512. }
  63513. if (currentRenderList.indexOf(emitter) >= 0) {
  63514. this._renderingManager.dispatchParticles(particleSystem);
  63515. }
  63516. }
  63517. if (this.isCube) {
  63518. for (var face = 0; face < 6; face++) {
  63519. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63520. scene.incrementRenderId();
  63521. scene.resetCachedMaterial();
  63522. }
  63523. }
  63524. else {
  63525. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63526. }
  63527. this.onAfterUnbindObservable.notifyObservers(this);
  63528. if (scene.activeCamera) {
  63529. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63530. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63531. }
  63532. engine.setViewport(scene.activeCamera.viewport);
  63533. }
  63534. scene.resetCachedMaterial();
  63535. };
  63536. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63537. var minimum = 128;
  63538. var x = renderDimension * scale;
  63539. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63540. // Ensure we don't exceed the render dimension (while staying POT)
  63541. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63542. };
  63543. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63544. var _this = this;
  63545. if (!this._texture) {
  63546. return;
  63547. }
  63548. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63549. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63550. });
  63551. };
  63552. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63553. var scene = this.getScene();
  63554. if (!scene) {
  63555. return;
  63556. }
  63557. var engine = scene.getEngine();
  63558. if (!this._texture) {
  63559. return;
  63560. }
  63561. // Bind
  63562. if (this._postProcessManager) {
  63563. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63564. }
  63565. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63566. if (this._texture) {
  63567. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63568. }
  63569. }
  63570. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63571. // Clear
  63572. if (this.onClearObservable.hasObservers()) {
  63573. this.onClearObservable.notifyObservers(engine);
  63574. }
  63575. else {
  63576. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63577. }
  63578. if (!this._doNotChangeAspectRatio) {
  63579. scene.updateTransformMatrix(true);
  63580. }
  63581. // Render
  63582. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63583. if (this._postProcessManager) {
  63584. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63585. }
  63586. else if (useCameraPostProcess) {
  63587. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63588. }
  63589. if (!this._doNotChangeAspectRatio) {
  63590. scene.updateTransformMatrix(true);
  63591. }
  63592. // Dump ?
  63593. if (dumpForDebug) {
  63594. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63595. }
  63596. // Unbind
  63597. if (!this.isCube || faceIndex === 5) {
  63598. if (this.isCube) {
  63599. if (faceIndex === 5) {
  63600. engine.generateMipMapsForCubemap(this._texture);
  63601. }
  63602. }
  63603. this.unbindFrameBuffer(engine, faceIndex);
  63604. }
  63605. else {
  63606. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63607. }
  63608. };
  63609. /**
  63610. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63611. * This allowed control for front to back rendering or reversly depending of the special needs.
  63612. *
  63613. * @param renderingGroupId The rendering group id corresponding to its index
  63614. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63615. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63616. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63617. */
  63618. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63619. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63620. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63621. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63622. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63623. };
  63624. /**
  63625. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63626. *
  63627. * @param renderingGroupId The rendering group id corresponding to its index
  63628. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63629. */
  63630. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63631. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63632. };
  63633. RenderTargetTexture.prototype.clone = function () {
  63634. var textureSize = this.getSize();
  63635. 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);
  63636. // Base texture
  63637. newTexture.hasAlpha = this.hasAlpha;
  63638. newTexture.level = this.level;
  63639. // RenderTarget Texture
  63640. newTexture.coordinatesMode = this.coordinatesMode;
  63641. if (this.renderList) {
  63642. newTexture.renderList = this.renderList.slice(0);
  63643. }
  63644. return newTexture;
  63645. };
  63646. RenderTargetTexture.prototype.serialize = function () {
  63647. if (!this.name) {
  63648. return null;
  63649. }
  63650. var serializationObject = _super.prototype.serialize.call(this);
  63651. serializationObject.renderTargetSize = this.getRenderSize();
  63652. serializationObject.renderList = [];
  63653. if (this.renderList) {
  63654. for (var index = 0; index < this.renderList.length; index++) {
  63655. serializationObject.renderList.push(this.renderList[index].id);
  63656. }
  63657. }
  63658. return serializationObject;
  63659. };
  63660. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63661. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63662. var objBuffer = this.getInternalTexture();
  63663. var scene = this.getScene();
  63664. if (objBuffer && scene) {
  63665. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63666. }
  63667. };
  63668. RenderTargetTexture.prototype.dispose = function () {
  63669. if (this._postProcessManager) {
  63670. this._postProcessManager.dispose();
  63671. this._postProcessManager = null;
  63672. }
  63673. this.clearPostProcesses(true);
  63674. if (this._resizeObserver) {
  63675. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63676. this._resizeObserver = null;
  63677. }
  63678. this.renderList = null;
  63679. // Remove from custom render targets
  63680. var scene = this.getScene();
  63681. if (!scene) {
  63682. return;
  63683. }
  63684. var index = scene.customRenderTargets.indexOf(this);
  63685. if (index >= 0) {
  63686. scene.customRenderTargets.splice(index, 1);
  63687. }
  63688. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63689. var camera = _a[_i];
  63690. index = camera.customRenderTargets.indexOf(this);
  63691. if (index >= 0) {
  63692. camera.customRenderTargets.splice(index, 1);
  63693. }
  63694. }
  63695. _super.prototype.dispose.call(this);
  63696. };
  63697. RenderTargetTexture.prototype._rebuild = function () {
  63698. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63699. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63700. }
  63701. if (this._postProcessManager) {
  63702. this._postProcessManager._rebuild();
  63703. }
  63704. };
  63705. /**
  63706. * Clear the info related to rendering groups preventing retention point in material dispose.
  63707. */
  63708. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63709. if (this._renderingManager) {
  63710. this._renderingManager.freeRenderingGroups();
  63711. }
  63712. };
  63713. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63714. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63715. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63716. return RenderTargetTexture;
  63717. }(BABYLON.Texture));
  63718. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63719. })(BABYLON || (BABYLON = {}));
  63720. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63721. var BABYLON;
  63722. (function (BABYLON) {
  63723. ;
  63724. var MultiRenderTarget = /** @class */ (function (_super) {
  63725. __extends(MultiRenderTarget, _super);
  63726. function MultiRenderTarget(name, size, count, scene, options) {
  63727. var _this = this;
  63728. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63729. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63730. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63731. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63732. _this._engine = scene.getEngine();
  63733. if (!_this.isSupported) {
  63734. _this.dispose();
  63735. return;
  63736. }
  63737. var types = [];
  63738. var samplingModes = [];
  63739. for (var i = 0; i < count; i++) {
  63740. if (options && options.types && options.types[i] !== undefined) {
  63741. types.push(options.types[i]);
  63742. }
  63743. else {
  63744. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63745. }
  63746. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63747. samplingModes.push(options.samplingModes[i]);
  63748. }
  63749. else {
  63750. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63751. }
  63752. }
  63753. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63754. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63755. _this._size = size;
  63756. _this._multiRenderTargetOptions = {
  63757. samplingModes: samplingModes,
  63758. generateMipMaps: generateMipMaps,
  63759. generateDepthBuffer: generateDepthBuffer,
  63760. generateStencilBuffer: generateStencilBuffer,
  63761. generateDepthTexture: generateDepthTexture,
  63762. types: types,
  63763. textureCount: count
  63764. };
  63765. _this._createInternalTextures();
  63766. _this._createTextures();
  63767. return _this;
  63768. }
  63769. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63770. get: function () {
  63771. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63772. },
  63773. enumerable: true,
  63774. configurable: true
  63775. });
  63776. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63777. get: function () {
  63778. return this._textures;
  63779. },
  63780. enumerable: true,
  63781. configurable: true
  63782. });
  63783. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63784. get: function () {
  63785. return this._textures[this._textures.length - 1];
  63786. },
  63787. enumerable: true,
  63788. configurable: true
  63789. });
  63790. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63791. set: function (wrap) {
  63792. if (this._textures) {
  63793. for (var i = 0; i < this._textures.length; i++) {
  63794. this._textures[i].wrapU = wrap;
  63795. }
  63796. }
  63797. },
  63798. enumerable: true,
  63799. configurable: true
  63800. });
  63801. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63802. set: function (wrap) {
  63803. if (this._textures) {
  63804. for (var i = 0; i < this._textures.length; i++) {
  63805. this._textures[i].wrapV = wrap;
  63806. }
  63807. }
  63808. },
  63809. enumerable: true,
  63810. configurable: true
  63811. });
  63812. MultiRenderTarget.prototype._rebuild = function () {
  63813. this.releaseInternalTextures();
  63814. this._createInternalTextures();
  63815. for (var i = 0; i < this._internalTextures.length; i++) {
  63816. var texture = this._textures[i];
  63817. texture._texture = this._internalTextures[i];
  63818. }
  63819. // Keeps references to frame buffer and stencil/depth buffer
  63820. this._texture = this._internalTextures[0];
  63821. };
  63822. MultiRenderTarget.prototype._createInternalTextures = function () {
  63823. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63824. };
  63825. MultiRenderTarget.prototype._createTextures = function () {
  63826. this._textures = [];
  63827. for (var i = 0; i < this._internalTextures.length; i++) {
  63828. var texture = new BABYLON.Texture(null, this.getScene());
  63829. texture._texture = this._internalTextures[i];
  63830. this._textures.push(texture);
  63831. }
  63832. // Keeps references to frame buffer and stencil/depth buffer
  63833. this._texture = this._internalTextures[0];
  63834. };
  63835. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63836. get: function () {
  63837. return this._samples;
  63838. },
  63839. set: function (value) {
  63840. if (this._samples === value) {
  63841. return;
  63842. }
  63843. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63844. },
  63845. enumerable: true,
  63846. configurable: true
  63847. });
  63848. MultiRenderTarget.prototype.resize = function (size) {
  63849. this.releaseInternalTextures();
  63850. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63851. this._createInternalTextures();
  63852. };
  63853. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63854. var _this = this;
  63855. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63856. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63857. });
  63858. };
  63859. MultiRenderTarget.prototype.dispose = function () {
  63860. this.releaseInternalTextures();
  63861. _super.prototype.dispose.call(this);
  63862. };
  63863. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63864. if (!this._internalTextures) {
  63865. return;
  63866. }
  63867. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63868. if (this._internalTextures[i] !== undefined) {
  63869. this._internalTextures[i].dispose();
  63870. this._internalTextures.splice(i, 1);
  63871. }
  63872. }
  63873. };
  63874. return MultiRenderTarget;
  63875. }(BABYLON.RenderTargetTexture));
  63876. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63877. })(BABYLON || (BABYLON = {}));
  63878. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63879. var BABYLON;
  63880. (function (BABYLON) {
  63881. var MirrorTexture = /** @class */ (function (_super) {
  63882. __extends(MirrorTexture, _super);
  63883. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63884. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63886. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63887. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63888. _this.scene = scene;
  63889. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63890. _this._transformMatrix = BABYLON.Matrix.Zero();
  63891. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63892. _this._adaptiveBlurKernel = 0;
  63893. _this._blurKernelX = 0;
  63894. _this._blurKernelY = 0;
  63895. _this._blurRatio = 1.0;
  63896. _this.ignoreCameraViewport = true;
  63897. _this._updateGammaSpace();
  63898. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63899. _this._updateGammaSpace;
  63900. });
  63901. _this.onBeforeRenderObservable.add(function () {
  63902. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63903. _this._savedViewMatrix = scene.getViewMatrix();
  63904. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63905. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63906. scene.clipPlane = _this.mirrorPlane;
  63907. scene.getEngine().cullBackFaces = false;
  63908. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63909. });
  63910. _this.onAfterRenderObservable.add(function () {
  63911. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63912. scene.getEngine().cullBackFaces = true;
  63913. scene._mirroredCameraPosition = null;
  63914. delete scene.clipPlane;
  63915. });
  63916. return _this;
  63917. }
  63918. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63919. get: function () {
  63920. return this._blurRatio;
  63921. },
  63922. set: function (value) {
  63923. if (this._blurRatio === value) {
  63924. return;
  63925. }
  63926. this._blurRatio = value;
  63927. this._preparePostProcesses();
  63928. },
  63929. enumerable: true,
  63930. configurable: true
  63931. });
  63932. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63933. set: function (value) {
  63934. this._adaptiveBlurKernel = value;
  63935. this._autoComputeBlurKernel();
  63936. },
  63937. enumerable: true,
  63938. configurable: true
  63939. });
  63940. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63941. set: function (value) {
  63942. this.blurKernelX = value;
  63943. this.blurKernelY = value;
  63944. },
  63945. enumerable: true,
  63946. configurable: true
  63947. });
  63948. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63949. get: function () {
  63950. return this._blurKernelX;
  63951. },
  63952. set: function (value) {
  63953. if (this._blurKernelX === value) {
  63954. return;
  63955. }
  63956. this._blurKernelX = value;
  63957. this._preparePostProcesses();
  63958. },
  63959. enumerable: true,
  63960. configurable: true
  63961. });
  63962. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63963. get: function () {
  63964. return this._blurKernelY;
  63965. },
  63966. set: function (value) {
  63967. if (this._blurKernelY === value) {
  63968. return;
  63969. }
  63970. this._blurKernelY = value;
  63971. this._preparePostProcesses();
  63972. },
  63973. enumerable: true,
  63974. configurable: true
  63975. });
  63976. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63977. var engine = this.getScene().getEngine();
  63978. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63979. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63980. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63981. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63982. };
  63983. MirrorTexture.prototype._onRatioRescale = function () {
  63984. if (this._sizeRatio) {
  63985. this.resize(this._initialSizeParameter);
  63986. if (!this._adaptiveBlurKernel) {
  63987. this._preparePostProcesses();
  63988. }
  63989. }
  63990. if (this._adaptiveBlurKernel) {
  63991. this._autoComputeBlurKernel();
  63992. }
  63993. };
  63994. MirrorTexture.prototype._updateGammaSpace = function () {
  63995. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63996. };
  63997. MirrorTexture.prototype._preparePostProcesses = function () {
  63998. this.clearPostProcesses(true);
  63999. if (this._blurKernelX && this._blurKernelY) {
  64000. var engine = this.getScene().getEngine();
  64001. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64002. 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);
  64003. this._blurX.autoClear = false;
  64004. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64005. this._blurX.inputTexture = this._texture;
  64006. }
  64007. else {
  64008. this._blurX.alwaysForcePOT = true;
  64009. }
  64010. 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);
  64011. this._blurY.autoClear = false;
  64012. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64013. this.addPostProcess(this._blurX);
  64014. this.addPostProcess(this._blurY);
  64015. }
  64016. else {
  64017. if (this._blurY) {
  64018. this.removePostProcess(this._blurY);
  64019. this._blurY.dispose();
  64020. this._blurY = null;
  64021. }
  64022. if (this._blurX) {
  64023. this.removePostProcess(this._blurX);
  64024. this._blurX.dispose();
  64025. this._blurX = null;
  64026. }
  64027. }
  64028. };
  64029. MirrorTexture.prototype.clone = function () {
  64030. var scene = this.getScene();
  64031. if (!scene) {
  64032. return this;
  64033. }
  64034. var textureSize = this.getSize();
  64035. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64036. // Base texture
  64037. newTexture.hasAlpha = this.hasAlpha;
  64038. newTexture.level = this.level;
  64039. // Mirror Texture
  64040. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64041. if (this.renderList) {
  64042. newTexture.renderList = this.renderList.slice(0);
  64043. }
  64044. return newTexture;
  64045. };
  64046. MirrorTexture.prototype.serialize = function () {
  64047. if (!this.name) {
  64048. return null;
  64049. }
  64050. var serializationObject = _super.prototype.serialize.call(this);
  64051. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64052. return serializationObject;
  64053. };
  64054. MirrorTexture.prototype.dispose = function () {
  64055. _super.prototype.dispose.call(this);
  64056. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64057. };
  64058. return MirrorTexture;
  64059. }(BABYLON.RenderTargetTexture));
  64060. BABYLON.MirrorTexture = MirrorTexture;
  64061. })(BABYLON || (BABYLON = {}));
  64062. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64063. var BABYLON;
  64064. (function (BABYLON) {
  64065. /**
  64066. * Creates a refraction texture used by refraction channel of the standard material.
  64067. * @param name the texture name
  64068. * @param size size of the underlying texture
  64069. * @param scene root scene
  64070. */
  64071. var RefractionTexture = /** @class */ (function (_super) {
  64072. __extends(RefractionTexture, _super);
  64073. function RefractionTexture(name, size, scene, generateMipMaps) {
  64074. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64075. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64076. _this.depth = 2.0;
  64077. _this.onBeforeRenderObservable.add(function () {
  64078. scene.clipPlane = _this.refractionPlane;
  64079. });
  64080. _this.onAfterRenderObservable.add(function () {
  64081. delete scene.clipPlane;
  64082. });
  64083. return _this;
  64084. }
  64085. RefractionTexture.prototype.clone = function () {
  64086. var scene = this.getScene();
  64087. if (!scene) {
  64088. return this;
  64089. }
  64090. var textureSize = this.getSize();
  64091. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64092. // Base texture
  64093. newTexture.hasAlpha = this.hasAlpha;
  64094. newTexture.level = this.level;
  64095. // Refraction Texture
  64096. newTexture.refractionPlane = this.refractionPlane.clone();
  64097. if (this.renderList) {
  64098. newTexture.renderList = this.renderList.slice(0);
  64099. }
  64100. newTexture.depth = this.depth;
  64101. return newTexture;
  64102. };
  64103. RefractionTexture.prototype.serialize = function () {
  64104. if (!this.name) {
  64105. return null;
  64106. }
  64107. var serializationObject = _super.prototype.serialize.call(this);
  64108. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64109. serializationObject.depth = this.depth;
  64110. return serializationObject;
  64111. };
  64112. return RefractionTexture;
  64113. }(BABYLON.RenderTargetTexture));
  64114. BABYLON.RefractionTexture = RefractionTexture;
  64115. })(BABYLON || (BABYLON = {}));
  64116. //# sourceMappingURL=babylon.refractionTexture.js.map
  64117. var BABYLON;
  64118. (function (BABYLON) {
  64119. /**
  64120. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64121. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64122. */
  64123. var DynamicTexture = /** @class */ (function (_super) {
  64124. __extends(DynamicTexture, _super);
  64125. /**
  64126. * Creates a {BABYLON.DynamicTexture}
  64127. * @param name defines the name of the texture
  64128. * @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
  64129. * @param scene defines the scene where you want the texture
  64130. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64131. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64132. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64133. */
  64134. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64135. if (scene === void 0) { scene = null; }
  64136. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64137. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64138. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64139. _this.name = name;
  64140. _this._engine = _this.getScene().getEngine();
  64141. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64142. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64143. _this._generateMipMaps = generateMipMaps;
  64144. if (options.getContext) {
  64145. _this._canvas = options;
  64146. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64147. }
  64148. else {
  64149. _this._canvas = document.createElement("canvas");
  64150. if (options.width || options.width === 0) {
  64151. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64152. }
  64153. else {
  64154. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64155. }
  64156. }
  64157. var textureSize = _this.getSize();
  64158. _this._canvas.width = textureSize.width;
  64159. _this._canvas.height = textureSize.height;
  64160. _this._context = _this._canvas.getContext("2d");
  64161. return _this;
  64162. }
  64163. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64164. /**
  64165. * Gets the current state of canRescale
  64166. */
  64167. get: function () {
  64168. return true;
  64169. },
  64170. enumerable: true,
  64171. configurable: true
  64172. });
  64173. DynamicTexture.prototype._recreate = function (textureSize) {
  64174. this._canvas.width = textureSize.width;
  64175. this._canvas.height = textureSize.height;
  64176. this.releaseInternalTexture();
  64177. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64178. };
  64179. /**
  64180. * Scales the texture
  64181. * @param ratio the scale factor to apply to both width and height
  64182. */
  64183. DynamicTexture.prototype.scale = function (ratio) {
  64184. var textureSize = this.getSize();
  64185. textureSize.width *= ratio;
  64186. textureSize.height *= ratio;
  64187. this._recreate(textureSize);
  64188. };
  64189. /**
  64190. * Resizes the texture
  64191. * @param width the new width
  64192. * @param height the new height
  64193. */
  64194. DynamicTexture.prototype.scaleTo = function (width, height) {
  64195. var textureSize = this.getSize();
  64196. textureSize.width = width;
  64197. textureSize.height = height;
  64198. this._recreate(textureSize);
  64199. };
  64200. /**
  64201. * Gets the context of the canvas used by the texture
  64202. * @returns the canvas context of the dynamic texture
  64203. */
  64204. DynamicTexture.prototype.getContext = function () {
  64205. return this._context;
  64206. };
  64207. /**
  64208. * Clears the texture
  64209. */
  64210. DynamicTexture.prototype.clear = function () {
  64211. var size = this.getSize();
  64212. this._context.fillRect(0, 0, size.width, size.height);
  64213. };
  64214. /**
  64215. * Updates the texture
  64216. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64217. */
  64218. DynamicTexture.prototype.update = function (invertY) {
  64219. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64220. };
  64221. /**
  64222. * Draws text onto the texture
  64223. * @param text defines the text to be drawn
  64224. * @param x defines the placement of the text from the left
  64225. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64226. * @param font defines the font to be used with font-style, font-size, font-name
  64227. * @param color defines the color used for the text
  64228. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64229. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64230. * @param update defines whether texture is immediately update (default is true)
  64231. */
  64232. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64233. if (update === void 0) { update = true; }
  64234. var size = this.getSize();
  64235. if (clearColor) {
  64236. this._context.fillStyle = clearColor;
  64237. this._context.fillRect(0, 0, size.width, size.height);
  64238. }
  64239. this._context.font = font;
  64240. if (x === null || x === undefined) {
  64241. var textSize = this._context.measureText(text);
  64242. x = (size.width - textSize.width) / 2;
  64243. }
  64244. if (y === null || y === undefined) {
  64245. var fontSize = parseInt((font.replace(/\D/g, '')));
  64246. ;
  64247. y = (size.height / 2) + (fontSize / 3.65);
  64248. }
  64249. this._context.fillStyle = color;
  64250. this._context.fillText(text, x, y);
  64251. if (update) {
  64252. this.update(invertY);
  64253. }
  64254. };
  64255. /**
  64256. * Clones the texture
  64257. * @returns the clone of the texture.
  64258. */
  64259. DynamicTexture.prototype.clone = function () {
  64260. var scene = this.getScene();
  64261. if (!scene) {
  64262. return this;
  64263. }
  64264. var textureSize = this.getSize();
  64265. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64266. // Base texture
  64267. newTexture.hasAlpha = this.hasAlpha;
  64268. newTexture.level = this.level;
  64269. // Dynamic Texture
  64270. newTexture.wrapU = this.wrapU;
  64271. newTexture.wrapV = this.wrapV;
  64272. return newTexture;
  64273. };
  64274. /** @hidden */
  64275. DynamicTexture.prototype._rebuild = function () {
  64276. this.update();
  64277. };
  64278. return DynamicTexture;
  64279. }(BABYLON.Texture));
  64280. BABYLON.DynamicTexture = DynamicTexture;
  64281. })(BABYLON || (BABYLON = {}));
  64282. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64283. var BABYLON;
  64284. (function (BABYLON) {
  64285. var VideoTexture = /** @class */ (function (_super) {
  64286. __extends(VideoTexture, _super);
  64287. /**
  64288. * Creates a video texture.
  64289. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64290. * @param {string | null} name optional name, will detect from video source, if not defined
  64291. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64292. * @param {BABYLON.Scene} scene is obviously the current scene.
  64293. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64294. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64295. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64296. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64297. */
  64298. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64299. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64300. if (invertY === void 0) { invertY = false; }
  64301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64302. if (settings === void 0) { settings = {
  64303. autoPlay: true,
  64304. loop: true,
  64305. autoUpdateTexture: true,
  64306. }; }
  64307. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64308. _this._stillImageCaptured = false;
  64309. _this._createInternalTexture = function () {
  64310. if (_this._texture != null) {
  64311. return;
  64312. }
  64313. if (!_this._engine.needPOTTextures ||
  64314. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64315. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64316. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64317. }
  64318. else {
  64319. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64320. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64321. _this._generateMipMaps = false;
  64322. }
  64323. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64324. if (!_this.video.autoplay) {
  64325. var oldHandler_1 = _this.video.onplaying;
  64326. _this.video.onplaying = function () {
  64327. _this.video.onplaying = oldHandler_1;
  64328. _this._texture.isReady = true;
  64329. _this._updateInternalTexture();
  64330. _this.video.pause();
  64331. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64332. _this.onLoadObservable.notifyObservers(_this);
  64333. }
  64334. };
  64335. _this.video.play();
  64336. }
  64337. else {
  64338. _this._texture.isReady = true;
  64339. _this._updateInternalTexture();
  64340. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64341. _this.onLoadObservable.notifyObservers(_this);
  64342. }
  64343. }
  64344. };
  64345. _this.reset = function () {
  64346. if (_this._texture == null) {
  64347. return;
  64348. }
  64349. _this._texture.dispose();
  64350. _this._texture = null;
  64351. };
  64352. _this._updateInternalTexture = function (e) {
  64353. if (_this._texture == null || !_this._texture.isReady) {
  64354. return;
  64355. }
  64356. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64357. return;
  64358. }
  64359. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64360. };
  64361. _this._engine = _this.getScene().getEngine();
  64362. _this._generateMipMaps = generateMipMaps;
  64363. _this._samplingMode = samplingMode;
  64364. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64365. _this.name = name || _this._getName(src);
  64366. _this.video = _this._getVideo(src);
  64367. if (settings.autoPlay !== undefined) {
  64368. _this.video.autoplay = settings.autoPlay;
  64369. }
  64370. if (settings.loop !== undefined) {
  64371. _this.video.loop = settings.loop;
  64372. }
  64373. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64374. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64375. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64376. _this.video.addEventListener("emptied", _this.reset);
  64377. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64378. _this._createInternalTexture();
  64379. }
  64380. return _this;
  64381. }
  64382. VideoTexture.prototype._getName = function (src) {
  64383. if (src instanceof HTMLVideoElement) {
  64384. return src.currentSrc;
  64385. }
  64386. if (typeof src === "object") {
  64387. return src.toString();
  64388. }
  64389. return src;
  64390. };
  64391. ;
  64392. VideoTexture.prototype._getVideo = function (src) {
  64393. if (src instanceof HTMLVideoElement) {
  64394. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64395. return src;
  64396. }
  64397. var video = document.createElement("video");
  64398. if (typeof src === "string") {
  64399. BABYLON.Tools.SetCorsBehavior(src, video);
  64400. video.src = src;
  64401. }
  64402. else {
  64403. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64404. src.forEach(function (url) {
  64405. var source = document.createElement("source");
  64406. source.src = url;
  64407. video.appendChild(source);
  64408. });
  64409. }
  64410. return video;
  64411. };
  64412. ;
  64413. /**
  64414. * Internal method to initiate `update`.
  64415. */
  64416. VideoTexture.prototype._rebuild = function () {
  64417. this.update();
  64418. };
  64419. /**
  64420. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64421. */
  64422. VideoTexture.prototype.update = function () {
  64423. if (!this.autoUpdateTexture) {
  64424. // Expecting user to call `updateTexture` manually
  64425. return;
  64426. }
  64427. this.updateTexture(true);
  64428. };
  64429. /**
  64430. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64431. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64432. */
  64433. VideoTexture.prototype.updateTexture = function (isVisible) {
  64434. if (!isVisible) {
  64435. return;
  64436. }
  64437. if (this.video.paused && this._stillImageCaptured) {
  64438. return;
  64439. }
  64440. this._stillImageCaptured = true;
  64441. this._updateInternalTexture();
  64442. };
  64443. /**
  64444. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64445. * @param url New url.
  64446. */
  64447. VideoTexture.prototype.updateURL = function (url) {
  64448. this.video.src = url;
  64449. };
  64450. VideoTexture.prototype.dispose = function () {
  64451. _super.prototype.dispose.call(this);
  64452. this.video.removeEventListener("canplay", this._createInternalTexture);
  64453. this.video.removeEventListener("paused", this._updateInternalTexture);
  64454. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64455. this.video.removeEventListener("emptied", this.reset);
  64456. this.video.pause();
  64457. };
  64458. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64459. var video = document.createElement("video");
  64460. var constraintsDeviceId;
  64461. if (constraints && constraints.deviceId) {
  64462. constraintsDeviceId = {
  64463. exact: constraints.deviceId,
  64464. };
  64465. }
  64466. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64467. if (navigator.mediaDevices) {
  64468. navigator.mediaDevices.getUserMedia({ video: constraints })
  64469. .then(function (stream) {
  64470. if (video.mozSrcObject !== undefined) {
  64471. // hack for Firefox < 19
  64472. video.mozSrcObject = stream;
  64473. }
  64474. else {
  64475. video.srcObject = stream;
  64476. }
  64477. var onPlaying = function () {
  64478. if (onReady) {
  64479. onReady(new VideoTexture("video", video, scene, true, true));
  64480. }
  64481. video.removeEventListener("playing", onPlaying);
  64482. };
  64483. video.addEventListener("playing", onPlaying);
  64484. video.play();
  64485. })
  64486. .catch(function (err) {
  64487. BABYLON.Tools.Error(err.name);
  64488. });
  64489. }
  64490. else {
  64491. navigator.getUserMedia =
  64492. navigator.getUserMedia ||
  64493. navigator.webkitGetUserMedia ||
  64494. navigator.mozGetUserMedia ||
  64495. navigator.msGetUserMedia;
  64496. if (navigator.getUserMedia) {
  64497. navigator.getUserMedia({
  64498. video: {
  64499. deviceId: constraintsDeviceId,
  64500. width: {
  64501. min: (constraints && constraints.minWidth) || 256,
  64502. max: (constraints && constraints.maxWidth) || 640,
  64503. },
  64504. height: {
  64505. min: (constraints && constraints.minHeight) || 256,
  64506. max: (constraints && constraints.maxHeight) || 480,
  64507. },
  64508. },
  64509. }, function (stream) {
  64510. if (video.mozSrcObject !== undefined) {
  64511. // hack for Firefox < 19
  64512. video.mozSrcObject = stream;
  64513. }
  64514. else {
  64515. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64516. }
  64517. video.play();
  64518. if (onReady) {
  64519. onReady(new VideoTexture("video", video, scene, true, true));
  64520. }
  64521. }, function (e) {
  64522. BABYLON.Tools.Error(e.name);
  64523. });
  64524. }
  64525. }
  64526. };
  64527. return VideoTexture;
  64528. }(BABYLON.Texture));
  64529. BABYLON.VideoTexture = VideoTexture;
  64530. })(BABYLON || (BABYLON = {}));
  64531. //# sourceMappingURL=babylon.videoTexture.js.map
  64532. var BABYLON;
  64533. (function (BABYLON) {
  64534. var RawTexture = /** @class */ (function (_super) {
  64535. __extends(RawTexture, _super);
  64536. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64537. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64538. if (invertY === void 0) { invertY = false; }
  64539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64540. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64541. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64542. _this.format = format;
  64543. _this._engine = scene.getEngine();
  64544. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64545. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64546. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64547. return _this;
  64548. }
  64549. RawTexture.prototype.update = function (data) {
  64550. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64551. };
  64552. // Statics
  64553. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64554. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64555. if (invertY === void 0) { invertY = false; }
  64556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64557. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64558. };
  64559. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64560. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64561. if (invertY === void 0) { invertY = false; }
  64562. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64563. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64564. };
  64565. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64566. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64567. if (invertY === void 0) { invertY = false; }
  64568. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64569. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64570. };
  64571. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64572. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64573. if (invertY === void 0) { invertY = false; }
  64574. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64575. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64576. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64577. };
  64578. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64579. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64580. if (invertY === void 0) { invertY = false; }
  64581. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64582. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64583. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64584. };
  64585. return RawTexture;
  64586. }(BABYLON.Texture));
  64587. BABYLON.RawTexture = RawTexture;
  64588. })(BABYLON || (BABYLON = {}));
  64589. //# sourceMappingURL=babylon.rawTexture.js.map
  64590. var BABYLON;
  64591. (function (BABYLON) {
  64592. /**
  64593. * Class used to store 3D textures containing user data
  64594. */
  64595. var RawTexture3D = /** @class */ (function (_super) {
  64596. __extends(RawTexture3D, _super);
  64597. /**
  64598. * Create a new RawTexture3D
  64599. * @param data defines the data of the texture
  64600. * @param width defines the width of the texture
  64601. * @param height defines the height of the texture
  64602. * @param depth defines the depth of the texture
  64603. * @param format defines the texture format to use
  64604. * @param scene defines the hosting scene
  64605. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64606. * @param invertY defines if texture must be stored with Y axis inverted
  64607. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64608. */
  64609. function RawTexture3D(data, width, height, depth,
  64610. /** Gets or sets the texture format to use*/
  64611. format, scene, generateMipMaps, invertY, samplingMode) {
  64612. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64613. if (invertY === void 0) { invertY = false; }
  64614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64615. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64616. _this.format = format;
  64617. _this._engine = scene.getEngine();
  64618. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64619. _this.is3D = true;
  64620. return _this;
  64621. }
  64622. /**
  64623. * Update the texture with new data
  64624. * @param data defines the data to store in the texture
  64625. */
  64626. RawTexture3D.prototype.update = function (data) {
  64627. if (!this._texture) {
  64628. return;
  64629. }
  64630. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64631. };
  64632. return RawTexture3D;
  64633. }(BABYLON.Texture));
  64634. BABYLON.RawTexture3D = RawTexture3D;
  64635. })(BABYLON || (BABYLON = {}));
  64636. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64637. var BABYLON;
  64638. (function (BABYLON) {
  64639. /**
  64640. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64641. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64642. */
  64643. var PostProcess = /** @class */ (function () {
  64644. /**
  64645. * Creates a new instance PostProcess
  64646. * @param name The name of the PostProcess.
  64647. * @param fragmentUrl The url of the fragment shader to be used.
  64648. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64649. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64650. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64651. * @param camera The camera to apply the render pass to.
  64652. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64653. * @param engine The engine which the post process will be applied. (default: current engine)
  64654. * @param reusable If the post process can be reused on the same frame. (default: false)
  64655. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64656. * @param textureType Type of textures used when performing the post process. (default: 0)
  64657. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64658. * @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
  64659. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64660. */
  64661. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64662. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64663. if (defines === void 0) { defines = null; }
  64664. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64665. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64666. if (blockCompilation === void 0) { blockCompilation = false; }
  64667. this.name = name;
  64668. /**
  64669. * Width of the texture to apply the post process on
  64670. */
  64671. this.width = -1;
  64672. /**
  64673. * Height of the texture to apply the post process on
  64674. */
  64675. this.height = -1;
  64676. /**
  64677. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64678. */
  64679. this._outputTexture = null;
  64680. /**
  64681. * If the buffer needs to be cleared before applying the post process. (default: true)
  64682. * Should be set to false if shader will overwrite all previous pixels.
  64683. */
  64684. this.autoClear = true;
  64685. /**
  64686. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64687. */
  64688. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64689. /**
  64690. * Animations to be used for the post processing
  64691. */
  64692. this.animations = new Array();
  64693. /**
  64694. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64695. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64696. */
  64697. this.enablePixelPerfectMode = false;
  64698. /**
  64699. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64700. */
  64701. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64702. /**
  64703. * Force textures to be a power of two (default: false)
  64704. */
  64705. this.alwaysForcePOT = false;
  64706. /**
  64707. * Number of sample textures (default: 1)
  64708. */
  64709. this.samples = 1;
  64710. /**
  64711. * Modify the scale of the post process to be the same as the viewport (default: false)
  64712. */
  64713. this.adaptScaleToCurrentViewport = false;
  64714. this._reusable = false;
  64715. /**
  64716. * Smart array of input and output textures for the post process.
  64717. */
  64718. this._textures = new BABYLON.SmartArray(2);
  64719. /**
  64720. * The index in _textures that corresponds to the output texture.
  64721. */
  64722. this._currentRenderTextureInd = 0;
  64723. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64724. this._texelSize = BABYLON.Vector2.Zero();
  64725. // Events
  64726. /**
  64727. * An event triggered when the postprocess is activated.
  64728. */
  64729. this.onActivateObservable = new BABYLON.Observable();
  64730. /**
  64731. * An event triggered when the postprocess changes its size.
  64732. */
  64733. this.onSizeChangedObservable = new BABYLON.Observable();
  64734. /**
  64735. * An event triggered when the postprocess applies its effect.
  64736. */
  64737. this.onApplyObservable = new BABYLON.Observable();
  64738. /**
  64739. * An event triggered before rendering the postprocess
  64740. */
  64741. this.onBeforeRenderObservable = new BABYLON.Observable();
  64742. /**
  64743. * An event triggered after rendering the postprocess
  64744. */
  64745. this.onAfterRenderObservable = new BABYLON.Observable();
  64746. if (camera != null) {
  64747. this._camera = camera;
  64748. this._scene = camera.getScene();
  64749. camera.attachPostProcess(this);
  64750. this._engine = this._scene.getEngine();
  64751. this._scene.postProcesses.push(this);
  64752. }
  64753. else if (engine) {
  64754. this._engine = engine;
  64755. this._engine.postProcesses.push(this);
  64756. }
  64757. this._options = options;
  64758. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64759. this._reusable = reusable || false;
  64760. this._textureType = textureType;
  64761. this._samplers = samplers || [];
  64762. this._samplers.push("textureSampler");
  64763. this._fragmentUrl = fragmentUrl;
  64764. this._vertexUrl = vertexUrl;
  64765. this._parameters = parameters || [];
  64766. this._parameters.push("scale");
  64767. this._indexParameters = indexParameters;
  64768. if (!blockCompilation) {
  64769. this.updateEffect(defines);
  64770. }
  64771. }
  64772. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64773. /**
  64774. * A function that is added to the onActivateObservable
  64775. */
  64776. set: function (callback) {
  64777. if (this._onActivateObserver) {
  64778. this.onActivateObservable.remove(this._onActivateObserver);
  64779. }
  64780. if (callback) {
  64781. this._onActivateObserver = this.onActivateObservable.add(callback);
  64782. }
  64783. },
  64784. enumerable: true,
  64785. configurable: true
  64786. });
  64787. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64788. /**
  64789. * A function that is added to the onSizeChangedObservable
  64790. */
  64791. set: function (callback) {
  64792. if (this._onSizeChangedObserver) {
  64793. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64794. }
  64795. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64796. },
  64797. enumerable: true,
  64798. configurable: true
  64799. });
  64800. Object.defineProperty(PostProcess.prototype, "onApply", {
  64801. /**
  64802. * A function that is added to the onApplyObservable
  64803. */
  64804. set: function (callback) {
  64805. if (this._onApplyObserver) {
  64806. this.onApplyObservable.remove(this._onApplyObserver);
  64807. }
  64808. this._onApplyObserver = this.onApplyObservable.add(callback);
  64809. },
  64810. enumerable: true,
  64811. configurable: true
  64812. });
  64813. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64814. /**
  64815. * A function that is added to the onBeforeRenderObservable
  64816. */
  64817. set: function (callback) {
  64818. if (this._onBeforeRenderObserver) {
  64819. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64820. }
  64821. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64822. },
  64823. enumerable: true,
  64824. configurable: true
  64825. });
  64826. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64827. /**
  64828. * A function that is added to the onAfterRenderObservable
  64829. */
  64830. set: function (callback) {
  64831. if (this._onAfterRenderObserver) {
  64832. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64833. }
  64834. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64835. },
  64836. enumerable: true,
  64837. configurable: true
  64838. });
  64839. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64840. /**
  64841. * 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
  64842. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64843. */
  64844. get: function () {
  64845. return this._textures.data[this._currentRenderTextureInd];
  64846. },
  64847. set: function (value) {
  64848. this._forcedOutputTexture = value;
  64849. },
  64850. enumerable: true,
  64851. configurable: true
  64852. });
  64853. /**
  64854. * Gets the camera which post process is applied to.
  64855. * @returns The camera the post process is applied to.
  64856. */
  64857. PostProcess.prototype.getCamera = function () {
  64858. return this._camera;
  64859. };
  64860. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64861. /**
  64862. * Gets the texel size of the postprocess.
  64863. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64864. */
  64865. get: function () {
  64866. if (this._shareOutputWithPostProcess) {
  64867. return this._shareOutputWithPostProcess.texelSize;
  64868. }
  64869. if (this._forcedOutputTexture) {
  64870. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64871. }
  64872. return this._texelSize;
  64873. },
  64874. enumerable: true,
  64875. configurable: true
  64876. });
  64877. /**
  64878. * Gets the engine which this post process belongs to.
  64879. * @returns The engine the post process was enabled with.
  64880. */
  64881. PostProcess.prototype.getEngine = function () {
  64882. return this._engine;
  64883. };
  64884. /**
  64885. * The effect that is created when initializing the post process.
  64886. * @returns The created effect corrisponding the the postprocess.
  64887. */
  64888. PostProcess.prototype.getEffect = function () {
  64889. return this._effect;
  64890. };
  64891. /**
  64892. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64893. * @param postProcess The post process to share the output with.
  64894. * @returns This post process.
  64895. */
  64896. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64897. this._disposeTextures();
  64898. this._shareOutputWithPostProcess = postProcess;
  64899. return this;
  64900. };
  64901. /**
  64902. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64903. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64904. */
  64905. PostProcess.prototype.useOwnOutput = function () {
  64906. if (this._textures.length == 0) {
  64907. this._textures = new BABYLON.SmartArray(2);
  64908. }
  64909. this._shareOutputWithPostProcess = null;
  64910. };
  64911. /**
  64912. * Updates the effect with the current post process compile time values and recompiles the shader.
  64913. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64914. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64915. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64916. * @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
  64917. * @param onCompiled Called when the shader has been compiled.
  64918. * @param onError Called if there is an error when compiling a shader.
  64919. */
  64920. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64921. if (defines === void 0) { defines = null; }
  64922. if (uniforms === void 0) { uniforms = null; }
  64923. if (samplers === void 0) { samplers = null; }
  64924. 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);
  64925. };
  64926. /**
  64927. * The post process is reusable if it can be used multiple times within one frame.
  64928. * @returns If the post process is reusable
  64929. */
  64930. PostProcess.prototype.isReusable = function () {
  64931. return this._reusable;
  64932. };
  64933. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64934. PostProcess.prototype.markTextureDirty = function () {
  64935. this.width = -1;
  64936. };
  64937. /**
  64938. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64939. * 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.
  64940. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64941. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64942. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64943. * @returns The target texture that was bound to be written to.
  64944. */
  64945. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64946. var _this = this;
  64947. if (sourceTexture === void 0) { sourceTexture = null; }
  64948. camera = camera || this._camera;
  64949. var scene = camera.getScene();
  64950. var engine = scene.getEngine();
  64951. var maxSize = engine.getCaps().maxTextureSize;
  64952. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64953. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64954. // 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
  64955. var webVRCamera = camera.parent;
  64956. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64957. requiredWidth /= 2;
  64958. }
  64959. var desiredWidth = (this._options.width || requiredWidth);
  64960. var desiredHeight = this._options.height || requiredHeight;
  64961. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64962. if (this.adaptScaleToCurrentViewport) {
  64963. var currentViewport = engine.currentViewport;
  64964. if (currentViewport) {
  64965. desiredWidth *= currentViewport.width;
  64966. desiredHeight *= currentViewport.height;
  64967. }
  64968. }
  64969. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64970. if (!this._options.width) {
  64971. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64972. }
  64973. if (!this._options.height) {
  64974. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64975. }
  64976. }
  64977. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64978. if (this._textures.length > 0) {
  64979. for (var i = 0; i < this._textures.length; i++) {
  64980. this._engine._releaseTexture(this._textures.data[i]);
  64981. }
  64982. this._textures.reset();
  64983. }
  64984. this.width = desiredWidth;
  64985. this.height = desiredHeight;
  64986. var textureSize = { width: this.width, height: this.height };
  64987. var textureOptions = {
  64988. generateMipMaps: false,
  64989. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64990. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64991. samplingMode: this.renderTargetSamplingMode,
  64992. type: this._textureType
  64993. };
  64994. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64995. if (this._reusable) {
  64996. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64997. }
  64998. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64999. this.onSizeChangedObservable.notifyObservers(this);
  65000. }
  65001. this._textures.forEach(function (texture) {
  65002. if (texture.samples !== _this.samples) {
  65003. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65004. }
  65005. });
  65006. }
  65007. var target;
  65008. if (this._shareOutputWithPostProcess) {
  65009. target = this._shareOutputWithPostProcess.inputTexture;
  65010. }
  65011. else if (this._forcedOutputTexture) {
  65012. target = this._forcedOutputTexture;
  65013. this.width = this._forcedOutputTexture.width;
  65014. this.height = this._forcedOutputTexture.height;
  65015. }
  65016. else {
  65017. target = this.inputTexture;
  65018. }
  65019. // Bind the input of this post process to be used as the output of the previous post process.
  65020. if (this.enablePixelPerfectMode) {
  65021. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65022. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65023. }
  65024. else {
  65025. this._scaleRatio.copyFromFloats(1, 1);
  65026. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65027. }
  65028. this.onActivateObservable.notifyObservers(camera);
  65029. // Clear
  65030. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65031. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65032. }
  65033. if (this._reusable) {
  65034. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65035. }
  65036. return target;
  65037. };
  65038. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65039. /**
  65040. * If the post process is supported.
  65041. */
  65042. get: function () {
  65043. return this._effect.isSupported;
  65044. },
  65045. enumerable: true,
  65046. configurable: true
  65047. });
  65048. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65049. /**
  65050. * The aspect ratio of the output texture.
  65051. */
  65052. get: function () {
  65053. if (this._shareOutputWithPostProcess) {
  65054. return this._shareOutputWithPostProcess.aspectRatio;
  65055. }
  65056. if (this._forcedOutputTexture) {
  65057. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65058. }
  65059. return this.width / this.height;
  65060. },
  65061. enumerable: true,
  65062. configurable: true
  65063. });
  65064. /**
  65065. * Get a value indicating if the post-process is ready to be used
  65066. * @returns true if the post-process is ready (shader is compiled)
  65067. */
  65068. PostProcess.prototype.isReady = function () {
  65069. return this._effect && this._effect.isReady();
  65070. };
  65071. /**
  65072. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65073. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65074. */
  65075. PostProcess.prototype.apply = function () {
  65076. // Check
  65077. if (!this._effect || !this._effect.isReady())
  65078. return null;
  65079. // States
  65080. this._engine.enableEffect(this._effect);
  65081. this._engine.setState(false);
  65082. this._engine.setDepthBuffer(false);
  65083. this._engine.setDepthWrite(false);
  65084. // Alpha
  65085. this._engine.setAlphaMode(this.alphaMode);
  65086. if (this.alphaConstants) {
  65087. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65088. }
  65089. // Bind the output texture of the preivous post process as the input to this post process.
  65090. var source;
  65091. if (this._shareOutputWithPostProcess) {
  65092. source = this._shareOutputWithPostProcess.inputTexture;
  65093. }
  65094. else if (this._forcedOutputTexture) {
  65095. source = this._forcedOutputTexture;
  65096. }
  65097. else {
  65098. source = this.inputTexture;
  65099. }
  65100. this._effect._bindTexture("textureSampler", source);
  65101. // Parameters
  65102. this._effect.setVector2("scale", this._scaleRatio);
  65103. this.onApplyObservable.notifyObservers(this._effect);
  65104. return this._effect;
  65105. };
  65106. PostProcess.prototype._disposeTextures = function () {
  65107. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65108. return;
  65109. }
  65110. if (this._textures.length > 0) {
  65111. for (var i = 0; i < this._textures.length; i++) {
  65112. this._engine._releaseTexture(this._textures.data[i]);
  65113. }
  65114. }
  65115. this._textures.dispose();
  65116. };
  65117. /**
  65118. * Disposes the post process.
  65119. * @param camera The camera to dispose the post process on.
  65120. */
  65121. PostProcess.prototype.dispose = function (camera) {
  65122. camera = camera || this._camera;
  65123. this._disposeTextures();
  65124. if (this._scene) {
  65125. var index_1 = this._scene.postProcesses.indexOf(this);
  65126. if (index_1 !== -1) {
  65127. this._scene.postProcesses.splice(index_1, 1);
  65128. }
  65129. }
  65130. else {
  65131. var index_2 = this._engine.postProcesses.indexOf(this);
  65132. if (index_2 !== -1) {
  65133. this._engine.postProcesses.splice(index_2, 1);
  65134. }
  65135. }
  65136. if (!camera) {
  65137. return;
  65138. }
  65139. camera.detachPostProcess(this);
  65140. var index = camera._postProcesses.indexOf(this);
  65141. if (index === 0 && camera._postProcesses.length > 0) {
  65142. var firstPostProcess = this._camera._getFirstPostProcess();
  65143. if (firstPostProcess) {
  65144. firstPostProcess.markTextureDirty();
  65145. }
  65146. }
  65147. this.onActivateObservable.clear();
  65148. this.onAfterRenderObservable.clear();
  65149. this.onApplyObservable.clear();
  65150. this.onBeforeRenderObservable.clear();
  65151. this.onSizeChangedObservable.clear();
  65152. };
  65153. return PostProcess;
  65154. }());
  65155. BABYLON.PostProcess = PostProcess;
  65156. })(BABYLON || (BABYLON = {}));
  65157. //# sourceMappingURL=babylon.postProcess.js.map
  65158. var BABYLON;
  65159. (function (BABYLON) {
  65160. var PassPostProcess = /** @class */ (function (_super) {
  65161. __extends(PassPostProcess, _super);
  65162. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65163. if (camera === void 0) { camera = null; }
  65164. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65165. if (blockCompilation === void 0) { blockCompilation = false; }
  65166. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65167. }
  65168. return PassPostProcess;
  65169. }(BABYLON.PostProcess));
  65170. BABYLON.PassPostProcess = PassPostProcess;
  65171. })(BABYLON || (BABYLON = {}));
  65172. //# sourceMappingURL=babylon.passPostProcess.js.map
  65173. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65174. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65175. s = arguments[i];
  65176. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65177. t[p] = s[p];
  65178. }
  65179. return t;
  65180. };
  65181. var BABYLON;
  65182. (function (BABYLON) {
  65183. /**
  65184. * Default implementation IShadowGenerator.
  65185. * This is the main object responsible of generating shadows in the framework.
  65186. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65187. */
  65188. var ShadowGenerator = /** @class */ (function () {
  65189. /**
  65190. * Creates a ShadowGenerator object.
  65191. * A ShadowGenerator is the required tool to use the shadows.
  65192. * Each light casting shadows needs to use its own ShadowGenerator.
  65193. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65194. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65195. * @param light The light object generating the shadows.
  65196. * @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.
  65197. */
  65198. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65199. this._bias = 0.00005;
  65200. this._normalBias = 0;
  65201. this._blurBoxOffset = 1;
  65202. this._blurScale = 2;
  65203. this._blurKernel = 1;
  65204. this._useKernelBlur = false;
  65205. this._filter = ShadowGenerator.FILTER_NONE;
  65206. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65207. this._contactHardeningLightSizeUVRatio = 0.1;
  65208. this._darkness = 0;
  65209. this._transparencyShadow = false;
  65210. /**
  65211. * Controls the extent to which the shadows fade out at the edge of the frustum
  65212. * Used only by directionals and spots
  65213. */
  65214. this.frustumEdgeFalloff = 0;
  65215. /**
  65216. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65217. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65218. * It might on the other hand introduce peter panning.
  65219. */
  65220. this.forceBackFacesOnly = false;
  65221. this._lightDirection = BABYLON.Vector3.Zero();
  65222. this._viewMatrix = BABYLON.Matrix.Zero();
  65223. this._projectionMatrix = BABYLON.Matrix.Zero();
  65224. this._transformMatrix = BABYLON.Matrix.Zero();
  65225. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65226. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65227. this._currentFaceIndex = 0;
  65228. this._currentFaceIndexCache = 0;
  65229. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65230. this._mapSize = mapSize;
  65231. this._light = light;
  65232. this._scene = light.getScene();
  65233. light._shadowGenerator = this;
  65234. // Texture type fallback from float to int if not supported.
  65235. var caps = this._scene.getEngine().getCaps();
  65236. if (!useFullFloatFirst) {
  65237. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65238. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65239. }
  65240. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65241. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65242. }
  65243. else {
  65244. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65245. }
  65246. }
  65247. else {
  65248. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65249. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65250. }
  65251. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65252. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65253. }
  65254. else {
  65255. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65256. }
  65257. }
  65258. this._initializeGenerator();
  65259. this._applyFilterValues();
  65260. }
  65261. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65262. /**
  65263. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65264. */
  65265. get: function () {
  65266. return this._bias;
  65267. },
  65268. /**
  65269. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65270. */
  65271. set: function (bias) {
  65272. this._bias = bias;
  65273. },
  65274. enumerable: true,
  65275. configurable: true
  65276. });
  65277. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65278. /**
  65279. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65280. */
  65281. get: function () {
  65282. return this._normalBias;
  65283. },
  65284. /**
  65285. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65286. */
  65287. set: function (normalBias) {
  65288. this._normalBias = normalBias;
  65289. },
  65290. enumerable: true,
  65291. configurable: true
  65292. });
  65293. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65294. /**
  65295. * Gets the blur box offset: offset applied during the blur pass.
  65296. * Only usefull if useKernelBlur = false
  65297. */
  65298. get: function () {
  65299. return this._blurBoxOffset;
  65300. },
  65301. /**
  65302. * Sets the blur box offset: offset applied during the blur pass.
  65303. * Only usefull if useKernelBlur = false
  65304. */
  65305. set: function (value) {
  65306. if (this._blurBoxOffset === value) {
  65307. return;
  65308. }
  65309. this._blurBoxOffset = value;
  65310. this._disposeBlurPostProcesses();
  65311. },
  65312. enumerable: true,
  65313. configurable: true
  65314. });
  65315. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65316. /**
  65317. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65318. * 2 means half of the size.
  65319. */
  65320. get: function () {
  65321. return this._blurScale;
  65322. },
  65323. /**
  65324. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65325. * 2 means half of the size.
  65326. */
  65327. set: function (value) {
  65328. if (this._blurScale === value) {
  65329. return;
  65330. }
  65331. this._blurScale = value;
  65332. this._disposeBlurPostProcesses();
  65333. },
  65334. enumerable: true,
  65335. configurable: true
  65336. });
  65337. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65338. /**
  65339. * Gets the blur kernel: kernel size of the blur pass.
  65340. * Only usefull if useKernelBlur = true
  65341. */
  65342. get: function () {
  65343. return this._blurKernel;
  65344. },
  65345. /**
  65346. * Sets the blur kernel: kernel size of the blur pass.
  65347. * Only usefull if useKernelBlur = true
  65348. */
  65349. set: function (value) {
  65350. if (this._blurKernel === value) {
  65351. return;
  65352. }
  65353. this._blurKernel = value;
  65354. this._disposeBlurPostProcesses();
  65355. },
  65356. enumerable: true,
  65357. configurable: true
  65358. });
  65359. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65360. /**
  65361. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65362. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65363. */
  65364. get: function () {
  65365. return this._useKernelBlur;
  65366. },
  65367. /**
  65368. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65369. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65370. */
  65371. set: function (value) {
  65372. if (this._useKernelBlur === value) {
  65373. return;
  65374. }
  65375. this._useKernelBlur = value;
  65376. this._disposeBlurPostProcesses();
  65377. },
  65378. enumerable: true,
  65379. configurable: true
  65380. });
  65381. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65382. /**
  65383. * Gets the depth scale used in ESM mode.
  65384. */
  65385. get: function () {
  65386. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65387. },
  65388. /**
  65389. * Sets the depth scale used in ESM mode.
  65390. * This can override the scale stored on the light.
  65391. */
  65392. set: function (value) {
  65393. this._depthScale = value;
  65394. },
  65395. enumerable: true,
  65396. configurable: true
  65397. });
  65398. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65399. /**
  65400. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65401. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65402. */
  65403. get: function () {
  65404. return this._filter;
  65405. },
  65406. /**
  65407. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65408. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65409. */
  65410. set: function (value) {
  65411. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65412. if (this._light.needCube()) {
  65413. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65414. this.useExponentialShadowMap = true;
  65415. return;
  65416. }
  65417. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65418. this.useCloseExponentialShadowMap = true;
  65419. return;
  65420. }
  65421. // PCF on cubemap would also be expensive
  65422. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65423. this.usePoissonSampling = true;
  65424. return;
  65425. }
  65426. }
  65427. // Weblg1 fallback for PCF.
  65428. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65429. if (this._scene.getEngine().webGLVersion === 1) {
  65430. this.usePoissonSampling = true;
  65431. return;
  65432. }
  65433. }
  65434. if (this._filter === value) {
  65435. return;
  65436. }
  65437. this._filter = value;
  65438. this._disposeBlurPostProcesses();
  65439. this._applyFilterValues();
  65440. this._light._markMeshesAsLightDirty();
  65441. },
  65442. enumerable: true,
  65443. configurable: true
  65444. });
  65445. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65446. /**
  65447. * Gets if the current filter is set to Poisson Sampling.
  65448. */
  65449. get: function () {
  65450. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65451. },
  65452. /**
  65453. * Sets the current filter to Poisson Sampling.
  65454. */
  65455. set: function (value) {
  65456. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65457. return;
  65458. }
  65459. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65460. },
  65461. enumerable: true,
  65462. configurable: true
  65463. });
  65464. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65465. /**
  65466. * Gets if the current filter is set to VSM.
  65467. * DEPRECATED. Should use useExponentialShadowMap instead.
  65468. */
  65469. get: function () {
  65470. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65471. return this.useExponentialShadowMap;
  65472. },
  65473. /**
  65474. * Sets the current filter is to VSM.
  65475. * DEPRECATED. Should use useExponentialShadowMap instead.
  65476. */
  65477. set: function (value) {
  65478. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65479. this.useExponentialShadowMap = value;
  65480. },
  65481. enumerable: true,
  65482. configurable: true
  65483. });
  65484. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65485. /**
  65486. * Gets if the current filter is set to blurred VSM.
  65487. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65488. */
  65489. get: function () {
  65490. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65491. return this.useBlurExponentialShadowMap;
  65492. },
  65493. /**
  65494. * Sets the current filter is to blurred VSM.
  65495. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65496. */
  65497. set: function (value) {
  65498. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65499. this.useBlurExponentialShadowMap = value;
  65500. },
  65501. enumerable: true,
  65502. configurable: true
  65503. });
  65504. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65505. /**
  65506. * Gets if the current filter is set to ESM.
  65507. */
  65508. get: function () {
  65509. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65510. },
  65511. /**
  65512. * Sets the current filter is to ESM.
  65513. */
  65514. set: function (value) {
  65515. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65516. return;
  65517. }
  65518. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65519. },
  65520. enumerable: true,
  65521. configurable: true
  65522. });
  65523. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65524. /**
  65525. * Gets if the current filter is set to filtered ESM.
  65526. */
  65527. get: function () {
  65528. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65529. },
  65530. /**
  65531. * Gets if the current filter is set to filtered ESM.
  65532. */
  65533. set: function (value) {
  65534. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65535. return;
  65536. }
  65537. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65538. },
  65539. enumerable: true,
  65540. configurable: true
  65541. });
  65542. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65543. /**
  65544. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65545. * exponential to prevent steep falloff artifacts).
  65546. */
  65547. get: function () {
  65548. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65549. },
  65550. /**
  65551. * Sets the current filter to "close ESM" (using the inverse of the
  65552. * exponential to prevent steep falloff artifacts).
  65553. */
  65554. set: function (value) {
  65555. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65556. return;
  65557. }
  65558. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65559. },
  65560. enumerable: true,
  65561. configurable: true
  65562. });
  65563. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65564. /**
  65565. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65566. * exponential to prevent steep falloff artifacts).
  65567. */
  65568. get: function () {
  65569. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65570. },
  65571. /**
  65572. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65573. * exponential to prevent steep falloff artifacts).
  65574. */
  65575. set: function (value) {
  65576. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65577. return;
  65578. }
  65579. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65580. },
  65581. enumerable: true,
  65582. configurable: true
  65583. });
  65584. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65585. /**
  65586. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65587. */
  65588. get: function () {
  65589. return this.filter === ShadowGenerator.FILTER_PCF;
  65590. },
  65591. /**
  65592. * Sets the current filter to "PCF" (percentage closer filtering).
  65593. */
  65594. set: function (value) {
  65595. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65596. return;
  65597. }
  65598. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65599. },
  65600. enumerable: true,
  65601. configurable: true
  65602. });
  65603. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65604. /**
  65605. * Gets the PCF or PCSS Quality.
  65606. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65607. */
  65608. get: function () {
  65609. return this._filteringQuality;
  65610. },
  65611. /**
  65612. * Sets the PCF or PCSS Quality.
  65613. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65614. */
  65615. set: function (filteringQuality) {
  65616. this._filteringQuality = filteringQuality;
  65617. },
  65618. enumerable: true,
  65619. configurable: true
  65620. });
  65621. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65622. /**
  65623. * Gets if the current filter is set to "PCSS" (contact hardening).
  65624. */
  65625. get: function () {
  65626. return this.filter === ShadowGenerator.FILTER_PCSS;
  65627. },
  65628. /**
  65629. * Sets the current filter to "PCSS" (contact hardening).
  65630. */
  65631. set: function (value) {
  65632. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65633. return;
  65634. }
  65635. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65636. },
  65637. enumerable: true,
  65638. configurable: true
  65639. });
  65640. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65641. /**
  65642. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65643. * Using a ratio helps keeping shape stability independently of the map size.
  65644. *
  65645. * It does not account for the light projection as it was having too much
  65646. * instability during the light setup or during light position changes.
  65647. *
  65648. * Only valid if useContactHardeningShadow is true.
  65649. */
  65650. get: function () {
  65651. return this._contactHardeningLightSizeUVRatio;
  65652. },
  65653. /**
  65654. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65655. * Using a ratio helps keeping shape stability independently of the map size.
  65656. *
  65657. * It does not account for the light projection as it was having too much
  65658. * instability during the light setup or during light position changes.
  65659. *
  65660. * Only valid if useContactHardeningShadow is true.
  65661. */
  65662. set: function (contactHardeningLightSizeUVRatio) {
  65663. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65664. },
  65665. enumerable: true,
  65666. configurable: true
  65667. });
  65668. /**
  65669. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65670. * 0 means strongest and 1 would means no shadow.
  65671. * @returns the darkness.
  65672. */
  65673. ShadowGenerator.prototype.getDarkness = function () {
  65674. return this._darkness;
  65675. };
  65676. /**
  65677. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65678. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65679. * @returns the shadow generator allowing fluent coding.
  65680. */
  65681. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65682. if (darkness >= 1.0)
  65683. this._darkness = 1.0;
  65684. else if (darkness <= 0.0)
  65685. this._darkness = 0.0;
  65686. else
  65687. this._darkness = darkness;
  65688. return this;
  65689. };
  65690. /**
  65691. * Sets the ability to have transparent shadow (boolean).
  65692. * @param transparent True if transparent else False
  65693. * @returns the shadow generator allowing fluent coding
  65694. */
  65695. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65696. this._transparencyShadow = transparent;
  65697. return this;
  65698. };
  65699. /**
  65700. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65701. * @returns The render target texture if present otherwise, null
  65702. */
  65703. ShadowGenerator.prototype.getShadowMap = function () {
  65704. return this._shadowMap;
  65705. };
  65706. /**
  65707. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65708. * @returns The render target texture if the shadow map is present otherwise, null
  65709. */
  65710. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65711. if (this._shadowMap2) {
  65712. return this._shadowMap2;
  65713. }
  65714. return this._shadowMap;
  65715. };
  65716. /**
  65717. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65718. * @param mesh Mesh to add
  65719. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65720. * @returns the Shadow Generator itself
  65721. */
  65722. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65723. if (includeDescendants === void 0) { includeDescendants = true; }
  65724. if (!this._shadowMap) {
  65725. return this;
  65726. }
  65727. if (!this._shadowMap.renderList) {
  65728. this._shadowMap.renderList = [];
  65729. }
  65730. this._shadowMap.renderList.push(mesh);
  65731. if (includeDescendants) {
  65732. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65733. }
  65734. return this;
  65735. var _a;
  65736. };
  65737. /**
  65738. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65739. * @param mesh Mesh to remove
  65740. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65741. * @returns the Shadow Generator itself
  65742. */
  65743. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65744. if (includeDescendants === void 0) { includeDescendants = true; }
  65745. if (!this._shadowMap || !this._shadowMap.renderList) {
  65746. return this;
  65747. }
  65748. var index = this._shadowMap.renderList.indexOf(mesh);
  65749. if (index !== -1) {
  65750. this._shadowMap.renderList.splice(index, 1);
  65751. }
  65752. if (includeDescendants) {
  65753. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65754. var child = _a[_i];
  65755. this.removeShadowCaster(child);
  65756. }
  65757. }
  65758. return this;
  65759. };
  65760. /**
  65761. * Returns the associated light object.
  65762. * @returns the light generating the shadow
  65763. */
  65764. ShadowGenerator.prototype.getLight = function () {
  65765. return this._light;
  65766. };
  65767. ShadowGenerator.prototype._initializeGenerator = function () {
  65768. this._light._markMeshesAsLightDirty();
  65769. this._initializeShadowMap();
  65770. };
  65771. ShadowGenerator.prototype._initializeShadowMap = function () {
  65772. var _this = this;
  65773. // Render target
  65774. var engine = this._scene.getEngine();
  65775. if (engine.webGLVersion > 1) {
  65776. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65777. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65778. }
  65779. else {
  65780. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65781. }
  65782. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65783. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65784. this._shadowMap.anisotropicFilteringLevel = 1;
  65785. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65786. this._shadowMap.renderParticles = false;
  65787. this._shadowMap.ignoreCameraViewport = true;
  65788. // Record Face Index before render.
  65789. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65790. _this._currentFaceIndex = faceIndex;
  65791. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65792. engine.setColorWrite(false);
  65793. }
  65794. });
  65795. // Custom render function.
  65796. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65797. // Blur if required afer render.
  65798. this._shadowMap.onAfterUnbindObservable.add(function () {
  65799. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65800. engine.setColorWrite(true);
  65801. }
  65802. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65803. return;
  65804. }
  65805. var shadowMap = _this.getShadowMapForRendering();
  65806. if (shadowMap) {
  65807. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65808. }
  65809. });
  65810. // Clear according to the chosen filter.
  65811. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65812. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65813. this._shadowMap.onClearObservable.add(function (engine) {
  65814. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65815. engine.clear(clearOne, false, true, false);
  65816. }
  65817. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65818. engine.clear(clearZero, true, true, false);
  65819. }
  65820. else {
  65821. engine.clear(clearOne, true, true, false);
  65822. }
  65823. });
  65824. };
  65825. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65826. var _this = this;
  65827. var engine = this._scene.getEngine();
  65828. var targetSize = this._mapSize / this.blurScale;
  65829. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65830. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65831. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65832. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65833. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65834. }
  65835. if (this.useKernelBlur) {
  65836. 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);
  65837. this._kernelBlurXPostprocess.width = targetSize;
  65838. this._kernelBlurXPostprocess.height = targetSize;
  65839. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65840. effect.setTexture("textureSampler", _this._shadowMap);
  65841. });
  65842. 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);
  65843. this._kernelBlurXPostprocess.autoClear = false;
  65844. this._kernelBlurYPostprocess.autoClear = false;
  65845. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65846. this._kernelBlurXPostprocess.packedFloat = true;
  65847. this._kernelBlurYPostprocess.packedFloat = true;
  65848. }
  65849. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65850. }
  65851. else {
  65852. 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);
  65853. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65854. effect.setFloat2("screenSize", targetSize, targetSize);
  65855. effect.setTexture("textureSampler", _this._shadowMap);
  65856. });
  65857. this._boxBlurPostprocess.autoClear = false;
  65858. this._blurPostProcesses = [this._boxBlurPostprocess];
  65859. }
  65860. };
  65861. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65862. var index;
  65863. var engine = this._scene.getEngine();
  65864. if (depthOnlySubMeshes.length) {
  65865. engine.setColorWrite(false);
  65866. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65867. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65868. }
  65869. engine.setColorWrite(true);
  65870. }
  65871. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65872. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65873. }
  65874. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65875. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65876. }
  65877. if (this._transparencyShadow) {
  65878. for (index = 0; index < transparentSubMeshes.length; index++) {
  65879. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65880. }
  65881. }
  65882. };
  65883. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65884. var _this = this;
  65885. var mesh = subMesh.getRenderingMesh();
  65886. var scene = this._scene;
  65887. var engine = scene.getEngine();
  65888. var material = subMesh.getMaterial();
  65889. if (!material) {
  65890. return;
  65891. }
  65892. // Culling
  65893. engine.setState(material.backFaceCulling);
  65894. // Managing instances
  65895. var batch = mesh._getInstancesRenderList(subMesh._id);
  65896. if (batch.mustReturn) {
  65897. return;
  65898. }
  65899. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65900. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65901. engine.enableEffect(this._effect);
  65902. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65903. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65904. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65905. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65906. this._effect.setVector3("lightData", this._cachedDirection);
  65907. }
  65908. else {
  65909. this._effect.setVector3("lightData", this._cachedPosition);
  65910. }
  65911. if (scene.activeCamera) {
  65912. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65913. }
  65914. // Alpha test
  65915. if (material && material.needAlphaTesting()) {
  65916. var alphaTexture = material.getAlphaTestTexture();
  65917. if (alphaTexture) {
  65918. this._effect.setTexture("diffuseSampler", alphaTexture);
  65919. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65920. }
  65921. }
  65922. // Bones
  65923. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65924. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65925. }
  65926. // Morph targets
  65927. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65928. if (this.forceBackFacesOnly) {
  65929. engine.setState(true, 0, false, true);
  65930. }
  65931. // Draw
  65932. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65933. if (this.forceBackFacesOnly) {
  65934. engine.setState(true, 0, false, false);
  65935. }
  65936. }
  65937. else {
  65938. // Need to reset refresh rate of the shadowMap
  65939. if (this._shadowMap) {
  65940. this._shadowMap.resetRefreshCounter();
  65941. }
  65942. }
  65943. };
  65944. ShadowGenerator.prototype._applyFilterValues = function () {
  65945. if (!this._shadowMap) {
  65946. return;
  65947. }
  65948. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65949. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65950. }
  65951. else {
  65952. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65953. }
  65954. };
  65955. /**
  65956. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65957. * @param onCompiled Callback triggered at the and of the effects compilation
  65958. * @param options Sets of optional options forcing the compilation with different modes
  65959. */
  65960. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65961. var _this = this;
  65962. var localOptions = __assign({ useInstances: false }, options);
  65963. var shadowMap = this.getShadowMap();
  65964. if (!shadowMap) {
  65965. if (onCompiled) {
  65966. onCompiled(this);
  65967. }
  65968. return;
  65969. }
  65970. var renderList = shadowMap.renderList;
  65971. if (!renderList) {
  65972. if (onCompiled) {
  65973. onCompiled(this);
  65974. }
  65975. return;
  65976. }
  65977. var subMeshes = new Array();
  65978. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65979. var mesh = renderList_1[_i];
  65980. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65981. }
  65982. if (subMeshes.length === 0) {
  65983. if (onCompiled) {
  65984. onCompiled(this);
  65985. }
  65986. return;
  65987. }
  65988. var currentIndex = 0;
  65989. var checkReady = function () {
  65990. if (!_this._scene || !_this._scene.getEngine()) {
  65991. return;
  65992. }
  65993. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65994. currentIndex++;
  65995. if (currentIndex >= subMeshes.length) {
  65996. if (onCompiled) {
  65997. onCompiled(_this);
  65998. }
  65999. return;
  66000. }
  66001. }
  66002. setTimeout(checkReady, 16);
  66003. };
  66004. checkReady();
  66005. };
  66006. /**
  66007. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66008. * @param options Sets of optional options forcing the compilation with different modes
  66009. * @returns A promise that resolves when the compilation completes
  66010. */
  66011. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66012. var _this = this;
  66013. return new Promise(function (resolve) {
  66014. _this.forceCompilation(function () {
  66015. resolve();
  66016. }, options);
  66017. });
  66018. };
  66019. /**
  66020. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66021. * @param subMesh The submesh we want to render in the shadow map
  66022. * @param useInstances Defines wether will draw in the map using instances
  66023. * @returns true if ready otherwise, false
  66024. */
  66025. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66026. var defines = [];
  66027. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66028. defines.push("#define FLOAT");
  66029. }
  66030. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66031. defines.push("#define ESM");
  66032. }
  66033. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66034. defines.push("#define DEPTHTEXTURE");
  66035. }
  66036. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66037. var mesh = subMesh.getMesh();
  66038. var material = subMesh.getMaterial();
  66039. // Normal bias.
  66040. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66041. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66042. defines.push("#define NORMAL");
  66043. if (mesh.nonUniformScaling) {
  66044. defines.push("#define NONUNIFORMSCALING");
  66045. }
  66046. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66047. defines.push("#define DIRECTIONINLIGHTDATA");
  66048. }
  66049. }
  66050. // Alpha test
  66051. if (material && material.needAlphaTesting()) {
  66052. var alphaTexture = material.getAlphaTestTexture();
  66053. if (alphaTexture) {
  66054. defines.push("#define ALPHATEST");
  66055. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66056. attribs.push(BABYLON.VertexBuffer.UVKind);
  66057. defines.push("#define UV1");
  66058. }
  66059. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66060. if (alphaTexture.coordinatesIndex === 1) {
  66061. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66062. defines.push("#define UV2");
  66063. }
  66064. }
  66065. }
  66066. }
  66067. // Bones
  66068. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66069. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66070. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66071. if (mesh.numBoneInfluencers > 4) {
  66072. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66073. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66074. }
  66075. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66076. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66077. }
  66078. else {
  66079. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66080. }
  66081. // Morph targets
  66082. var manager = mesh.morphTargetManager;
  66083. var morphInfluencers = 0;
  66084. if (manager) {
  66085. if (manager.numInfluencers > 0) {
  66086. defines.push("#define MORPHTARGETS");
  66087. morphInfluencers = manager.numInfluencers;
  66088. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66089. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66090. }
  66091. }
  66092. // Instances
  66093. if (useInstances) {
  66094. defines.push("#define INSTANCES");
  66095. attribs.push("world0");
  66096. attribs.push("world1");
  66097. attribs.push("world2");
  66098. attribs.push("world3");
  66099. }
  66100. // Get correct effect
  66101. var join = defines.join("\n");
  66102. if (this._cachedDefines !== join) {
  66103. this._cachedDefines = join;
  66104. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66105. }
  66106. if (!this._effect.isReady()) {
  66107. return false;
  66108. }
  66109. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66110. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66111. this._initializeBlurRTTAndPostProcesses();
  66112. }
  66113. }
  66114. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66115. return false;
  66116. }
  66117. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66118. return false;
  66119. }
  66120. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66121. return false;
  66122. }
  66123. return true;
  66124. };
  66125. /**
  66126. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66127. * @param defines Defines of the material we want to update
  66128. * @param lightIndex Index of the light in the enabled light list of the material
  66129. */
  66130. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66131. var scene = this._scene;
  66132. var light = this._light;
  66133. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66134. return;
  66135. }
  66136. defines["SHADOW" + lightIndex] = true;
  66137. if (this.useContactHardeningShadow) {
  66138. defines["SHADOWPCSS" + lightIndex] = true;
  66139. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66140. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66141. }
  66142. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66143. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66144. }
  66145. // else default to high.
  66146. }
  66147. if (this.usePercentageCloserFiltering) {
  66148. defines["SHADOWPCF" + lightIndex] = true;
  66149. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66150. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66151. }
  66152. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66153. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66154. }
  66155. // else default to high.
  66156. }
  66157. else if (this.usePoissonSampling) {
  66158. defines["SHADOWPOISSON" + lightIndex] = true;
  66159. }
  66160. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66161. defines["SHADOWESM" + lightIndex] = true;
  66162. }
  66163. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66164. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66165. }
  66166. if (light.needCube()) {
  66167. defines["SHADOWCUBE" + lightIndex] = true;
  66168. }
  66169. };
  66170. /**
  66171. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66172. * defined in the generator but impacting the effect).
  66173. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66174. * @param effect The effect we are binfing the information for
  66175. */
  66176. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66177. var light = this._light;
  66178. var scene = this._scene;
  66179. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66180. return;
  66181. }
  66182. var camera = scene.activeCamera;
  66183. if (!camera) {
  66184. return;
  66185. }
  66186. var shadowMap = this.getShadowMap();
  66187. if (!shadowMap) {
  66188. return;
  66189. }
  66190. if (!light.needCube()) {
  66191. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66192. }
  66193. // Only PCF uses depth stencil texture.
  66194. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66195. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66196. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66197. }
  66198. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66199. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66200. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66201. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66202. }
  66203. else {
  66204. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66205. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66206. }
  66207. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66208. };
  66209. /**
  66210. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66211. * (eq to shadow prjection matrix * light transform matrix)
  66212. * @returns The transform matrix used to create the shadow map
  66213. */
  66214. ShadowGenerator.prototype.getTransformMatrix = function () {
  66215. var scene = this._scene;
  66216. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66217. return this._transformMatrix;
  66218. }
  66219. this._currentRenderID = scene.getRenderId();
  66220. this._currentFaceIndexCache = this._currentFaceIndex;
  66221. var lightPosition = this._light.position;
  66222. if (this._light.computeTransformedInformation()) {
  66223. lightPosition = this._light.transformedPosition;
  66224. }
  66225. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66226. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66227. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66228. }
  66229. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66230. this._cachedPosition.copyFrom(lightPosition);
  66231. this._cachedDirection.copyFrom(this._lightDirection);
  66232. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66233. var shadowMap = this.getShadowMap();
  66234. if (shadowMap) {
  66235. var renderList = shadowMap.renderList;
  66236. if (renderList) {
  66237. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66238. }
  66239. }
  66240. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66241. }
  66242. return this._transformMatrix;
  66243. };
  66244. /**
  66245. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66246. * Cube and 2D textures for instance.
  66247. */
  66248. ShadowGenerator.prototype.recreateShadowMap = function () {
  66249. var shadowMap = this._shadowMap;
  66250. if (!shadowMap) {
  66251. return;
  66252. }
  66253. // Track render list.
  66254. var renderList = shadowMap.renderList;
  66255. // Clean up existing data.
  66256. this._disposeRTTandPostProcesses();
  66257. // Reinitializes.
  66258. this._initializeGenerator();
  66259. // Reaffect the filter to ensure a correct fallback if necessary.
  66260. this.filter = this.filter;
  66261. // Reaffect the filter.
  66262. this._applyFilterValues();
  66263. // Reaffect Render List.
  66264. this._shadowMap.renderList = renderList;
  66265. };
  66266. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66267. if (this._shadowMap2) {
  66268. this._shadowMap2.dispose();
  66269. this._shadowMap2 = null;
  66270. }
  66271. if (this._boxBlurPostprocess) {
  66272. this._boxBlurPostprocess.dispose();
  66273. this._boxBlurPostprocess = null;
  66274. }
  66275. if (this._kernelBlurXPostprocess) {
  66276. this._kernelBlurXPostprocess.dispose();
  66277. this._kernelBlurXPostprocess = null;
  66278. }
  66279. if (this._kernelBlurYPostprocess) {
  66280. this._kernelBlurYPostprocess.dispose();
  66281. this._kernelBlurYPostprocess = null;
  66282. }
  66283. this._blurPostProcesses = [];
  66284. };
  66285. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66286. if (this._shadowMap) {
  66287. this._shadowMap.dispose();
  66288. this._shadowMap = null;
  66289. }
  66290. this._disposeBlurPostProcesses();
  66291. };
  66292. /**
  66293. * Disposes the ShadowGenerator.
  66294. * Returns nothing.
  66295. */
  66296. ShadowGenerator.prototype.dispose = function () {
  66297. this._disposeRTTandPostProcesses();
  66298. if (this._light) {
  66299. this._light._shadowGenerator = null;
  66300. this._light._markMeshesAsLightDirty();
  66301. }
  66302. };
  66303. /**
  66304. * Serializes the shadow generator setup to a json object.
  66305. * @returns The serialized JSON object
  66306. */
  66307. ShadowGenerator.prototype.serialize = function () {
  66308. var serializationObject = {};
  66309. var shadowMap = this.getShadowMap();
  66310. if (!shadowMap) {
  66311. return serializationObject;
  66312. }
  66313. serializationObject.lightId = this._light.id;
  66314. serializationObject.mapSize = shadowMap.getRenderSize();
  66315. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66316. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66317. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66318. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66319. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66320. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66321. serializationObject.depthScale = this.depthScale;
  66322. serializationObject.darkness = this.getDarkness();
  66323. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66324. serializationObject.blurKernel = this.blurKernel;
  66325. serializationObject.blurScale = this.blurScale;
  66326. serializationObject.useKernelBlur = this.useKernelBlur;
  66327. serializationObject.transparencyShadow = this._transparencyShadow;
  66328. serializationObject.bias = this.bias;
  66329. serializationObject.normalBias = this.normalBias;
  66330. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66331. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66332. serializationObject.filteringQuality = this.filteringQuality;
  66333. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66334. serializationObject.renderList = [];
  66335. if (shadowMap.renderList) {
  66336. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66337. var mesh = shadowMap.renderList[meshIndex];
  66338. serializationObject.renderList.push(mesh.id);
  66339. }
  66340. }
  66341. return serializationObject;
  66342. };
  66343. /**
  66344. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66345. * @param parsedShadowGenerator The JSON object to parse
  66346. * @param scene The scene to create the shadow map for
  66347. * @returns The parsed shadow generator
  66348. */
  66349. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66350. //casting to point light, as light is missing the position attr and typescript complains.
  66351. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66352. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66353. var shadowMap = shadowGenerator.getShadowMap();
  66354. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66355. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66356. meshes.forEach(function (mesh) {
  66357. if (!shadowMap) {
  66358. return;
  66359. }
  66360. if (!shadowMap.renderList) {
  66361. shadowMap.renderList = [];
  66362. }
  66363. shadowMap.renderList.push(mesh);
  66364. });
  66365. }
  66366. if (parsedShadowGenerator.usePoissonSampling) {
  66367. shadowGenerator.usePoissonSampling = true;
  66368. }
  66369. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66370. shadowGenerator.useExponentialShadowMap = true;
  66371. }
  66372. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66373. shadowGenerator.useBlurExponentialShadowMap = true;
  66374. }
  66375. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66376. shadowGenerator.useCloseExponentialShadowMap = true;
  66377. }
  66378. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66379. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66380. }
  66381. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66382. shadowGenerator.usePercentageCloserFiltering = true;
  66383. }
  66384. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66385. shadowGenerator.useContactHardeningShadow = true;
  66386. }
  66387. if (parsedShadowGenerator.filteringQuality) {
  66388. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66389. }
  66390. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66391. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66392. }
  66393. // Backward compat
  66394. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66395. shadowGenerator.useExponentialShadowMap = true;
  66396. }
  66397. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66398. shadowGenerator.useBlurExponentialShadowMap = true;
  66399. }
  66400. if (parsedShadowGenerator.depthScale) {
  66401. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66402. }
  66403. if (parsedShadowGenerator.blurScale) {
  66404. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66405. }
  66406. if (parsedShadowGenerator.blurBoxOffset) {
  66407. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66408. }
  66409. if (parsedShadowGenerator.useKernelBlur) {
  66410. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66411. }
  66412. if (parsedShadowGenerator.blurKernel) {
  66413. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66414. }
  66415. if (parsedShadowGenerator.bias !== undefined) {
  66416. shadowGenerator.bias = parsedShadowGenerator.bias;
  66417. }
  66418. if (parsedShadowGenerator.normalBias !== undefined) {
  66419. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66420. }
  66421. if (parsedShadowGenerator.darkness) {
  66422. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66423. }
  66424. if (parsedShadowGenerator.transparencyShadow) {
  66425. shadowGenerator.setTransparencyShadow(true);
  66426. }
  66427. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66428. return shadowGenerator;
  66429. };
  66430. /**
  66431. * Shadow generator mode None: no filtering applied.
  66432. */
  66433. ShadowGenerator.FILTER_NONE = 0;
  66434. /**
  66435. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66436. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66437. */
  66438. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66439. /**
  66440. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66441. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66442. */
  66443. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66444. /**
  66445. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66446. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66447. */
  66448. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66449. /**
  66450. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66451. * edge artifacts on steep falloff.
  66452. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66453. */
  66454. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66455. /**
  66456. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66457. * edge artifacts on steep falloff.
  66458. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66459. */
  66460. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66461. /**
  66462. * Shadow generator mode PCF: Percentage Closer Filtering
  66463. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66464. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66465. */
  66466. ShadowGenerator.FILTER_PCF = 6;
  66467. /**
  66468. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66469. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66470. * Contact Hardening
  66471. */
  66472. ShadowGenerator.FILTER_PCSS = 7;
  66473. /**
  66474. * Reserved for PCF and PCSS
  66475. * Highest Quality.
  66476. *
  66477. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66478. *
  66479. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66480. */
  66481. ShadowGenerator.QUALITY_HIGH = 0;
  66482. /**
  66483. * Reserved for PCF and PCSS
  66484. * Good tradeoff for quality/perf cross devices
  66485. *
  66486. * Execute PCF on a 3*3 kernel.
  66487. *
  66488. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66489. */
  66490. ShadowGenerator.QUALITY_MEDIUM = 1;
  66491. /**
  66492. * Reserved for PCF and PCSS
  66493. * The lowest quality but the fastest.
  66494. *
  66495. * Execute PCF on a 1*1 kernel.
  66496. *
  66497. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66498. */
  66499. ShadowGenerator.QUALITY_LOW = 2;
  66500. return ShadowGenerator;
  66501. }());
  66502. BABYLON.ShadowGenerator = ShadowGenerator;
  66503. })(BABYLON || (BABYLON = {}));
  66504. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66505. var BABYLON;
  66506. (function (BABYLON) {
  66507. var DefaultLoadingScreen = /** @class */ (function () {
  66508. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66509. if (_loadingText === void 0) { _loadingText = ""; }
  66510. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66511. var _this = this;
  66512. this._renderingCanvas = _renderingCanvas;
  66513. this._loadingText = _loadingText;
  66514. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66515. // Resize
  66516. this._resizeLoadingUI = function () {
  66517. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66518. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66519. if (!_this._loadingDiv) {
  66520. return;
  66521. }
  66522. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66523. _this._loadingDiv.style.left = canvasRect.left + "px";
  66524. _this._loadingDiv.style.top = canvasRect.top + "px";
  66525. _this._loadingDiv.style.width = canvasRect.width + "px";
  66526. _this._loadingDiv.style.height = canvasRect.height + "px";
  66527. };
  66528. }
  66529. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66530. if (this._loadingDiv) {
  66531. // Do not add a loading screen if there is already one
  66532. return;
  66533. }
  66534. this._loadingDiv = document.createElement("div");
  66535. this._loadingDiv.id = "babylonjsLoadingDiv";
  66536. this._loadingDiv.style.opacity = "0";
  66537. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66538. this._loadingDiv.style.pointerEvents = "none";
  66539. // Loading text
  66540. this._loadingTextDiv = document.createElement("div");
  66541. this._loadingTextDiv.style.position = "absolute";
  66542. this._loadingTextDiv.style.left = "0";
  66543. this._loadingTextDiv.style.top = "50%";
  66544. this._loadingTextDiv.style.marginTop = "80px";
  66545. this._loadingTextDiv.style.width = "100%";
  66546. this._loadingTextDiv.style.height = "20px";
  66547. this._loadingTextDiv.style.fontFamily = "Arial";
  66548. this._loadingTextDiv.style.fontSize = "14px";
  66549. this._loadingTextDiv.style.color = "white";
  66550. this._loadingTextDiv.style.textAlign = "center";
  66551. this._loadingTextDiv.innerHTML = "Loading";
  66552. this._loadingDiv.appendChild(this._loadingTextDiv);
  66553. //set the predefined text
  66554. this._loadingTextDiv.innerHTML = this._loadingText;
  66555. // Generating keyframes
  66556. var style = document.createElement('style');
  66557. style.type = 'text/css';
  66558. 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 }";
  66559. style.innerHTML = keyFrames;
  66560. document.getElementsByTagName('head')[0].appendChild(style);
  66561. // Loading img
  66562. var imgBack = new Image();
  66563. 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";
  66564. imgBack.style.position = "absolute";
  66565. imgBack.style.left = "50%";
  66566. imgBack.style.top = "50%";
  66567. imgBack.style.marginLeft = "-60px";
  66568. imgBack.style.marginTop = "-60px";
  66569. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66570. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66571. imgBack.style.transformOrigin = "50% 50%";
  66572. imgBack.style.webkitTransformOrigin = "50% 50%";
  66573. this._loadingDiv.appendChild(imgBack);
  66574. this._resizeLoadingUI();
  66575. window.addEventListener("resize", this._resizeLoadingUI);
  66576. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66577. document.body.appendChild(this._loadingDiv);
  66578. this._loadingDiv.style.opacity = "1";
  66579. };
  66580. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66581. var _this = this;
  66582. if (!this._loadingDiv) {
  66583. return;
  66584. }
  66585. var onTransitionEnd = function () {
  66586. if (!_this._loadingDiv) {
  66587. return;
  66588. }
  66589. document.body.removeChild(_this._loadingDiv);
  66590. window.removeEventListener("resize", _this._resizeLoadingUI);
  66591. _this._loadingDiv = null;
  66592. };
  66593. this._loadingDiv.style.opacity = "0";
  66594. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66595. };
  66596. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66597. set: function (text) {
  66598. this._loadingText = text;
  66599. if (this._loadingTextDiv) {
  66600. this._loadingTextDiv.innerHTML = this._loadingText;
  66601. }
  66602. },
  66603. enumerable: true,
  66604. configurable: true
  66605. });
  66606. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66607. get: function () {
  66608. return this._loadingDivBackgroundColor;
  66609. },
  66610. set: function (color) {
  66611. this._loadingDivBackgroundColor = color;
  66612. if (!this._loadingDiv) {
  66613. return;
  66614. }
  66615. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66616. },
  66617. enumerable: true,
  66618. configurable: true
  66619. });
  66620. return DefaultLoadingScreen;
  66621. }());
  66622. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66623. })(BABYLON || (BABYLON = {}));
  66624. //# sourceMappingURL=babylon.loadingScreen.js.map
  66625. var BABYLON;
  66626. (function (BABYLON) {
  66627. var SceneLoaderProgressEvent = /** @class */ (function () {
  66628. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66629. this.lengthComputable = lengthComputable;
  66630. this.loaded = loaded;
  66631. this.total = total;
  66632. }
  66633. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66634. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66635. };
  66636. return SceneLoaderProgressEvent;
  66637. }());
  66638. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66639. var SceneLoader = /** @class */ (function () {
  66640. function SceneLoader() {
  66641. }
  66642. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66643. get: function () {
  66644. return 0;
  66645. },
  66646. enumerable: true,
  66647. configurable: true
  66648. });
  66649. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66650. get: function () {
  66651. return 1;
  66652. },
  66653. enumerable: true,
  66654. configurable: true
  66655. });
  66656. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66657. get: function () {
  66658. return 2;
  66659. },
  66660. enumerable: true,
  66661. configurable: true
  66662. });
  66663. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66664. get: function () {
  66665. return 3;
  66666. },
  66667. enumerable: true,
  66668. configurable: true
  66669. });
  66670. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66671. get: function () {
  66672. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66673. },
  66674. set: function (value) {
  66675. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66676. },
  66677. enumerable: true,
  66678. configurable: true
  66679. });
  66680. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66681. get: function () {
  66682. return SceneLoader._ShowLoadingScreen;
  66683. },
  66684. set: function (value) {
  66685. SceneLoader._ShowLoadingScreen = value;
  66686. },
  66687. enumerable: true,
  66688. configurable: true
  66689. });
  66690. Object.defineProperty(SceneLoader, "loggingLevel", {
  66691. get: function () {
  66692. return SceneLoader._loggingLevel;
  66693. },
  66694. set: function (value) {
  66695. SceneLoader._loggingLevel = value;
  66696. },
  66697. enumerable: true,
  66698. configurable: true
  66699. });
  66700. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66701. get: function () {
  66702. return SceneLoader._CleanBoneMatrixWeights;
  66703. },
  66704. set: function (value) {
  66705. SceneLoader._CleanBoneMatrixWeights = value;
  66706. },
  66707. enumerable: true,
  66708. configurable: true
  66709. });
  66710. SceneLoader._getDefaultPlugin = function () {
  66711. return SceneLoader._registeredPlugins[".babylon"];
  66712. };
  66713. SceneLoader._getPluginForExtension = function (extension) {
  66714. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66715. if (registeredPlugin) {
  66716. return registeredPlugin;
  66717. }
  66718. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66719. return SceneLoader._getDefaultPlugin();
  66720. };
  66721. SceneLoader._getPluginForDirectLoad = function (data) {
  66722. for (var extension in SceneLoader._registeredPlugins) {
  66723. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66724. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66725. return SceneLoader._registeredPlugins[extension];
  66726. }
  66727. }
  66728. return SceneLoader._getDefaultPlugin();
  66729. };
  66730. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66731. if (sceneFilename.name) {
  66732. sceneFilename = sceneFilename.name;
  66733. }
  66734. var queryStringPosition = sceneFilename.indexOf("?");
  66735. if (queryStringPosition !== -1) {
  66736. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66737. }
  66738. var dotPosition = sceneFilename.lastIndexOf(".");
  66739. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66740. return SceneLoader._getPluginForExtension(extension);
  66741. };
  66742. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66743. SceneLoader._getDirectLoad = function (sceneFilename) {
  66744. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66745. return sceneFilename.substr(5);
  66746. }
  66747. return null;
  66748. };
  66749. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66750. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66751. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66752. var plugin;
  66753. if (registeredPlugin.plugin.createPlugin) {
  66754. plugin = registeredPlugin.plugin.createPlugin();
  66755. }
  66756. else {
  66757. plugin = registeredPlugin.plugin;
  66758. }
  66759. var useArrayBuffer = registeredPlugin.isBinary;
  66760. var database;
  66761. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66762. var dataCallback = function (data, responseURL) {
  66763. if (scene.isDisposed) {
  66764. onError("Scene has been disposed");
  66765. return;
  66766. }
  66767. scene.database = database;
  66768. onSuccess(plugin, data, responseURL);
  66769. };
  66770. var request = null;
  66771. var pluginDisposed = false;
  66772. var onDisposeObservable = plugin.onDisposeObservable;
  66773. if (onDisposeObservable) {
  66774. onDisposeObservable.add(function () {
  66775. pluginDisposed = true;
  66776. if (request) {
  66777. request.abort();
  66778. request = null;
  66779. }
  66780. onDispose();
  66781. });
  66782. }
  66783. var manifestChecked = function () {
  66784. if (pluginDisposed) {
  66785. return;
  66786. }
  66787. var url = rootUrl + sceneFilename;
  66788. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66789. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66790. } : undefined, database, useArrayBuffer, function (request, exception) {
  66791. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66792. });
  66793. };
  66794. if (directLoad) {
  66795. dataCallback(directLoad);
  66796. return plugin;
  66797. }
  66798. if (rootUrl.indexOf("file:") === -1) {
  66799. var engine = scene.getEngine();
  66800. var canUseOfflineSupport = engine.enableOfflineSupport;
  66801. if (canUseOfflineSupport) {
  66802. // Also check for exceptions
  66803. var exceptionFound = false;
  66804. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66805. var regex = _a[_i];
  66806. if (regex.test(rootUrl + sceneFilename)) {
  66807. exceptionFound = true;
  66808. break;
  66809. }
  66810. }
  66811. canUseOfflineSupport = !exceptionFound;
  66812. }
  66813. if (canUseOfflineSupport) {
  66814. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66815. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66816. }
  66817. else {
  66818. manifestChecked();
  66819. }
  66820. }
  66821. // Loading file from disk via input file or drag'n'drop
  66822. else {
  66823. var fileOrString = sceneFilename;
  66824. if (fileOrString.name) { // File
  66825. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66826. }
  66827. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66828. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66829. }
  66830. else {
  66831. onError("Unable to find file named " + sceneFilename);
  66832. }
  66833. }
  66834. return plugin;
  66835. };
  66836. // Public functions
  66837. SceneLoader.GetPluginForExtension = function (extension) {
  66838. return SceneLoader._getPluginForExtension(extension).plugin;
  66839. };
  66840. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66841. return !!SceneLoader._registeredPlugins[extension];
  66842. };
  66843. SceneLoader.RegisterPlugin = function (plugin) {
  66844. if (typeof plugin.extensions === "string") {
  66845. var extension = plugin.extensions;
  66846. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66847. plugin: plugin,
  66848. isBinary: false
  66849. };
  66850. }
  66851. else {
  66852. var extensions = plugin.extensions;
  66853. Object.keys(extensions).forEach(function (extension) {
  66854. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66855. plugin: plugin,
  66856. isBinary: extensions[extension].isBinary
  66857. };
  66858. });
  66859. }
  66860. };
  66861. /**
  66862. * Import meshes into a scene
  66863. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66864. * @param rootUrl a string that defines the root url for scene and resources
  66865. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66866. * @param scene the instance of BABYLON.Scene to append to
  66867. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66868. * @param onProgress a callback with a progress event for each file being loaded
  66869. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66870. * @param pluginExtension the extension used to determine the plugin
  66871. * @returns The loaded plugin
  66872. */
  66873. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66874. if (onSuccess === void 0) { onSuccess = null; }
  66875. if (onProgress === void 0) { onProgress = null; }
  66876. if (onError === void 0) { onError = null; }
  66877. if (pluginExtension === void 0) { pluginExtension = null; }
  66878. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66879. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66880. return null;
  66881. }
  66882. var loadingToken = {};
  66883. scene._addPendingData(loadingToken);
  66884. var disposeHandler = function () {
  66885. scene._removePendingData(loadingToken);
  66886. };
  66887. var errorHandler = function (message, exception) {
  66888. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66889. if (onError) {
  66890. onError(scene, errorMessage, exception);
  66891. }
  66892. else {
  66893. BABYLON.Tools.Error(errorMessage);
  66894. // should the exception be thrown?
  66895. }
  66896. disposeHandler();
  66897. };
  66898. var progressHandler = onProgress ? function (event) {
  66899. try {
  66900. onProgress(event);
  66901. }
  66902. catch (e) {
  66903. errorHandler("Error in onProgress callback", e);
  66904. }
  66905. } : undefined;
  66906. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66907. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66908. if (onSuccess) {
  66909. try {
  66910. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66911. }
  66912. catch (e) {
  66913. errorHandler("Error in onSuccess callback", e);
  66914. }
  66915. }
  66916. scene._removePendingData(loadingToken);
  66917. };
  66918. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66919. if (plugin.rewriteRootURL) {
  66920. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66921. }
  66922. if (sceneFilename === "") {
  66923. if (sceneFilename === "") {
  66924. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66925. }
  66926. }
  66927. if (plugin.importMesh) {
  66928. var syncedPlugin = plugin;
  66929. var meshes = new Array();
  66930. var particleSystems = new Array();
  66931. var skeletons = new Array();
  66932. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66933. return;
  66934. }
  66935. scene.loadingPluginName = plugin.name;
  66936. successHandler(meshes, particleSystems, skeletons, []);
  66937. }
  66938. else {
  66939. var asyncedPlugin = plugin;
  66940. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66941. scene.loadingPluginName = plugin.name;
  66942. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66943. }).catch(function (error) {
  66944. errorHandler(error.message, error);
  66945. });
  66946. }
  66947. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66948. };
  66949. /**
  66950. * Import meshes into a scene
  66951. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66952. * @param rootUrl a string that defines the root url for scene and resources
  66953. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66954. * @param scene the instance of BABYLON.Scene to append to
  66955. * @param onProgress a callback with a progress event for each file being loaded
  66956. * @param pluginExtension the extension used to determine the plugin
  66957. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66958. */
  66959. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66960. if (onProgress === void 0) { onProgress = null; }
  66961. if (pluginExtension === void 0) { pluginExtension = null; }
  66962. return new Promise(function (resolve, reject) {
  66963. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66964. resolve({
  66965. meshes: meshes,
  66966. particleSystems: particleSystems,
  66967. skeletons: skeletons,
  66968. animationGroups: animationGroups
  66969. });
  66970. }, onProgress, function (scene, message, exception) {
  66971. reject(exception || new Error(message));
  66972. });
  66973. });
  66974. };
  66975. /**
  66976. * Load a scene
  66977. * @param rootUrl a string that defines the root url for scene and resources
  66978. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66979. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66980. * @param onSuccess a callback with the scene when import succeeds
  66981. * @param onProgress a callback with a progress event for each file being loaded
  66982. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66983. * @param pluginExtension the extension used to determine the plugin
  66984. * @returns The loaded plugin
  66985. */
  66986. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66987. if (onSuccess === void 0) { onSuccess = null; }
  66988. if (onProgress === void 0) { onProgress = null; }
  66989. if (onError === void 0) { onError = null; }
  66990. if (pluginExtension === void 0) { pluginExtension = null; }
  66991. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66992. };
  66993. /**
  66994. * Load a scene
  66995. * @param rootUrl a string that defines the root url for scene and resources
  66996. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66997. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66998. * @param onProgress a callback with a progress event for each file being loaded
  66999. * @param pluginExtension the extension used to determine the plugin
  67000. * @returns The loaded scene
  67001. */
  67002. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67003. if (onProgress === void 0) { onProgress = null; }
  67004. if (pluginExtension === void 0) { pluginExtension = null; }
  67005. return new Promise(function (resolve, reject) {
  67006. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67007. resolve(scene);
  67008. }, onProgress, function (scene, message, exception) {
  67009. reject(exception || new Error(message));
  67010. }, pluginExtension);
  67011. });
  67012. };
  67013. /**
  67014. * Append a scene
  67015. * @param rootUrl a string that defines the root url for scene and resources
  67016. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67017. * @param scene is the instance of BABYLON.Scene to append to
  67018. * @param onSuccess a callback with the scene when import succeeds
  67019. * @param onProgress a callback with a progress event for each file being loaded
  67020. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67021. * @param pluginExtension the extension used to determine the plugin
  67022. * @returns The loaded plugin
  67023. */
  67024. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67025. if (onSuccess === void 0) { onSuccess = null; }
  67026. if (onProgress === void 0) { onProgress = null; }
  67027. if (onError === void 0) { onError = null; }
  67028. if (pluginExtension === void 0) { pluginExtension = null; }
  67029. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67030. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67031. return null;
  67032. }
  67033. if (SceneLoader.ShowLoadingScreen) {
  67034. scene.getEngine().displayLoadingUI();
  67035. }
  67036. var loadingToken = {};
  67037. scene._addPendingData(loadingToken);
  67038. var disposeHandler = function () {
  67039. scene._removePendingData(loadingToken);
  67040. scene.getEngine().hideLoadingUI();
  67041. };
  67042. var errorHandler = function (message, exception) {
  67043. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67044. if (onError) {
  67045. onError(scene, errorMessage, exception);
  67046. }
  67047. else {
  67048. BABYLON.Tools.Error(errorMessage);
  67049. // should the exception be thrown?
  67050. }
  67051. disposeHandler();
  67052. };
  67053. var progressHandler = onProgress ? function (event) {
  67054. try {
  67055. onProgress(event);
  67056. }
  67057. catch (e) {
  67058. errorHandler("Error in onProgress callback", e);
  67059. }
  67060. } : undefined;
  67061. var successHandler = function () {
  67062. if (onSuccess) {
  67063. try {
  67064. onSuccess(scene);
  67065. }
  67066. catch (e) {
  67067. errorHandler("Error in onSuccess callback", e);
  67068. }
  67069. }
  67070. scene._removePendingData(loadingToken);
  67071. };
  67072. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67073. if (sceneFilename === "") {
  67074. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67075. }
  67076. if (plugin.load) {
  67077. var syncedPlugin = plugin;
  67078. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67079. return;
  67080. }
  67081. scene.loadingPluginName = plugin.name;
  67082. successHandler();
  67083. }
  67084. else {
  67085. var asyncedPlugin = plugin;
  67086. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67087. scene.loadingPluginName = plugin.name;
  67088. successHandler();
  67089. }).catch(function (error) {
  67090. errorHandler(error.message, error);
  67091. });
  67092. }
  67093. if (SceneLoader.ShowLoadingScreen) {
  67094. scene.executeWhenReady(function () {
  67095. scene.getEngine().hideLoadingUI();
  67096. });
  67097. }
  67098. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67099. };
  67100. /**
  67101. * Append a scene
  67102. * @param rootUrl a string that defines the root url for scene and resources
  67103. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67104. * @param scene is the instance of BABYLON.Scene to append to
  67105. * @param onProgress a callback with a progress event for each file being loaded
  67106. * @param pluginExtension the extension used to determine the plugin
  67107. * @returns The given scene
  67108. */
  67109. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67110. if (onProgress === void 0) { onProgress = null; }
  67111. if (pluginExtension === void 0) { pluginExtension = null; }
  67112. return new Promise(function (resolve, reject) {
  67113. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67114. resolve(scene);
  67115. }, onProgress, function (scene, message, exception) {
  67116. reject(exception || new Error(message));
  67117. }, pluginExtension);
  67118. });
  67119. };
  67120. /**
  67121. * Load a scene into an asset container
  67122. * @param rootUrl a string that defines the root url for scene and resources
  67123. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67124. * @param scene is the instance of BABYLON.Scene to append to
  67125. * @param onSuccess a callback with the scene when import succeeds
  67126. * @param onProgress a callback with a progress event for each file being loaded
  67127. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67128. * @param pluginExtension the extension used to determine the plugin
  67129. * @returns The loaded plugin
  67130. */
  67131. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67132. if (onSuccess === void 0) { onSuccess = null; }
  67133. if (onProgress === void 0) { onProgress = null; }
  67134. if (onError === void 0) { onError = null; }
  67135. if (pluginExtension === void 0) { pluginExtension = null; }
  67136. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67137. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67138. return null;
  67139. }
  67140. var loadingToken = {};
  67141. scene._addPendingData(loadingToken);
  67142. var disposeHandler = function () {
  67143. scene._removePendingData(loadingToken);
  67144. };
  67145. var errorHandler = function (message, exception) {
  67146. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67147. if (onError) {
  67148. onError(scene, errorMessage, exception);
  67149. }
  67150. else {
  67151. BABYLON.Tools.Error(errorMessage);
  67152. // should the exception be thrown?
  67153. }
  67154. disposeHandler();
  67155. };
  67156. var progressHandler = onProgress ? function (event) {
  67157. try {
  67158. onProgress(event);
  67159. }
  67160. catch (e) {
  67161. errorHandler("Error in onProgress callback", e);
  67162. }
  67163. } : undefined;
  67164. var successHandler = function (assets) {
  67165. if (onSuccess) {
  67166. try {
  67167. onSuccess(assets);
  67168. }
  67169. catch (e) {
  67170. errorHandler("Error in onSuccess callback", e);
  67171. }
  67172. }
  67173. scene._removePendingData(loadingToken);
  67174. };
  67175. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67176. if (plugin.loadAssetContainer) {
  67177. var syncedPlugin = plugin;
  67178. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67179. if (!assetContainer) {
  67180. return;
  67181. }
  67182. scene.loadingPluginName = plugin.name;
  67183. successHandler(assetContainer);
  67184. }
  67185. else if (plugin.loadAssetContainerAsync) {
  67186. var asyncedPlugin = plugin;
  67187. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67188. scene.loadingPluginName = plugin.name;
  67189. successHandler(assetContainer);
  67190. }).catch(function (error) {
  67191. errorHandler(error.message, error);
  67192. });
  67193. }
  67194. else {
  67195. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67196. }
  67197. if (SceneLoader.ShowLoadingScreen) {
  67198. scene.executeWhenReady(function () {
  67199. scene.getEngine().hideLoadingUI();
  67200. });
  67201. }
  67202. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67203. };
  67204. /**
  67205. * Load a scene into an asset container
  67206. * @param rootUrl a string that defines the root url for scene and resources
  67207. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67208. * @param scene is the instance of BABYLON.Scene to append to
  67209. * @param onProgress a callback with a progress event for each file being loaded
  67210. * @param pluginExtension the extension used to determine the plugin
  67211. * @returns The loaded asset container
  67212. */
  67213. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67214. if (onProgress === void 0) { onProgress = null; }
  67215. if (pluginExtension === void 0) { pluginExtension = null; }
  67216. return new Promise(function (resolve, reject) {
  67217. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67218. resolve(assetContainer);
  67219. }, onProgress, function (scene, message, exception) {
  67220. reject(exception || new Error(message));
  67221. }, pluginExtension);
  67222. });
  67223. };
  67224. // Flags
  67225. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67226. SceneLoader._ShowLoadingScreen = true;
  67227. SceneLoader._CleanBoneMatrixWeights = false;
  67228. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67229. // Members
  67230. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67231. SceneLoader._registeredPlugins = {};
  67232. return SceneLoader;
  67233. }());
  67234. BABYLON.SceneLoader = SceneLoader;
  67235. ;
  67236. })(BABYLON || (BABYLON = {}));
  67237. //# sourceMappingURL=babylon.sceneLoader.js.map
  67238. var BABYLON;
  67239. (function (BABYLON) {
  67240. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67241. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67242. var parsedMaterial = parsedData.materials[index];
  67243. if (parsedMaterial.id === id) {
  67244. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67245. }
  67246. }
  67247. return null;
  67248. };
  67249. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67250. for (var i in names) {
  67251. if (mesh.name === names[i]) {
  67252. hierarchyIds.push(mesh.id);
  67253. return true;
  67254. }
  67255. }
  67256. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67257. hierarchyIds.push(mesh.id);
  67258. return true;
  67259. }
  67260. return false;
  67261. };
  67262. var logOperation = function (operation, producer) {
  67263. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67264. };
  67265. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67266. if (addToScene === void 0) { addToScene = false; }
  67267. var container = new BABYLON.AssetContainer(scene);
  67268. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67269. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67270. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67271. // and avoid problems with multiple concurrent .babylon loads.
  67272. var log = "importScene has failed JSON parse";
  67273. try {
  67274. var parsedData = JSON.parse(data);
  67275. log = "";
  67276. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67277. var index;
  67278. var cache;
  67279. // Lights
  67280. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67281. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67282. var parsedLight = parsedData.lights[index];
  67283. var light = BABYLON.Light.Parse(parsedLight, scene);
  67284. if (light) {
  67285. container.lights.push(light);
  67286. log += (index === 0 ? "\n\tLights:" : "");
  67287. log += "\n\t\t" + light.toString(fullDetails);
  67288. }
  67289. }
  67290. }
  67291. // Animations
  67292. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67293. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67294. var parsedAnimation = parsedData.animations[index];
  67295. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67296. scene.animations.push(animation);
  67297. container.animations.push(animation);
  67298. log += (index === 0 ? "\n\tAnimations:" : "");
  67299. log += "\n\t\t" + animation.toString(fullDetails);
  67300. }
  67301. }
  67302. // Materials
  67303. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67304. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67305. var parsedMaterial = parsedData.materials[index];
  67306. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67307. container.materials.push(mat);
  67308. log += (index === 0 ? "\n\tMaterials:" : "");
  67309. log += "\n\t\t" + mat.toString(fullDetails);
  67310. }
  67311. }
  67312. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67313. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67314. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67315. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67316. container.multiMaterials.push(mmat);
  67317. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67318. log += "\n\t\t" + mmat.toString(fullDetails);
  67319. }
  67320. }
  67321. // Morph targets
  67322. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67323. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67324. var managerData = _a[_i];
  67325. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67326. }
  67327. }
  67328. // Skeletons
  67329. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67330. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67331. var parsedSkeleton = parsedData.skeletons[index];
  67332. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67333. container.skeletons.push(skeleton);
  67334. log += (index === 0 ? "\n\tSkeletons:" : "");
  67335. log += "\n\t\t" + skeleton.toString(fullDetails);
  67336. }
  67337. }
  67338. // Geometries
  67339. var geometries = parsedData.geometries;
  67340. if (geometries !== undefined && geometries !== null) {
  67341. var addedGeometry = new Array();
  67342. // Boxes
  67343. var boxes = geometries.boxes;
  67344. if (boxes !== undefined && boxes !== null) {
  67345. for (index = 0, cache = boxes.length; index < cache; index++) {
  67346. var parsedBox = boxes[index];
  67347. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67348. }
  67349. }
  67350. // Spheres
  67351. var spheres = geometries.spheres;
  67352. if (spheres !== undefined && spheres !== null) {
  67353. for (index = 0, cache = spheres.length; index < cache; index++) {
  67354. var parsedSphere = spheres[index];
  67355. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67356. }
  67357. }
  67358. // Cylinders
  67359. var cylinders = geometries.cylinders;
  67360. if (cylinders !== undefined && cylinders !== null) {
  67361. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67362. var parsedCylinder = cylinders[index];
  67363. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67364. }
  67365. }
  67366. // Toruses
  67367. var toruses = geometries.toruses;
  67368. if (toruses !== undefined && toruses !== null) {
  67369. for (index = 0, cache = toruses.length; index < cache; index++) {
  67370. var parsedTorus = toruses[index];
  67371. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67372. }
  67373. }
  67374. // Grounds
  67375. var grounds = geometries.grounds;
  67376. if (grounds !== undefined && grounds !== null) {
  67377. for (index = 0, cache = grounds.length; index < cache; index++) {
  67378. var parsedGround = grounds[index];
  67379. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67380. }
  67381. }
  67382. // Planes
  67383. var planes = geometries.planes;
  67384. if (planes !== undefined && planes !== null) {
  67385. for (index = 0, cache = planes.length; index < cache; index++) {
  67386. var parsedPlane = planes[index];
  67387. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67388. }
  67389. }
  67390. // TorusKnots
  67391. var torusKnots = geometries.torusKnots;
  67392. if (torusKnots !== undefined && torusKnots !== null) {
  67393. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67394. var parsedTorusKnot = torusKnots[index];
  67395. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67396. }
  67397. }
  67398. // VertexData
  67399. var vertexData = geometries.vertexData;
  67400. if (vertexData !== undefined && vertexData !== null) {
  67401. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67402. var parsedVertexData = vertexData[index];
  67403. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67404. }
  67405. }
  67406. addedGeometry.forEach(function (g) {
  67407. if (g) {
  67408. container.geometries.push(g);
  67409. }
  67410. });
  67411. }
  67412. // Transform nodes
  67413. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67414. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67415. var parsedTransformNode = parsedData.transformNodes[index];
  67416. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67417. container.transformNodes.push(node);
  67418. }
  67419. }
  67420. // Meshes
  67421. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67422. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67423. var parsedMesh = parsedData.meshes[index];
  67424. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67425. container.meshes.push(mesh);
  67426. log += (index === 0 ? "\n\tMeshes:" : "");
  67427. log += "\n\t\t" + mesh.toString(fullDetails);
  67428. }
  67429. }
  67430. // Cameras
  67431. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67432. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67433. var parsedCamera = parsedData.cameras[index];
  67434. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67435. container.cameras.push(camera);
  67436. log += (index === 0 ? "\n\tCameras:" : "");
  67437. log += "\n\t\t" + camera.toString(fullDetails);
  67438. }
  67439. }
  67440. // Browsing all the graph to connect the dots
  67441. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67442. var camera = scene.cameras[index];
  67443. if (camera._waitingParentId) {
  67444. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67445. camera._waitingParentId = null;
  67446. }
  67447. }
  67448. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67449. var light_1 = scene.lights[index];
  67450. if (light_1 && light_1._waitingParentId) {
  67451. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67452. light_1._waitingParentId = null;
  67453. }
  67454. }
  67455. // Sounds
  67456. // TODO: add sound
  67457. var loadedSounds = [];
  67458. var loadedSound;
  67459. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67460. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67461. var parsedSound = parsedData.sounds[index];
  67462. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67463. if (!parsedSound.url)
  67464. parsedSound.url = parsedSound.name;
  67465. if (!loadedSounds[parsedSound.url]) {
  67466. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67467. loadedSounds[parsedSound.url] = loadedSound;
  67468. container.sounds.push(loadedSound);
  67469. }
  67470. else {
  67471. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67472. }
  67473. }
  67474. else {
  67475. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67476. }
  67477. }
  67478. }
  67479. loadedSounds = [];
  67480. // Connect parents & children and parse actions
  67481. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67482. var transformNode = scene.transformNodes[index];
  67483. if (transformNode._waitingParentId) {
  67484. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67485. transformNode._waitingParentId = null;
  67486. }
  67487. }
  67488. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67489. var mesh = scene.meshes[index];
  67490. if (mesh._waitingParentId) {
  67491. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67492. mesh._waitingParentId = null;
  67493. }
  67494. if (mesh._waitingActions) {
  67495. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67496. mesh._waitingActions = null;
  67497. }
  67498. }
  67499. // freeze world matrix application
  67500. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67501. var currentMesh = scene.meshes[index];
  67502. if (currentMesh._waitingFreezeWorldMatrix) {
  67503. currentMesh.freezeWorldMatrix();
  67504. currentMesh._waitingFreezeWorldMatrix = null;
  67505. }
  67506. else {
  67507. currentMesh.computeWorldMatrix(true);
  67508. }
  67509. }
  67510. // Particles Systems
  67511. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67512. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67513. var parsedParticleSystem = parsedData.particleSystems[index];
  67514. if (parsedParticleSystem.activeParticleCount) {
  67515. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67516. container.particleSystems.push(ps);
  67517. }
  67518. else {
  67519. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67520. container.particleSystems.push(ps);
  67521. }
  67522. }
  67523. }
  67524. // Lens flares
  67525. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67526. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67527. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67528. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67529. container.lensFlareSystems.push(lf);
  67530. }
  67531. }
  67532. // Shadows
  67533. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67534. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67535. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67536. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67537. container.shadowGenerators.push(sg);
  67538. }
  67539. }
  67540. // Lights exclusions / inclusions
  67541. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67542. var light_2 = scene.lights[index];
  67543. // Excluded check
  67544. if (light_2._excludedMeshesIds.length > 0) {
  67545. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67546. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67547. if (excludedMesh) {
  67548. light_2.excludedMeshes.push(excludedMesh);
  67549. }
  67550. }
  67551. light_2._excludedMeshesIds = [];
  67552. }
  67553. // Included check
  67554. if (light_2._includedOnlyMeshesIds.length > 0) {
  67555. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67556. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67557. if (includedOnlyMesh) {
  67558. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67559. }
  67560. }
  67561. light_2._includedOnlyMeshesIds = [];
  67562. }
  67563. }
  67564. // Effect layers
  67565. if (parsedData.effectLayers) {
  67566. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67567. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67568. container.effectLayers.push(effectLayer);
  67569. }
  67570. }
  67571. // Actions (scene)
  67572. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67573. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67574. }
  67575. if (!addToScene) {
  67576. container.removeAllFromScene();
  67577. }
  67578. }
  67579. catch (err) {
  67580. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67581. if (onError) {
  67582. onError(msg, err);
  67583. }
  67584. else {
  67585. BABYLON.Tools.Log(msg);
  67586. throw err;
  67587. }
  67588. }
  67589. finally {
  67590. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67591. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67592. }
  67593. }
  67594. return container;
  67595. };
  67596. BABYLON.SceneLoader.RegisterPlugin({
  67597. name: "babylon.js",
  67598. extensions: ".babylon",
  67599. canDirectLoad: function (data) {
  67600. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67601. return true;
  67602. }
  67603. return false;
  67604. },
  67605. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67606. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67607. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67608. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67609. // and avoid problems with multiple concurrent .babylon loads.
  67610. var log = "importMesh has failed JSON parse";
  67611. try {
  67612. var parsedData = JSON.parse(data);
  67613. log = "";
  67614. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67615. if (!meshesNames) {
  67616. meshesNames = null;
  67617. }
  67618. else if (!Array.isArray(meshesNames)) {
  67619. meshesNames = [meshesNames];
  67620. }
  67621. var hierarchyIds = new Array();
  67622. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67623. var loadedSkeletonsIds = [];
  67624. var loadedMaterialsIds = [];
  67625. var index;
  67626. var cache;
  67627. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67628. var parsedMesh = parsedData.meshes[index];
  67629. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67630. if (meshesNames !== null) {
  67631. // Remove found mesh name from list.
  67632. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67633. }
  67634. //Geometry?
  67635. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67636. //does the file contain geometries?
  67637. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67638. //find the correct geometry and add it to the scene
  67639. var found = false;
  67640. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67641. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67642. return;
  67643. }
  67644. else {
  67645. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67646. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67647. switch (geometryType) {
  67648. case "boxes":
  67649. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67650. break;
  67651. case "spheres":
  67652. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67653. break;
  67654. case "cylinders":
  67655. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67656. break;
  67657. case "toruses":
  67658. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67659. break;
  67660. case "grounds":
  67661. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67662. break;
  67663. case "planes":
  67664. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67665. break;
  67666. case "torusKnots":
  67667. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67668. break;
  67669. case "vertexData":
  67670. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67671. break;
  67672. }
  67673. found = true;
  67674. }
  67675. });
  67676. }
  67677. });
  67678. if (found === false) {
  67679. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67680. }
  67681. }
  67682. }
  67683. // Material ?
  67684. if (parsedMesh.materialId) {
  67685. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67686. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67687. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67688. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67689. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67690. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67691. var subMatId = parsedMultiMaterial.materials[matIndex];
  67692. loadedMaterialsIds.push(subMatId);
  67693. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67694. if (mat) {
  67695. log += "\n\tMaterial " + mat.toString(fullDetails);
  67696. }
  67697. }
  67698. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67699. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67700. if (mmat) {
  67701. materialFound = true;
  67702. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67703. }
  67704. break;
  67705. }
  67706. }
  67707. }
  67708. if (materialFound === false) {
  67709. loadedMaterialsIds.push(parsedMesh.materialId);
  67710. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67711. if (!mat) {
  67712. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67713. }
  67714. else {
  67715. log += "\n\tMaterial " + mat.toString(fullDetails);
  67716. }
  67717. }
  67718. }
  67719. // Skeleton ?
  67720. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67721. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67722. if (skeletonAlreadyLoaded === false) {
  67723. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67724. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67725. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67726. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67727. skeletons.push(skeleton);
  67728. loadedSkeletonsIds.push(parsedSkeleton.id);
  67729. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67730. }
  67731. }
  67732. }
  67733. }
  67734. // Morph targets ?
  67735. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67736. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67737. var managerData = _a[_i];
  67738. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67739. }
  67740. }
  67741. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67742. meshes.push(mesh);
  67743. log += "\n\tMesh " + mesh.toString(fullDetails);
  67744. }
  67745. }
  67746. // Connecting parents
  67747. var currentMesh;
  67748. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67749. currentMesh = scene.meshes[index];
  67750. if (currentMesh._waitingParentId) {
  67751. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67752. currentMesh._waitingParentId = null;
  67753. }
  67754. }
  67755. // freeze and compute world matrix application
  67756. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67757. currentMesh = scene.meshes[index];
  67758. if (currentMesh._waitingFreezeWorldMatrix) {
  67759. currentMesh.freezeWorldMatrix();
  67760. currentMesh._waitingFreezeWorldMatrix = null;
  67761. }
  67762. else {
  67763. currentMesh.computeWorldMatrix(true);
  67764. }
  67765. }
  67766. }
  67767. // Particles
  67768. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67769. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67770. var parsedParticleSystem = parsedData.particleSystems[index];
  67771. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67772. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67773. }
  67774. }
  67775. }
  67776. return true;
  67777. }
  67778. catch (err) {
  67779. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67780. if (onError) {
  67781. onError(msg, err);
  67782. }
  67783. else {
  67784. BABYLON.Tools.Log(msg);
  67785. throw err;
  67786. }
  67787. }
  67788. finally {
  67789. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67790. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67791. }
  67792. }
  67793. return false;
  67794. },
  67795. load: function (scene, data, rootUrl, onError) {
  67796. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67797. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67798. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67799. // and avoid problems with multiple concurrent .babylon loads.
  67800. var log = "importScene has failed JSON parse";
  67801. try {
  67802. var parsedData = JSON.parse(data);
  67803. log = "";
  67804. // Scene
  67805. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67806. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67807. }
  67808. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67809. scene.autoClear = parsedData.autoClear;
  67810. }
  67811. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67812. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67813. }
  67814. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67815. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67816. }
  67817. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67818. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67819. }
  67820. // Fog
  67821. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67822. scene.fogMode = parsedData.fogMode;
  67823. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67824. scene.fogStart = parsedData.fogStart;
  67825. scene.fogEnd = parsedData.fogEnd;
  67826. scene.fogDensity = parsedData.fogDensity;
  67827. log += "\tFog mode for scene: ";
  67828. switch (scene.fogMode) {
  67829. // getters not compiling, so using hardcoded
  67830. case 1:
  67831. log += "exp\n";
  67832. break;
  67833. case 2:
  67834. log += "exp2\n";
  67835. break;
  67836. case 3:
  67837. log += "linear\n";
  67838. break;
  67839. }
  67840. }
  67841. //Physics
  67842. if (parsedData.physicsEnabled) {
  67843. var physicsPlugin;
  67844. if (parsedData.physicsEngine === "cannon") {
  67845. physicsPlugin = new BABYLON.CannonJSPlugin();
  67846. }
  67847. else if (parsedData.physicsEngine === "oimo") {
  67848. physicsPlugin = new BABYLON.OimoJSPlugin();
  67849. }
  67850. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67851. //else - default engine, which is currently oimo
  67852. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67853. scene.enablePhysics(physicsGravity, physicsPlugin);
  67854. }
  67855. // Metadata
  67856. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67857. scene.metadata = parsedData.metadata;
  67858. }
  67859. //collisions, if defined. otherwise, default is true
  67860. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67861. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67862. }
  67863. scene.workerCollisions = !!parsedData.workerCollisions;
  67864. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67865. if (!container) {
  67866. return false;
  67867. }
  67868. if (parsedData.autoAnimate) {
  67869. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67870. }
  67871. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67872. scene.setActiveCameraByID(parsedData.activeCameraID);
  67873. }
  67874. // Environment texture
  67875. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67876. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67877. if (parsedData.createDefaultSkybox === true) {
  67878. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67879. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67880. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67881. }
  67882. }
  67883. // Finish
  67884. return true;
  67885. }
  67886. catch (err) {
  67887. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67888. if (onError) {
  67889. onError(msg, err);
  67890. }
  67891. else {
  67892. BABYLON.Tools.Log(msg);
  67893. throw err;
  67894. }
  67895. }
  67896. finally {
  67897. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67898. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67899. }
  67900. }
  67901. return false;
  67902. },
  67903. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67904. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67905. return container;
  67906. }
  67907. });
  67908. })(BABYLON || (BABYLON = {}));
  67909. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67910. var BABYLON;
  67911. (function (BABYLON) {
  67912. var FilesInput = /** @class */ (function () {
  67913. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67914. this.onProcessFileCallback = function () { return true; };
  67915. this._engine = engine;
  67916. this._currentScene = scene;
  67917. this._sceneLoadedCallback = sceneLoadedCallback;
  67918. this._progressCallback = progressCallback;
  67919. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67920. this._textureLoadingCallback = textureLoadingCallback;
  67921. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67922. this._onReloadCallback = onReloadCallback;
  67923. this._errorCallback = errorCallback;
  67924. }
  67925. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67926. var _this = this;
  67927. if (elementToMonitor) {
  67928. this._elementToMonitor = elementToMonitor;
  67929. this._dragEnterHandler = function (e) { _this.drag(e); };
  67930. this._dragOverHandler = function (e) { _this.drag(e); };
  67931. this._dropHandler = function (e) { _this.drop(e); };
  67932. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67933. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67934. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67935. }
  67936. };
  67937. FilesInput.prototype.dispose = function () {
  67938. if (!this._elementToMonitor) {
  67939. return;
  67940. }
  67941. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67942. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67943. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67944. };
  67945. FilesInput.prototype.renderFunction = function () {
  67946. if (this._additionalRenderLoopLogicCallback) {
  67947. this._additionalRenderLoopLogicCallback();
  67948. }
  67949. if (this._currentScene) {
  67950. if (this._textureLoadingCallback) {
  67951. var remaining = this._currentScene.getWaitingItemsCount();
  67952. if (remaining > 0) {
  67953. this._textureLoadingCallback(remaining);
  67954. }
  67955. }
  67956. this._currentScene.render();
  67957. }
  67958. };
  67959. FilesInput.prototype.drag = function (e) {
  67960. e.stopPropagation();
  67961. e.preventDefault();
  67962. };
  67963. FilesInput.prototype.drop = function (eventDrop) {
  67964. eventDrop.stopPropagation();
  67965. eventDrop.preventDefault();
  67966. this.loadFiles(eventDrop);
  67967. };
  67968. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67969. var _this = this;
  67970. var reader = folder.createReader();
  67971. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67972. reader.readEntries(function (entries) {
  67973. remaining.count += entries.length;
  67974. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67975. var entry = entries_1[_i];
  67976. if (entry.isFile) {
  67977. entry.file(function (file) {
  67978. file.correctName = relativePath + file.name;
  67979. files.push(file);
  67980. if (--remaining.count === 0) {
  67981. callback();
  67982. }
  67983. });
  67984. }
  67985. else if (entry.isDirectory) {
  67986. _this._traverseFolder(entry, files, remaining, callback);
  67987. }
  67988. }
  67989. if (--remaining.count) {
  67990. callback();
  67991. }
  67992. });
  67993. };
  67994. FilesInput.prototype._processFiles = function (files) {
  67995. for (var i = 0; i < files.length; i++) {
  67996. var name = files[i].correctName.toLowerCase();
  67997. var extension = name.split('.').pop();
  67998. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67999. continue;
  68000. }
  68001. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68002. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68003. this._sceneFileToLoad = files[i];
  68004. }
  68005. else {
  68006. FilesInput.FilesToLoad[name] = files[i];
  68007. }
  68008. }
  68009. };
  68010. FilesInput.prototype.loadFiles = function (event) {
  68011. var _this = this;
  68012. if (this._startingProcessingFilesCallback)
  68013. this._startingProcessingFilesCallback();
  68014. // Handling data transfer via drag'n'drop
  68015. if (event && event.dataTransfer && event.dataTransfer.files) {
  68016. this._filesToLoad = event.dataTransfer.files;
  68017. }
  68018. // Handling files from input files
  68019. if (event && event.target && event.target.files) {
  68020. this._filesToLoad = event.target.files;
  68021. }
  68022. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68023. var files_1 = new Array();
  68024. var folders = [];
  68025. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68026. for (var i = 0; i < this._filesToLoad.length; i++) {
  68027. var fileToLoad = this._filesToLoad[i];
  68028. var name_1 = fileToLoad.name.toLowerCase();
  68029. var entry = void 0;
  68030. fileToLoad.correctName = name_1;
  68031. if (items) {
  68032. var item = items[i];
  68033. if (item.getAsEntry) {
  68034. entry = item.getAsEntry();
  68035. }
  68036. else if (item.webkitGetAsEntry) {
  68037. entry = item.webkitGetAsEntry();
  68038. }
  68039. }
  68040. if (!entry) {
  68041. files_1.push(fileToLoad);
  68042. }
  68043. else {
  68044. if (entry.isDirectory) {
  68045. folders.push(entry);
  68046. }
  68047. else {
  68048. files_1.push(fileToLoad);
  68049. }
  68050. }
  68051. }
  68052. if (folders.length === 0) {
  68053. this._processFiles(files_1);
  68054. this._processReload();
  68055. }
  68056. else {
  68057. var remaining = { count: folders.length };
  68058. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68059. var folder = folders_1[_i];
  68060. this._traverseFolder(folder, files_1, remaining, function () {
  68061. _this._processFiles(files_1);
  68062. if (remaining.count === 0) {
  68063. _this._processReload();
  68064. }
  68065. });
  68066. }
  68067. }
  68068. }
  68069. };
  68070. FilesInput.prototype._processReload = function () {
  68071. if (this._onReloadCallback) {
  68072. this._onReloadCallback(this._sceneFileToLoad);
  68073. }
  68074. else {
  68075. this.reload();
  68076. }
  68077. };
  68078. FilesInput.prototype.reload = function () {
  68079. var _this = this;
  68080. // If a scene file has been provided
  68081. if (this._sceneFileToLoad) {
  68082. if (this._currentScene) {
  68083. if (BABYLON.Tools.errorsCount > 0) {
  68084. BABYLON.Tools.ClearLogCache();
  68085. }
  68086. this._engine.stopRenderLoop();
  68087. this._currentScene.dispose();
  68088. }
  68089. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68090. if (_this._progressCallback) {
  68091. _this._progressCallback(progress);
  68092. }
  68093. }).then(function (scene) {
  68094. _this._currentScene = scene;
  68095. if (_this._sceneLoadedCallback) {
  68096. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68097. }
  68098. // Wait for textures and shaders to be ready
  68099. _this._currentScene.executeWhenReady(function () {
  68100. _this._engine.runRenderLoop(function () {
  68101. _this.renderFunction();
  68102. });
  68103. });
  68104. }).catch(function (error) {
  68105. if (_this._errorCallback) {
  68106. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68107. }
  68108. });
  68109. }
  68110. else {
  68111. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68112. }
  68113. };
  68114. FilesInput.FilesToLoad = {};
  68115. return FilesInput;
  68116. }());
  68117. BABYLON.FilesInput = FilesInput;
  68118. })(BABYLON || (BABYLON = {}));
  68119. //# sourceMappingURL=babylon.filesInput.js.map
  68120. var BABYLON;
  68121. (function (BABYLON) {
  68122. /**
  68123. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68124. * The underlying implementation relies on an associative array to ensure the best performances.
  68125. * The value can be anything including 'null' but except 'undefined'
  68126. */
  68127. var StringDictionary = /** @class */ (function () {
  68128. function StringDictionary() {
  68129. this._count = 0;
  68130. this._data = {};
  68131. }
  68132. /**
  68133. * This will clear this dictionary and copy the content from the 'source' one.
  68134. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68135. * @param source the dictionary to take the content from and copy to this dictionary
  68136. */
  68137. StringDictionary.prototype.copyFrom = function (source) {
  68138. var _this = this;
  68139. this.clear();
  68140. source.forEach(function (t, v) { return _this.add(t, v); });
  68141. };
  68142. /**
  68143. * Get a value based from its key
  68144. * @param key the given key to get the matching value from
  68145. * @return the value if found, otherwise undefined is returned
  68146. */
  68147. StringDictionary.prototype.get = function (key) {
  68148. var val = this._data[key];
  68149. if (val !== undefined) {
  68150. return val;
  68151. }
  68152. return undefined;
  68153. };
  68154. /**
  68155. * Get a value from its key or add it if it doesn't exist.
  68156. * This method will ensure you that a given key/data will be present in the dictionary.
  68157. * @param key the given key to get the matching value from
  68158. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68159. * The factory will only be invoked if there's no data for the given key.
  68160. * @return the value corresponding to the key.
  68161. */
  68162. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68163. var val = this.get(key);
  68164. if (val !== undefined) {
  68165. return val;
  68166. }
  68167. val = factory(key);
  68168. if (val) {
  68169. this.add(key, val);
  68170. }
  68171. return val;
  68172. };
  68173. /**
  68174. * Get a value from its key if present in the dictionary otherwise add it
  68175. * @param key the key to get the value from
  68176. * @param val if there's no such key/value pair in the dictionary add it with this value
  68177. * @return the value corresponding to the key
  68178. */
  68179. StringDictionary.prototype.getOrAdd = function (key, val) {
  68180. var curVal = this.get(key);
  68181. if (curVal !== undefined) {
  68182. return curVal;
  68183. }
  68184. this.add(key, val);
  68185. return val;
  68186. };
  68187. /**
  68188. * Check if there's a given key in the dictionary
  68189. * @param key the key to check for
  68190. * @return true if the key is present, false otherwise
  68191. */
  68192. StringDictionary.prototype.contains = function (key) {
  68193. return this._data[key] !== undefined;
  68194. };
  68195. /**
  68196. * Add a new key and its corresponding value
  68197. * @param key the key to add
  68198. * @param value the value corresponding to the key
  68199. * @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
  68200. */
  68201. StringDictionary.prototype.add = function (key, value) {
  68202. if (this._data[key] !== undefined) {
  68203. return false;
  68204. }
  68205. this._data[key] = value;
  68206. ++this._count;
  68207. return true;
  68208. };
  68209. StringDictionary.prototype.set = function (key, value) {
  68210. if (this._data[key] === undefined) {
  68211. return false;
  68212. }
  68213. this._data[key] = value;
  68214. return true;
  68215. };
  68216. /**
  68217. * Get the element of the given key and remove it from the dictionary
  68218. * @param key
  68219. */
  68220. StringDictionary.prototype.getAndRemove = function (key) {
  68221. var val = this.get(key);
  68222. if (val !== undefined) {
  68223. delete this._data[key];
  68224. --this._count;
  68225. return val;
  68226. }
  68227. return null;
  68228. };
  68229. /**
  68230. * Remove a key/value from the dictionary.
  68231. * @param key the key to remove
  68232. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68233. */
  68234. StringDictionary.prototype.remove = function (key) {
  68235. if (this.contains(key)) {
  68236. delete this._data[key];
  68237. --this._count;
  68238. return true;
  68239. }
  68240. return false;
  68241. };
  68242. /**
  68243. * Clear the whole content of the dictionary
  68244. */
  68245. StringDictionary.prototype.clear = function () {
  68246. this._data = {};
  68247. this._count = 0;
  68248. };
  68249. Object.defineProperty(StringDictionary.prototype, "count", {
  68250. get: function () {
  68251. return this._count;
  68252. },
  68253. enumerable: true,
  68254. configurable: true
  68255. });
  68256. /**
  68257. * Execute a callback on each key/val of the dictionary.
  68258. * Note that you can remove any element in this dictionary in the callback implementation
  68259. * @param callback the callback to execute on a given key/value pair
  68260. */
  68261. StringDictionary.prototype.forEach = function (callback) {
  68262. for (var cur in this._data) {
  68263. var val = this._data[cur];
  68264. callback(cur, val);
  68265. }
  68266. };
  68267. /**
  68268. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68269. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68270. * Note that you can remove any element in this dictionary in the callback implementation
  68271. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68272. */
  68273. StringDictionary.prototype.first = function (callback) {
  68274. for (var cur in this._data) {
  68275. var val = this._data[cur];
  68276. var res = callback(cur, val);
  68277. if (res) {
  68278. return res;
  68279. }
  68280. }
  68281. return null;
  68282. };
  68283. return StringDictionary;
  68284. }());
  68285. BABYLON.StringDictionary = StringDictionary;
  68286. })(BABYLON || (BABYLON = {}));
  68287. //# sourceMappingURL=babylon.stringDictionary.js.map
  68288. var BABYLON;
  68289. (function (BABYLON) {
  68290. var Tags = /** @class */ (function () {
  68291. function Tags() {
  68292. }
  68293. Tags.EnableFor = function (obj) {
  68294. obj._tags = obj._tags || {};
  68295. obj.hasTags = function () {
  68296. return Tags.HasTags(obj);
  68297. };
  68298. obj.addTags = function (tagsString) {
  68299. return Tags.AddTagsTo(obj, tagsString);
  68300. };
  68301. obj.removeTags = function (tagsString) {
  68302. return Tags.RemoveTagsFrom(obj, tagsString);
  68303. };
  68304. obj.matchesTagsQuery = function (tagsQuery) {
  68305. return Tags.MatchesQuery(obj, tagsQuery);
  68306. };
  68307. };
  68308. Tags.DisableFor = function (obj) {
  68309. delete obj._tags;
  68310. delete obj.hasTags;
  68311. delete obj.addTags;
  68312. delete obj.removeTags;
  68313. delete obj.matchesTagsQuery;
  68314. };
  68315. Tags.HasTags = function (obj) {
  68316. if (!obj._tags) {
  68317. return false;
  68318. }
  68319. return !BABYLON.Tools.IsEmpty(obj._tags);
  68320. };
  68321. Tags.GetTags = function (obj, asString) {
  68322. if (asString === void 0) { asString = true; }
  68323. if (!obj._tags) {
  68324. return null;
  68325. }
  68326. if (asString) {
  68327. var tagsArray = [];
  68328. for (var tag in obj._tags) {
  68329. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68330. tagsArray.push(tag);
  68331. }
  68332. }
  68333. return tagsArray.join(" ");
  68334. }
  68335. else {
  68336. return obj._tags;
  68337. }
  68338. };
  68339. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68340. // a tag cannot start with '||', '&&', and '!'
  68341. // it cannot contain whitespaces
  68342. Tags.AddTagsTo = function (obj, tagsString) {
  68343. if (!tagsString) {
  68344. return;
  68345. }
  68346. if (typeof tagsString !== "string") {
  68347. return;
  68348. }
  68349. var tags = tagsString.split(" ");
  68350. tags.forEach(function (tag, index, array) {
  68351. Tags._AddTagTo(obj, tag);
  68352. });
  68353. };
  68354. Tags._AddTagTo = function (obj, tag) {
  68355. tag = tag.trim();
  68356. if (tag === "" || tag === "true" || tag === "false") {
  68357. return;
  68358. }
  68359. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68360. return;
  68361. }
  68362. Tags.EnableFor(obj);
  68363. obj._tags[tag] = true;
  68364. };
  68365. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68366. if (!Tags.HasTags(obj)) {
  68367. return;
  68368. }
  68369. var tags = tagsString.split(" ");
  68370. for (var t in tags) {
  68371. Tags._RemoveTagFrom(obj, tags[t]);
  68372. }
  68373. };
  68374. Tags._RemoveTagFrom = function (obj, tag) {
  68375. delete obj._tags[tag];
  68376. };
  68377. Tags.MatchesQuery = function (obj, tagsQuery) {
  68378. if (tagsQuery === undefined) {
  68379. return true;
  68380. }
  68381. if (tagsQuery === "") {
  68382. return Tags.HasTags(obj);
  68383. }
  68384. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68385. };
  68386. return Tags;
  68387. }());
  68388. BABYLON.Tags = Tags;
  68389. })(BABYLON || (BABYLON = {}));
  68390. //# sourceMappingURL=babylon.tags.js.map
  68391. var BABYLON;
  68392. (function (BABYLON) {
  68393. /**
  68394. * Class used to evalaute queries containing `and` and `or` operators
  68395. */
  68396. var AndOrNotEvaluator = /** @class */ (function () {
  68397. function AndOrNotEvaluator() {
  68398. }
  68399. /**
  68400. * Evaluate a query
  68401. * @param query defines the query to evaluate
  68402. * @param evaluateCallback defines the callback used to filter result
  68403. * @returns true if the query matches
  68404. */
  68405. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68406. if (!query.match(/\([^\(\)]*\)/g)) {
  68407. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68408. }
  68409. else {
  68410. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68411. // remove parenthesis
  68412. r = r.slice(1, r.length - 1);
  68413. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68414. });
  68415. }
  68416. if (query === "true") {
  68417. return true;
  68418. }
  68419. if (query === "false") {
  68420. return false;
  68421. }
  68422. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68423. };
  68424. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68425. evaluateCallback = evaluateCallback || (function (r) {
  68426. return r === "true" ? true : false;
  68427. });
  68428. var result;
  68429. var or = parenthesisContent.split("||");
  68430. for (var i in or) {
  68431. if (or.hasOwnProperty(i)) {
  68432. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68433. var and = ori.split("&&");
  68434. if (and.length > 1) {
  68435. for (var j = 0; j < and.length; ++j) {
  68436. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68437. if (andj !== "true" && andj !== "false") {
  68438. if (andj[0] === "!") {
  68439. result = !evaluateCallback(andj.substring(1));
  68440. }
  68441. else {
  68442. result = evaluateCallback(andj);
  68443. }
  68444. }
  68445. else {
  68446. result = andj === "true" ? true : false;
  68447. }
  68448. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68449. ori = "false";
  68450. break;
  68451. }
  68452. }
  68453. }
  68454. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68455. result = true;
  68456. break;
  68457. }
  68458. // result equals false (or undefined)
  68459. if (ori !== "true" && ori !== "false") {
  68460. if (ori[0] === "!") {
  68461. result = !evaluateCallback(ori.substring(1));
  68462. }
  68463. else {
  68464. result = evaluateCallback(ori);
  68465. }
  68466. }
  68467. else {
  68468. result = ori === "true" ? true : false;
  68469. }
  68470. }
  68471. }
  68472. // the whole parenthesis scope is replaced by 'true' or 'false'
  68473. return result ? "true" : "false";
  68474. };
  68475. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68476. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68477. // remove whitespaces
  68478. r = r.replace(/[\s]/g, function () { return ""; });
  68479. return r.length % 2 ? "!" : "";
  68480. });
  68481. booleanString = booleanString.trim();
  68482. if (booleanString === "!true") {
  68483. booleanString = "false";
  68484. }
  68485. else if (booleanString === "!false") {
  68486. booleanString = "true";
  68487. }
  68488. return booleanString;
  68489. };
  68490. return AndOrNotEvaluator;
  68491. }());
  68492. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68493. })(BABYLON || (BABYLON = {}));
  68494. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68495. var BABYLON;
  68496. (function (BABYLON) {
  68497. /**
  68498. * Class used to enable access to IndexedDB
  68499. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68500. */
  68501. var Database = /** @class */ (function () {
  68502. /**
  68503. * Creates a new Database
  68504. * @param urlToScene defines the url to load the scene
  68505. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68506. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68507. */
  68508. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68509. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68510. var _this = this;
  68511. // Handling various flavors of prefixed version of IndexedDB
  68512. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68513. this.callbackManifestChecked = callbackManifestChecked;
  68514. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68515. this.db = null;
  68516. this._enableSceneOffline = false;
  68517. this._enableTexturesOffline = false;
  68518. this.manifestVersionFound = 0;
  68519. this.mustUpdateRessources = false;
  68520. this.hasReachedQuota = false;
  68521. if (!Database.IDBStorageEnabled) {
  68522. this.callbackManifestChecked(true);
  68523. }
  68524. else {
  68525. if (disableManifestCheck) {
  68526. this._enableSceneOffline = true;
  68527. this._enableTexturesOffline = true;
  68528. this.manifestVersionFound = 1;
  68529. BABYLON.Tools.SetImmediate(function () {
  68530. _this.callbackManifestChecked(true);
  68531. });
  68532. }
  68533. else {
  68534. this._checkManifestFile();
  68535. }
  68536. }
  68537. }
  68538. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68539. /**
  68540. * Gets a boolean indicating if scene must be saved in the database
  68541. */
  68542. get: function () {
  68543. return this._enableSceneOffline;
  68544. },
  68545. enumerable: true,
  68546. configurable: true
  68547. });
  68548. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68549. /**
  68550. * Gets a boolean indicating if textures must be saved in the database
  68551. */
  68552. get: function () {
  68553. return this._enableTexturesOffline;
  68554. },
  68555. enumerable: true,
  68556. configurable: true
  68557. });
  68558. Database.prototype._checkManifestFile = function () {
  68559. var _this = this;
  68560. var noManifestFile = function () {
  68561. _this._enableSceneOffline = false;
  68562. _this._enableTexturesOffline = false;
  68563. _this.callbackManifestChecked(false);
  68564. };
  68565. var timeStampUsed = false;
  68566. var manifestURL = this.currentSceneUrl + ".manifest";
  68567. var xhr = new XMLHttpRequest();
  68568. if (navigator.onLine) {
  68569. // Adding a timestamp to by-pass browsers' cache
  68570. timeStampUsed = true;
  68571. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68572. }
  68573. xhr.open("GET", manifestURL, true);
  68574. xhr.addEventListener("load", function () {
  68575. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68576. try {
  68577. var manifestFile = JSON.parse(xhr.response);
  68578. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68579. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68580. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68581. _this.manifestVersionFound = manifestFile.version;
  68582. }
  68583. if (_this.callbackManifestChecked) {
  68584. _this.callbackManifestChecked(true);
  68585. }
  68586. }
  68587. catch (ex) {
  68588. noManifestFile();
  68589. }
  68590. }
  68591. else {
  68592. noManifestFile();
  68593. }
  68594. }, false);
  68595. xhr.addEventListener("error", function (event) {
  68596. if (timeStampUsed) {
  68597. timeStampUsed = false;
  68598. // Let's retry without the timeStamp
  68599. // It could fail when coupled with HTML5 Offline API
  68600. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68601. xhr.open("GET", retryManifestURL, true);
  68602. xhr.send();
  68603. }
  68604. else {
  68605. noManifestFile();
  68606. }
  68607. }, false);
  68608. try {
  68609. xhr.send();
  68610. }
  68611. catch (ex) {
  68612. BABYLON.Tools.Error("Error on XHR send request.");
  68613. this.callbackManifestChecked(false);
  68614. }
  68615. };
  68616. /**
  68617. * Open the database and make it available
  68618. * @param successCallback defines the callback to call on success
  68619. * @param errorCallback defines the callback to call on error
  68620. */
  68621. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68622. var _this = this;
  68623. var handleError = function () {
  68624. _this.isSupported = false;
  68625. if (errorCallback)
  68626. errorCallback();
  68627. };
  68628. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68629. // Your browser doesn't support IndexedDB
  68630. this.isSupported = false;
  68631. if (errorCallback)
  68632. errorCallback();
  68633. }
  68634. else {
  68635. // If the DB hasn't been opened or created yet
  68636. if (!this.db) {
  68637. this.hasReachedQuota = false;
  68638. this.isSupported = true;
  68639. var request = this.idbFactory.open("babylonjs", 1);
  68640. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68641. request.onerror = function (event) {
  68642. handleError();
  68643. };
  68644. // executes when a version change transaction cannot complete due to other active transactions
  68645. request.onblocked = function (event) {
  68646. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68647. handleError();
  68648. };
  68649. // DB has been opened successfully
  68650. request.onsuccess = function (event) {
  68651. _this.db = request.result;
  68652. successCallback();
  68653. };
  68654. // Initialization of the DB. Creating Scenes & Textures stores
  68655. request.onupgradeneeded = function (event) {
  68656. _this.db = (event.target).result;
  68657. if (_this.db) {
  68658. try {
  68659. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68660. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68661. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68662. }
  68663. catch (ex) {
  68664. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68665. handleError();
  68666. }
  68667. }
  68668. };
  68669. }
  68670. // DB has already been created and opened
  68671. else {
  68672. if (successCallback)
  68673. successCallback();
  68674. }
  68675. }
  68676. };
  68677. /**
  68678. * Loads an image from the database
  68679. * @param url defines the url to load from
  68680. * @param image defines the target DOM image
  68681. */
  68682. Database.prototype.loadImageFromDB = function (url, image) {
  68683. var _this = this;
  68684. var completeURL = Database._ReturnFullUrlLocation(url);
  68685. var saveAndLoadImage = function () {
  68686. if (!_this.hasReachedQuota && _this.db !== null) {
  68687. // the texture is not yet in the DB, let's try to save it
  68688. _this._saveImageIntoDBAsync(completeURL, image);
  68689. }
  68690. // If the texture is not in the DB and we've reached the DB quota limit
  68691. // let's load it directly from the web
  68692. else {
  68693. image.src = url;
  68694. }
  68695. };
  68696. if (!this.mustUpdateRessources) {
  68697. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68698. }
  68699. // First time we're download the images or update requested in the manifest file by a version change
  68700. else {
  68701. saveAndLoadImage();
  68702. }
  68703. };
  68704. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68705. if (this.isSupported && this.db !== null) {
  68706. var texture;
  68707. var transaction = this.db.transaction(["textures"]);
  68708. transaction.onabort = function (event) {
  68709. image.src = url;
  68710. };
  68711. transaction.oncomplete = function (event) {
  68712. var blobTextureURL;
  68713. if (texture) {
  68714. var URL = window.URL || window.webkitURL;
  68715. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68716. image.onerror = function () {
  68717. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68718. image.src = url;
  68719. };
  68720. image.src = blobTextureURL;
  68721. }
  68722. else {
  68723. notInDBCallback();
  68724. }
  68725. };
  68726. var getRequest = transaction.objectStore("textures").get(url);
  68727. getRequest.onsuccess = function (event) {
  68728. texture = (event.target).result;
  68729. };
  68730. getRequest.onerror = function (event) {
  68731. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68732. image.src = url;
  68733. };
  68734. }
  68735. else {
  68736. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68737. image.src = url;
  68738. }
  68739. };
  68740. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68741. var _this = this;
  68742. if (this.isSupported) {
  68743. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68744. var generateBlobUrl = function () {
  68745. var blobTextureURL;
  68746. if (blob) {
  68747. var URL = window.URL || window.webkitURL;
  68748. try {
  68749. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68750. }
  68751. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68752. catch (ex) {
  68753. blobTextureURL = URL.createObjectURL(blob);
  68754. }
  68755. }
  68756. if (blobTextureURL) {
  68757. image.src = blobTextureURL;
  68758. }
  68759. };
  68760. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68761. var xhr = new XMLHttpRequest(), blob;
  68762. xhr.open("GET", url, true);
  68763. xhr.responseType = "blob";
  68764. xhr.addEventListener("load", function () {
  68765. if (xhr.status === 200 && _this.db) {
  68766. // Blob as response (XHR2)
  68767. blob = xhr.response;
  68768. var transaction = _this.db.transaction(["textures"], "readwrite");
  68769. // the transaction could abort because of a QuotaExceededError error
  68770. transaction.onabort = function (event) {
  68771. try {
  68772. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68773. var srcElement = (event.srcElement || event.target);
  68774. var error = srcElement.error;
  68775. if (error && error.name === "QuotaExceededError") {
  68776. _this.hasReachedQuota = true;
  68777. }
  68778. }
  68779. catch (ex) { }
  68780. generateBlobUrl();
  68781. };
  68782. transaction.oncomplete = function (event) {
  68783. generateBlobUrl();
  68784. };
  68785. var newTexture = { textureUrl: url, data: blob };
  68786. try {
  68787. // Put the blob into the dabase
  68788. var addRequest = transaction.objectStore("textures").put(newTexture);
  68789. addRequest.onsuccess = function (event) {
  68790. };
  68791. addRequest.onerror = function (event) {
  68792. generateBlobUrl();
  68793. };
  68794. }
  68795. catch (ex) {
  68796. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68797. if (ex.code === 25) {
  68798. Database.IsUASupportingBlobStorage = false;
  68799. }
  68800. image.src = url;
  68801. }
  68802. }
  68803. else {
  68804. image.src = url;
  68805. }
  68806. }, false);
  68807. xhr.addEventListener("error", function (event) {
  68808. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68809. image.src = url;
  68810. }, false);
  68811. xhr.send();
  68812. }
  68813. else {
  68814. image.src = url;
  68815. }
  68816. }
  68817. else {
  68818. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68819. image.src = url;
  68820. }
  68821. };
  68822. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68823. var _this = this;
  68824. var updateVersion = function () {
  68825. // the version is not yet in the DB or we need to update it
  68826. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68827. };
  68828. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68829. };
  68830. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68831. var _this = this;
  68832. if (this.isSupported && this.db) {
  68833. var version;
  68834. try {
  68835. var transaction = this.db.transaction(["versions"]);
  68836. transaction.oncomplete = function (event) {
  68837. if (version) {
  68838. // If the version in the JSON file is > than the version in DB
  68839. if (_this.manifestVersionFound > version.data) {
  68840. _this.mustUpdateRessources = true;
  68841. updateInDBCallback();
  68842. }
  68843. else {
  68844. callback(version.data);
  68845. }
  68846. }
  68847. // version was not found in DB
  68848. else {
  68849. _this.mustUpdateRessources = true;
  68850. updateInDBCallback();
  68851. }
  68852. };
  68853. transaction.onabort = function (event) {
  68854. callback(-1);
  68855. };
  68856. var getRequest = transaction.objectStore("versions").get(url);
  68857. getRequest.onsuccess = function (event) {
  68858. version = (event.target).result;
  68859. };
  68860. getRequest.onerror = function (event) {
  68861. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68862. callback(-1);
  68863. };
  68864. }
  68865. catch (ex) {
  68866. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68867. callback(-1);
  68868. }
  68869. }
  68870. else {
  68871. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68872. callback(-1);
  68873. }
  68874. };
  68875. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68876. var _this = this;
  68877. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68878. try {
  68879. // Open a transaction to the database
  68880. var transaction = this.db.transaction(["versions"], "readwrite");
  68881. // the transaction could abort because of a QuotaExceededError error
  68882. transaction.onabort = function (event) {
  68883. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68884. var error = event.srcElement['error'];
  68885. if (error && error.name === "QuotaExceededError") {
  68886. _this.hasReachedQuota = true;
  68887. }
  68888. }
  68889. catch (ex) { }
  68890. callback(-1);
  68891. };
  68892. transaction.oncomplete = function (event) {
  68893. callback(_this.manifestVersionFound);
  68894. };
  68895. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68896. // Put the scene into the database
  68897. var addRequest = transaction.objectStore("versions").put(newVersion);
  68898. addRequest.onsuccess = function (event) {
  68899. };
  68900. addRequest.onerror = function (event) {
  68901. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68902. };
  68903. }
  68904. catch (ex) {
  68905. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68906. callback(-1);
  68907. }
  68908. }
  68909. else {
  68910. callback(-1);
  68911. }
  68912. };
  68913. /**
  68914. * Loads a file from database
  68915. * @param url defines the URL to load from
  68916. * @param sceneLoaded defines a callback to call on success
  68917. * @param progressCallBack defines a callback to call when progress changed
  68918. * @param errorCallback defines a callback to call on error
  68919. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68920. */
  68921. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68922. var _this = this;
  68923. var completeUrl = Database._ReturnFullUrlLocation(url);
  68924. var saveAndLoadFile = function () {
  68925. // the scene is not yet in the DB, let's try to save it
  68926. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68927. };
  68928. this._checkVersionFromDB(completeUrl, function (version) {
  68929. if (version !== -1) {
  68930. if (!_this.mustUpdateRessources) {
  68931. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68932. }
  68933. else {
  68934. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68935. }
  68936. }
  68937. else {
  68938. if (errorCallback) {
  68939. errorCallback();
  68940. }
  68941. }
  68942. });
  68943. };
  68944. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68945. if (this.isSupported && this.db) {
  68946. var targetStore;
  68947. if (url.indexOf(".babylon") !== -1) {
  68948. targetStore = "scenes";
  68949. }
  68950. else {
  68951. targetStore = "textures";
  68952. }
  68953. var file;
  68954. var transaction = this.db.transaction([targetStore]);
  68955. transaction.oncomplete = function (event) {
  68956. if (file) {
  68957. callback(file.data);
  68958. }
  68959. // file was not found in DB
  68960. else {
  68961. notInDBCallback();
  68962. }
  68963. };
  68964. transaction.onabort = function (event) {
  68965. notInDBCallback();
  68966. };
  68967. var getRequest = transaction.objectStore(targetStore).get(url);
  68968. getRequest.onsuccess = function (event) {
  68969. file = (event.target).result;
  68970. };
  68971. getRequest.onerror = function (event) {
  68972. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68973. notInDBCallback();
  68974. };
  68975. }
  68976. else {
  68977. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68978. callback();
  68979. }
  68980. };
  68981. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68982. var _this = this;
  68983. if (this.isSupported) {
  68984. var targetStore;
  68985. if (url.indexOf(".babylon") !== -1) {
  68986. targetStore = "scenes";
  68987. }
  68988. else {
  68989. targetStore = "textures";
  68990. }
  68991. // Create XHR
  68992. var xhr = new XMLHttpRequest();
  68993. var fileData;
  68994. xhr.open("GET", url, true);
  68995. if (useArrayBuffer) {
  68996. xhr.responseType = "arraybuffer";
  68997. }
  68998. if (progressCallback) {
  68999. xhr.onprogress = progressCallback;
  69000. }
  69001. xhr.addEventListener("load", function () {
  69002. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69003. // Blob as response (XHR2)
  69004. //fileData = xhr.responseText;
  69005. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69006. if (!_this.hasReachedQuota && _this.db) {
  69007. // Open a transaction to the database
  69008. var transaction = _this.db.transaction([targetStore], "readwrite");
  69009. // the transaction could abort because of a QuotaExceededError error
  69010. transaction.onabort = function (event) {
  69011. try {
  69012. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69013. var error = event.srcElement['error'];
  69014. if (error && error.name === "QuotaExceededError") {
  69015. _this.hasReachedQuota = true;
  69016. }
  69017. }
  69018. catch (ex) { }
  69019. callback(fileData);
  69020. };
  69021. transaction.oncomplete = function (event) {
  69022. callback(fileData);
  69023. };
  69024. var newFile;
  69025. if (targetStore === "scenes") {
  69026. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69027. }
  69028. else {
  69029. newFile = { textureUrl: url, data: fileData };
  69030. }
  69031. try {
  69032. // Put the scene into the database
  69033. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69034. addRequest.onsuccess = function (event) {
  69035. };
  69036. addRequest.onerror = function (event) {
  69037. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69038. };
  69039. }
  69040. catch (ex) {
  69041. callback(fileData);
  69042. }
  69043. }
  69044. else {
  69045. callback(fileData);
  69046. }
  69047. }
  69048. else {
  69049. callback();
  69050. }
  69051. }, false);
  69052. xhr.addEventListener("error", function (event) {
  69053. BABYLON.Tools.Error("error on XHR request.");
  69054. callback();
  69055. }, false);
  69056. xhr.send();
  69057. }
  69058. else {
  69059. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69060. callback();
  69061. }
  69062. };
  69063. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69064. Database.IsUASupportingBlobStorage = true;
  69065. /** Gets a boolean indicating if Database storate is enabled */
  69066. Database.IDBStorageEnabled = true;
  69067. Database._ParseURL = function (url) {
  69068. var a = document.createElement('a');
  69069. a.href = url;
  69070. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69071. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69072. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69073. return absLocation;
  69074. };
  69075. Database._ReturnFullUrlLocation = function (url) {
  69076. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69077. return (Database._ParseURL(window.location.href) + url);
  69078. }
  69079. else {
  69080. return url;
  69081. }
  69082. };
  69083. return Database;
  69084. }());
  69085. BABYLON.Database = Database;
  69086. })(BABYLON || (BABYLON = {}));
  69087. //# sourceMappingURL=babylon.database.js.map
  69088. var BABYLON;
  69089. (function (BABYLON) {
  69090. var FresnelParameters = /** @class */ (function () {
  69091. function FresnelParameters() {
  69092. this._isEnabled = true;
  69093. this.leftColor = BABYLON.Color3.White();
  69094. this.rightColor = BABYLON.Color3.Black();
  69095. this.bias = 0;
  69096. this.power = 1;
  69097. }
  69098. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69099. get: function () {
  69100. return this._isEnabled;
  69101. },
  69102. set: function (value) {
  69103. if (this._isEnabled === value) {
  69104. return;
  69105. }
  69106. this._isEnabled = value;
  69107. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69108. },
  69109. enumerable: true,
  69110. configurable: true
  69111. });
  69112. FresnelParameters.prototype.clone = function () {
  69113. var newFresnelParameters = new FresnelParameters();
  69114. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69115. return newFresnelParameters;
  69116. };
  69117. FresnelParameters.prototype.serialize = function () {
  69118. var serializationObject = {};
  69119. serializationObject.isEnabled = this.isEnabled;
  69120. serializationObject.leftColor = this.leftColor.asArray();
  69121. serializationObject.rightColor = this.rightColor.asArray();
  69122. serializationObject.bias = this.bias;
  69123. serializationObject.power = this.power;
  69124. return serializationObject;
  69125. };
  69126. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69127. var fresnelParameters = new FresnelParameters();
  69128. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69129. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69130. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69131. fresnelParameters.bias = parsedFresnelParameters.bias;
  69132. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69133. return fresnelParameters;
  69134. };
  69135. return FresnelParameters;
  69136. }());
  69137. BABYLON.FresnelParameters = FresnelParameters;
  69138. })(BABYLON || (BABYLON = {}));
  69139. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69140. var BABYLON;
  69141. (function (BABYLON) {
  69142. var MultiMaterial = /** @class */ (function (_super) {
  69143. __extends(MultiMaterial, _super);
  69144. function MultiMaterial(name, scene) {
  69145. var _this = _super.call(this, name, scene, true) || this;
  69146. scene.multiMaterials.push(_this);
  69147. _this.subMaterials = new Array();
  69148. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69149. return _this;
  69150. }
  69151. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69152. get: function () {
  69153. return this._subMaterials;
  69154. },
  69155. set: function (value) {
  69156. this._subMaterials = value;
  69157. this._hookArray(value);
  69158. },
  69159. enumerable: true,
  69160. configurable: true
  69161. });
  69162. MultiMaterial.prototype._hookArray = function (array) {
  69163. var _this = this;
  69164. var oldPush = array.push;
  69165. array.push = function () {
  69166. var items = [];
  69167. for (var _i = 0; _i < arguments.length; _i++) {
  69168. items[_i] = arguments[_i];
  69169. }
  69170. var result = oldPush.apply(array, items);
  69171. _this._markAllSubMeshesAsTexturesDirty();
  69172. return result;
  69173. };
  69174. var oldSplice = array.splice;
  69175. array.splice = function (index, deleteCount) {
  69176. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69177. _this._markAllSubMeshesAsTexturesDirty();
  69178. return deleted;
  69179. };
  69180. };
  69181. // Properties
  69182. MultiMaterial.prototype.getSubMaterial = function (index) {
  69183. if (index < 0 || index >= this.subMaterials.length) {
  69184. return this.getScene().defaultMaterial;
  69185. }
  69186. return this.subMaterials[index];
  69187. };
  69188. MultiMaterial.prototype.getActiveTextures = function () {
  69189. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69190. if (subMaterial) {
  69191. return subMaterial.getActiveTextures();
  69192. }
  69193. else {
  69194. return [];
  69195. }
  69196. }));
  69197. var _a;
  69198. };
  69199. // Methods
  69200. MultiMaterial.prototype.getClassName = function () {
  69201. return "MultiMaterial";
  69202. };
  69203. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69204. for (var index = 0; index < this.subMaterials.length; index++) {
  69205. var subMaterial = this.subMaterials[index];
  69206. if (subMaterial) {
  69207. if (subMaterial.storeEffectOnSubMeshes) {
  69208. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69209. return false;
  69210. }
  69211. continue;
  69212. }
  69213. if (!subMaterial.isReady(mesh)) {
  69214. return false;
  69215. }
  69216. }
  69217. }
  69218. return true;
  69219. };
  69220. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69221. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69222. for (var index = 0; index < this.subMaterials.length; index++) {
  69223. var subMaterial = null;
  69224. var current = this.subMaterials[index];
  69225. if (cloneChildren && current) {
  69226. subMaterial = current.clone(name + "-" + current.name);
  69227. }
  69228. else {
  69229. subMaterial = this.subMaterials[index];
  69230. }
  69231. newMultiMaterial.subMaterials.push(subMaterial);
  69232. }
  69233. return newMultiMaterial;
  69234. };
  69235. MultiMaterial.prototype.serialize = function () {
  69236. var serializationObject = {};
  69237. serializationObject.name = this.name;
  69238. serializationObject.id = this.id;
  69239. if (BABYLON.Tags) {
  69240. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69241. }
  69242. serializationObject.materials = [];
  69243. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69244. var subMat = this.subMaterials[matIndex];
  69245. if (subMat) {
  69246. serializationObject.materials.push(subMat.id);
  69247. }
  69248. else {
  69249. serializationObject.materials.push(null);
  69250. }
  69251. }
  69252. return serializationObject;
  69253. };
  69254. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69255. var scene = this.getScene();
  69256. if (!scene) {
  69257. return;
  69258. }
  69259. var index = scene.multiMaterials.indexOf(this);
  69260. if (index >= 0) {
  69261. scene.multiMaterials.splice(index, 1);
  69262. }
  69263. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69264. };
  69265. return MultiMaterial;
  69266. }(BABYLON.Material));
  69267. BABYLON.MultiMaterial = MultiMaterial;
  69268. })(BABYLON || (BABYLON = {}));
  69269. //# sourceMappingURL=babylon.multiMaterial.js.map
  69270. var BABYLON;
  69271. (function (BABYLON) {
  69272. var FreeCameraTouchInput = /** @class */ (function () {
  69273. function FreeCameraTouchInput() {
  69274. this._offsetX = null;
  69275. this._offsetY = null;
  69276. this._pointerPressed = new Array();
  69277. this.touchAngularSensibility = 200000.0;
  69278. this.touchMoveSensibility = 250.0;
  69279. }
  69280. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69281. var _this = this;
  69282. var previousPosition = null;
  69283. if (this._pointerInput === undefined) {
  69284. this._onLostFocus = function (evt) {
  69285. _this._offsetX = null;
  69286. _this._offsetY = null;
  69287. };
  69288. this._pointerInput = function (p, s) {
  69289. var evt = p.event;
  69290. if (evt.pointerType === "mouse") {
  69291. return;
  69292. }
  69293. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69294. if (!noPreventDefault) {
  69295. evt.preventDefault();
  69296. }
  69297. _this._pointerPressed.push(evt.pointerId);
  69298. if (_this._pointerPressed.length !== 1) {
  69299. return;
  69300. }
  69301. previousPosition = {
  69302. x: evt.clientX,
  69303. y: evt.clientY
  69304. };
  69305. }
  69306. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69307. if (!noPreventDefault) {
  69308. evt.preventDefault();
  69309. }
  69310. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69311. if (index === -1) {
  69312. return;
  69313. }
  69314. _this._pointerPressed.splice(index, 1);
  69315. if (index != 0) {
  69316. return;
  69317. }
  69318. previousPosition = null;
  69319. _this._offsetX = null;
  69320. _this._offsetY = null;
  69321. }
  69322. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69323. if (!noPreventDefault) {
  69324. evt.preventDefault();
  69325. }
  69326. if (!previousPosition) {
  69327. return;
  69328. }
  69329. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69330. if (index != 0) {
  69331. return;
  69332. }
  69333. _this._offsetX = evt.clientX - previousPosition.x;
  69334. _this._offsetY = -(evt.clientY - previousPosition.y);
  69335. }
  69336. };
  69337. }
  69338. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69339. if (this._onLostFocus) {
  69340. element.addEventListener("blur", this._onLostFocus);
  69341. }
  69342. };
  69343. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69344. if (this._pointerInput && element) {
  69345. if (this._observer) {
  69346. this.camera.getScene().onPointerObservable.remove(this._observer);
  69347. this._observer = null;
  69348. }
  69349. if (this._onLostFocus) {
  69350. element.removeEventListener("blur", this._onLostFocus);
  69351. this._onLostFocus = null;
  69352. }
  69353. this._pointerPressed = [];
  69354. this._offsetX = null;
  69355. this._offsetY = null;
  69356. }
  69357. };
  69358. FreeCameraTouchInput.prototype.checkInputs = function () {
  69359. if (this._offsetX && this._offsetY) {
  69360. var camera = this.camera;
  69361. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69362. if (this._pointerPressed.length > 1) {
  69363. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69364. }
  69365. else {
  69366. var speed = camera._computeLocalCameraSpeed();
  69367. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69368. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69369. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69370. }
  69371. }
  69372. };
  69373. FreeCameraTouchInput.prototype.getClassName = function () {
  69374. return "FreeCameraTouchInput";
  69375. };
  69376. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69377. return "touch";
  69378. };
  69379. __decorate([
  69380. BABYLON.serialize()
  69381. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69382. __decorate([
  69383. BABYLON.serialize()
  69384. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69385. return FreeCameraTouchInput;
  69386. }());
  69387. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69388. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69389. })(BABYLON || (BABYLON = {}));
  69390. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69391. var BABYLON;
  69392. (function (BABYLON) {
  69393. // We're mainly based on the logic defined into the FreeCamera code
  69394. var TouchCamera = /** @class */ (function (_super) {
  69395. __extends(TouchCamera, _super);
  69396. //-- end properties for backward compatibility for inputs
  69397. function TouchCamera(name, position, scene) {
  69398. var _this = _super.call(this, name, position, scene) || this;
  69399. _this.inputs.addTouch();
  69400. _this._setupInputs();
  69401. return _this;
  69402. }
  69403. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69404. //-- Begin properties for backward compatibility for inputs
  69405. get: function () {
  69406. var touch = this.inputs.attached["touch"];
  69407. if (touch)
  69408. return touch.touchAngularSensibility;
  69409. return 0;
  69410. },
  69411. set: function (value) {
  69412. var touch = this.inputs.attached["touch"];
  69413. if (touch)
  69414. touch.touchAngularSensibility = value;
  69415. },
  69416. enumerable: true,
  69417. configurable: true
  69418. });
  69419. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69420. get: function () {
  69421. var touch = this.inputs.attached["touch"];
  69422. if (touch)
  69423. return touch.touchMoveSensibility;
  69424. return 0;
  69425. },
  69426. set: function (value) {
  69427. var touch = this.inputs.attached["touch"];
  69428. if (touch)
  69429. touch.touchMoveSensibility = value;
  69430. },
  69431. enumerable: true,
  69432. configurable: true
  69433. });
  69434. TouchCamera.prototype.getClassName = function () {
  69435. return "TouchCamera";
  69436. };
  69437. TouchCamera.prototype._setupInputs = function () {
  69438. var mouse = this.inputs.attached["mouse"];
  69439. if (mouse) {
  69440. mouse.touchEnabled = false;
  69441. }
  69442. };
  69443. return TouchCamera;
  69444. }(BABYLON.FreeCamera));
  69445. BABYLON.TouchCamera = TouchCamera;
  69446. })(BABYLON || (BABYLON = {}));
  69447. //# sourceMappingURL=babylon.touchCamera.js.map
  69448. var BABYLON;
  69449. (function (BABYLON) {
  69450. var ProceduralTexture = /** @class */ (function (_super) {
  69451. __extends(ProceduralTexture, _super);
  69452. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69453. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69454. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69455. if (isCube === void 0) { isCube = false; }
  69456. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69457. _this.isCube = isCube;
  69458. _this.isEnabled = true;
  69459. _this._currentRefreshId = -1;
  69460. _this._refreshRate = 1;
  69461. _this._vertexBuffers = {};
  69462. _this._uniforms = new Array();
  69463. _this._samplers = new Array();
  69464. _this._textures = {};
  69465. _this._floats = {};
  69466. _this._floatsArrays = {};
  69467. _this._colors3 = {};
  69468. _this._colors4 = {};
  69469. _this._vectors2 = {};
  69470. _this._vectors3 = {};
  69471. _this._matrices = {};
  69472. _this._fallbackTextureUsed = false;
  69473. scene.proceduralTextures.push(_this);
  69474. _this._engine = scene.getEngine();
  69475. _this.name = name;
  69476. _this.isRenderTarget = true;
  69477. _this._size = size;
  69478. _this._generateMipMaps = generateMipMaps;
  69479. _this.setFragment(fragment);
  69480. _this._fallbackTexture = fallbackTexture;
  69481. if (isCube) {
  69482. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69483. _this.setFloat("face", 0);
  69484. }
  69485. else {
  69486. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69487. }
  69488. // VBO
  69489. var vertices = [];
  69490. vertices.push(1, 1);
  69491. vertices.push(-1, 1);
  69492. vertices.push(-1, -1);
  69493. vertices.push(1, -1);
  69494. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69495. _this._createIndexBuffer();
  69496. return _this;
  69497. }
  69498. ProceduralTexture.prototype._createIndexBuffer = function () {
  69499. var engine = this._engine;
  69500. // Indices
  69501. var indices = [];
  69502. indices.push(0);
  69503. indices.push(1);
  69504. indices.push(2);
  69505. indices.push(0);
  69506. indices.push(2);
  69507. indices.push(3);
  69508. this._indexBuffer = engine.createIndexBuffer(indices);
  69509. };
  69510. ProceduralTexture.prototype._rebuild = function () {
  69511. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69512. if (vb) {
  69513. vb._rebuild();
  69514. }
  69515. this._createIndexBuffer();
  69516. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69517. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69518. }
  69519. };
  69520. ProceduralTexture.prototype.reset = function () {
  69521. if (this._effect === undefined) {
  69522. return;
  69523. }
  69524. var engine = this._engine;
  69525. engine._releaseEffect(this._effect);
  69526. };
  69527. ProceduralTexture.prototype.isReady = function () {
  69528. var _this = this;
  69529. var engine = this._engine;
  69530. var shaders;
  69531. if (!this._fragment) {
  69532. return false;
  69533. }
  69534. if (this._fallbackTextureUsed) {
  69535. return true;
  69536. }
  69537. if (this._fragment.fragmentElement !== undefined) {
  69538. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69539. }
  69540. else {
  69541. shaders = { vertex: "procedural", fragment: this._fragment };
  69542. }
  69543. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69544. _this.releaseInternalTexture();
  69545. if (_this._fallbackTexture) {
  69546. _this._texture = _this._fallbackTexture._texture;
  69547. if (_this._texture) {
  69548. _this._texture.incrementReferences();
  69549. }
  69550. }
  69551. _this._fallbackTextureUsed = true;
  69552. });
  69553. return this._effect.isReady();
  69554. };
  69555. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69556. this._currentRefreshId = -1;
  69557. };
  69558. ProceduralTexture.prototype.setFragment = function (fragment) {
  69559. this._fragment = fragment;
  69560. };
  69561. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69562. get: function () {
  69563. return this._refreshRate;
  69564. },
  69565. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69566. set: function (value) {
  69567. this._refreshRate = value;
  69568. this.resetRefreshCounter();
  69569. },
  69570. enumerable: true,
  69571. configurable: true
  69572. });
  69573. ProceduralTexture.prototype._shouldRender = function () {
  69574. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69575. return false;
  69576. }
  69577. if (this._fallbackTextureUsed) {
  69578. return false;
  69579. }
  69580. if (this._currentRefreshId === -1) { // At least render once
  69581. this._currentRefreshId = 1;
  69582. return true;
  69583. }
  69584. if (this.refreshRate === this._currentRefreshId) {
  69585. this._currentRefreshId = 1;
  69586. return true;
  69587. }
  69588. this._currentRefreshId++;
  69589. return false;
  69590. };
  69591. ProceduralTexture.prototype.getRenderSize = function () {
  69592. return this._size;
  69593. };
  69594. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69595. if (this._fallbackTextureUsed) {
  69596. return;
  69597. }
  69598. this.releaseInternalTexture();
  69599. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69600. };
  69601. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69602. if (this._uniforms.indexOf(uniformName) === -1) {
  69603. this._uniforms.push(uniformName);
  69604. }
  69605. };
  69606. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69607. if (this._samplers.indexOf(name) === -1) {
  69608. this._samplers.push(name);
  69609. }
  69610. this._textures[name] = texture;
  69611. return this;
  69612. };
  69613. ProceduralTexture.prototype.setFloat = function (name, value) {
  69614. this._checkUniform(name);
  69615. this._floats[name] = value;
  69616. return this;
  69617. };
  69618. ProceduralTexture.prototype.setFloats = function (name, value) {
  69619. this._checkUniform(name);
  69620. this._floatsArrays[name] = value;
  69621. return this;
  69622. };
  69623. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69624. this._checkUniform(name);
  69625. this._colors3[name] = value;
  69626. return this;
  69627. };
  69628. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69629. this._checkUniform(name);
  69630. this._colors4[name] = value;
  69631. return this;
  69632. };
  69633. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69634. this._checkUniform(name);
  69635. this._vectors2[name] = value;
  69636. return this;
  69637. };
  69638. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69639. this._checkUniform(name);
  69640. this._vectors3[name] = value;
  69641. return this;
  69642. };
  69643. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69644. this._checkUniform(name);
  69645. this._matrices[name] = value;
  69646. return this;
  69647. };
  69648. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69649. var scene = this.getScene();
  69650. if (!scene) {
  69651. return;
  69652. }
  69653. var engine = this._engine;
  69654. // Render
  69655. engine.enableEffect(this._effect);
  69656. engine.setState(false);
  69657. // Texture
  69658. for (var name in this._textures) {
  69659. this._effect.setTexture(name, this._textures[name]);
  69660. }
  69661. // Float
  69662. for (name in this._floats) {
  69663. this._effect.setFloat(name, this._floats[name]);
  69664. }
  69665. // Floats
  69666. for (name in this._floatsArrays) {
  69667. this._effect.setArray(name, this._floatsArrays[name]);
  69668. }
  69669. // Color3
  69670. for (name in this._colors3) {
  69671. this._effect.setColor3(name, this._colors3[name]);
  69672. }
  69673. // Color4
  69674. for (name in this._colors4) {
  69675. var color = this._colors4[name];
  69676. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69677. }
  69678. // Vector2
  69679. for (name in this._vectors2) {
  69680. this._effect.setVector2(name, this._vectors2[name]);
  69681. }
  69682. // Vector3
  69683. for (name in this._vectors3) {
  69684. this._effect.setVector3(name, this._vectors3[name]);
  69685. }
  69686. // Matrix
  69687. for (name in this._matrices) {
  69688. this._effect.setMatrix(name, this._matrices[name]);
  69689. }
  69690. if (!this._texture) {
  69691. return;
  69692. }
  69693. if (this.isCube) {
  69694. for (var face = 0; face < 6; face++) {
  69695. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69696. // VBOs
  69697. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69698. this._effect.setFloat("face", face);
  69699. // Clear
  69700. engine.clear(scene.clearColor, true, true, true);
  69701. // Draw order
  69702. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69703. // Mipmaps
  69704. if (face === 5) {
  69705. engine.generateMipMapsForCubemap(this._texture);
  69706. }
  69707. }
  69708. }
  69709. else {
  69710. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69711. // VBOs
  69712. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69713. // Clear
  69714. engine.clear(scene.clearColor, true, true, true);
  69715. // Draw order
  69716. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69717. }
  69718. // Unbind
  69719. engine.unBindFramebuffer(this._texture, this.isCube);
  69720. if (this.onGenerated) {
  69721. this.onGenerated();
  69722. }
  69723. };
  69724. ProceduralTexture.prototype.clone = function () {
  69725. var textureSize = this.getSize();
  69726. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69727. // Base texture
  69728. newTexture.hasAlpha = this.hasAlpha;
  69729. newTexture.level = this.level;
  69730. // RenderTarget Texture
  69731. newTexture.coordinatesMode = this.coordinatesMode;
  69732. return newTexture;
  69733. };
  69734. ProceduralTexture.prototype.dispose = function () {
  69735. var scene = this.getScene();
  69736. if (!scene) {
  69737. return;
  69738. }
  69739. var index = scene.proceduralTextures.indexOf(this);
  69740. if (index >= 0) {
  69741. scene.proceduralTextures.splice(index, 1);
  69742. }
  69743. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69744. if (vertexBuffer) {
  69745. vertexBuffer.dispose();
  69746. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69747. }
  69748. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69749. this._indexBuffer = null;
  69750. }
  69751. _super.prototype.dispose.call(this);
  69752. };
  69753. return ProceduralTexture;
  69754. }(BABYLON.Texture));
  69755. BABYLON.ProceduralTexture = ProceduralTexture;
  69756. })(BABYLON || (BABYLON = {}));
  69757. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69758. var BABYLON;
  69759. (function (BABYLON) {
  69760. var CustomProceduralTexture = /** @class */ (function (_super) {
  69761. __extends(CustomProceduralTexture, _super);
  69762. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69763. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69764. _this._animate = true;
  69765. _this._time = 0;
  69766. _this._texturePath = texturePath;
  69767. //Try to load json
  69768. _this.loadJson(texturePath);
  69769. _this.refreshRate = 1;
  69770. return _this;
  69771. }
  69772. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69773. var _this = this;
  69774. var noConfigFile = function () {
  69775. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69776. try {
  69777. _this.setFragment(_this._texturePath);
  69778. }
  69779. catch (ex) {
  69780. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69781. }
  69782. };
  69783. var configFileUrl = jsonUrl + "/config.json";
  69784. var xhr = new XMLHttpRequest();
  69785. xhr.open("GET", configFileUrl, true);
  69786. xhr.addEventListener("load", function () {
  69787. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69788. try {
  69789. _this._config = JSON.parse(xhr.response);
  69790. _this.updateShaderUniforms();
  69791. _this.updateTextures();
  69792. _this.setFragment(_this._texturePath + "/custom");
  69793. _this._animate = _this._config.animate;
  69794. _this.refreshRate = _this._config.refreshrate;
  69795. }
  69796. catch (ex) {
  69797. noConfigFile();
  69798. }
  69799. }
  69800. else {
  69801. noConfigFile();
  69802. }
  69803. }, false);
  69804. xhr.addEventListener("error", function () {
  69805. noConfigFile();
  69806. }, false);
  69807. try {
  69808. xhr.send();
  69809. }
  69810. catch (ex) {
  69811. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69812. }
  69813. };
  69814. CustomProceduralTexture.prototype.isReady = function () {
  69815. if (!_super.prototype.isReady.call(this)) {
  69816. return false;
  69817. }
  69818. for (var name in this._textures) {
  69819. var texture = this._textures[name];
  69820. if (!texture.isReady()) {
  69821. return false;
  69822. }
  69823. }
  69824. return true;
  69825. };
  69826. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69827. var scene = this.getScene();
  69828. if (this._animate && scene) {
  69829. this._time += scene.getAnimationRatio() * 0.03;
  69830. this.updateShaderUniforms();
  69831. }
  69832. _super.prototype.render.call(this, useCameraPostProcess);
  69833. };
  69834. CustomProceduralTexture.prototype.updateTextures = function () {
  69835. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69836. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69837. }
  69838. };
  69839. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69840. if (this._config) {
  69841. for (var j = 0; j < this._config.uniforms.length; j++) {
  69842. var uniform = this._config.uniforms[j];
  69843. switch (uniform.type) {
  69844. case "float":
  69845. this.setFloat(uniform.name, uniform.value);
  69846. break;
  69847. case "color3":
  69848. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69849. break;
  69850. case "color4":
  69851. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69852. break;
  69853. case "vector2":
  69854. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69855. break;
  69856. case "vector3":
  69857. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69858. break;
  69859. }
  69860. }
  69861. }
  69862. this.setFloat("time", this._time);
  69863. };
  69864. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69865. get: function () {
  69866. return this._animate;
  69867. },
  69868. set: function (value) {
  69869. this._animate = value;
  69870. },
  69871. enumerable: true,
  69872. configurable: true
  69873. });
  69874. return CustomProceduralTexture;
  69875. }(BABYLON.ProceduralTexture));
  69876. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69877. })(BABYLON || (BABYLON = {}));
  69878. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69879. var BABYLON;
  69880. (function (BABYLON) {
  69881. var FreeCameraGamepadInput = /** @class */ (function () {
  69882. function FreeCameraGamepadInput() {
  69883. this.gamepadAngularSensibility = 200;
  69884. this.gamepadMoveSensibility = 40;
  69885. // private members
  69886. this._cameraTransform = BABYLON.Matrix.Identity();
  69887. this._deltaTransform = BABYLON.Vector3.Zero();
  69888. this._vector3 = BABYLON.Vector3.Zero();
  69889. this._vector2 = BABYLON.Vector2.Zero();
  69890. }
  69891. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69892. var _this = this;
  69893. var manager = this.camera.getScene().gamepadManager;
  69894. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69895. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69896. // prioritize XBOX gamepads.
  69897. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69898. _this.gamepad = gamepad;
  69899. }
  69900. }
  69901. });
  69902. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69903. if (_this.gamepad === gamepad) {
  69904. _this.gamepad = null;
  69905. }
  69906. });
  69907. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69908. };
  69909. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69910. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69911. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69912. this.gamepad = null;
  69913. };
  69914. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69915. if (this.gamepad && this.gamepad.leftStick) {
  69916. var camera = this.camera;
  69917. var LSValues = this.gamepad.leftStick;
  69918. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69919. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69920. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69921. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69922. var RSValues = this.gamepad.rightStick;
  69923. if (RSValues) {
  69924. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69925. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69926. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69927. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69928. }
  69929. else {
  69930. RSValues = { x: 0, y: 0 };
  69931. }
  69932. if (!camera.rotationQuaternion) {
  69933. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69934. }
  69935. else {
  69936. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69937. }
  69938. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69939. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69940. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69941. camera.cameraDirection.addInPlace(this._deltaTransform);
  69942. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69943. camera.cameraRotation.addInPlace(this._vector2);
  69944. }
  69945. };
  69946. FreeCameraGamepadInput.prototype.getClassName = function () {
  69947. return "FreeCameraGamepadInput";
  69948. };
  69949. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69950. return "gamepad";
  69951. };
  69952. __decorate([
  69953. BABYLON.serialize()
  69954. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69955. __decorate([
  69956. BABYLON.serialize()
  69957. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69958. return FreeCameraGamepadInput;
  69959. }());
  69960. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69961. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69962. })(BABYLON || (BABYLON = {}));
  69963. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69964. var BABYLON;
  69965. (function (BABYLON) {
  69966. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69967. function ArcRotateCameraGamepadInput() {
  69968. this.gamepadRotationSensibility = 80;
  69969. this.gamepadMoveSensibility = 40;
  69970. }
  69971. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69972. var _this = this;
  69973. var manager = this.camera.getScene().gamepadManager;
  69974. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69975. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69976. // prioritize XBOX gamepads.
  69977. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69978. _this.gamepad = gamepad;
  69979. }
  69980. }
  69981. });
  69982. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69983. if (_this.gamepad === gamepad) {
  69984. _this.gamepad = null;
  69985. }
  69986. });
  69987. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69988. };
  69989. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69990. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69991. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69992. this.gamepad = null;
  69993. };
  69994. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69995. if (this.gamepad) {
  69996. var camera = this.camera;
  69997. var RSValues = this.gamepad.rightStick;
  69998. if (RSValues) {
  69999. if (RSValues.x != 0) {
  70000. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70001. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70002. camera.inertialAlphaOffset += normalizedRX;
  70003. }
  70004. }
  70005. if (RSValues.y != 0) {
  70006. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70007. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70008. camera.inertialBetaOffset += normalizedRY;
  70009. }
  70010. }
  70011. }
  70012. var LSValues = this.gamepad.leftStick;
  70013. if (LSValues && LSValues.y != 0) {
  70014. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70015. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70016. this.camera.inertialRadiusOffset -= normalizedLY;
  70017. }
  70018. }
  70019. }
  70020. };
  70021. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70022. return "ArcRotateCameraGamepadInput";
  70023. };
  70024. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70025. return "gamepad";
  70026. };
  70027. __decorate([
  70028. BABYLON.serialize()
  70029. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70030. __decorate([
  70031. BABYLON.serialize()
  70032. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70033. return ArcRotateCameraGamepadInput;
  70034. }());
  70035. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70036. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70037. })(BABYLON || (BABYLON = {}));
  70038. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70039. var BABYLON;
  70040. (function (BABYLON) {
  70041. var GamepadManager = /** @class */ (function () {
  70042. function GamepadManager(_scene) {
  70043. var _this = this;
  70044. this._scene = _scene;
  70045. this._babylonGamepads = [];
  70046. this._oneGamepadConnected = false;
  70047. this._isMonitoring = false;
  70048. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70049. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70050. this._gamepadEventSupported = false;
  70051. }
  70052. else {
  70053. this._gamepadEventSupported = 'GamepadEvent' in window;
  70054. this._gamepadSupport = (navigator.getGamepads ||
  70055. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70056. }
  70057. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70058. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70059. for (var i in _this._babylonGamepads) {
  70060. var gamepad = _this._babylonGamepads[i];
  70061. if (gamepad && gamepad._isConnected) {
  70062. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70063. }
  70064. }
  70065. });
  70066. this._onGamepadConnectedEvent = function (evt) {
  70067. var gamepad = evt.gamepad;
  70068. if (gamepad.index in _this._babylonGamepads) {
  70069. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70070. return;
  70071. }
  70072. }
  70073. var newGamepad;
  70074. if (_this._babylonGamepads[gamepad.index]) {
  70075. newGamepad = _this._babylonGamepads[gamepad.index];
  70076. newGamepad.browserGamepad = gamepad;
  70077. newGamepad._isConnected = true;
  70078. }
  70079. else {
  70080. newGamepad = _this._addNewGamepad(gamepad);
  70081. }
  70082. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70083. _this._startMonitoringGamepads();
  70084. };
  70085. this._onGamepadDisconnectedEvent = function (evt) {
  70086. var gamepad = evt.gamepad;
  70087. // Remove the gamepad from the list of gamepads to monitor.
  70088. for (var i in _this._babylonGamepads) {
  70089. if (_this._babylonGamepads[i].index === gamepad.index) {
  70090. var disconnectedGamepad = _this._babylonGamepads[i];
  70091. disconnectedGamepad._isConnected = false;
  70092. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70093. break;
  70094. }
  70095. }
  70096. };
  70097. if (this._gamepadSupport) {
  70098. //first add already-connected gamepads
  70099. this._updateGamepadObjects();
  70100. if (this._babylonGamepads.length) {
  70101. this._startMonitoringGamepads();
  70102. }
  70103. // Checking if the gamepad connected event is supported (like in Firefox)
  70104. if (this._gamepadEventSupported) {
  70105. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70106. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70107. }
  70108. else {
  70109. this._startMonitoringGamepads();
  70110. }
  70111. }
  70112. }
  70113. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70114. get: function () {
  70115. return this._babylonGamepads;
  70116. },
  70117. enumerable: true,
  70118. configurable: true
  70119. });
  70120. GamepadManager.prototype.getGamepadByType = function (type) {
  70121. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70122. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70123. var gamepad = _a[_i];
  70124. if (gamepad && gamepad.type === type) {
  70125. return gamepad;
  70126. }
  70127. }
  70128. return null;
  70129. };
  70130. GamepadManager.prototype.dispose = function () {
  70131. if (this._gamepadEventSupported) {
  70132. if (this._onGamepadConnectedEvent) {
  70133. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70134. }
  70135. if (this._onGamepadDisconnectedEvent) {
  70136. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70137. }
  70138. this._onGamepadConnectedEvent = null;
  70139. this._onGamepadDisconnectedEvent = null;
  70140. }
  70141. this._babylonGamepads.forEach(function (gamepad) {
  70142. gamepad.dispose();
  70143. });
  70144. this.onGamepadConnectedObservable.clear();
  70145. this.onGamepadDisconnectedObservable.clear();
  70146. this._oneGamepadConnected = false;
  70147. this._stopMonitoringGamepads();
  70148. this._babylonGamepads = [];
  70149. };
  70150. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70151. if (!this._oneGamepadConnected) {
  70152. this._oneGamepadConnected = true;
  70153. }
  70154. var newGamepad;
  70155. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70156. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70157. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70158. }
  70159. // if pose is supported, use the (WebVR) pose enabled controller
  70160. else if (gamepad.pose) {
  70161. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70162. }
  70163. else {
  70164. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70165. }
  70166. this._babylonGamepads[newGamepad.index] = newGamepad;
  70167. return newGamepad;
  70168. };
  70169. GamepadManager.prototype._startMonitoringGamepads = function () {
  70170. if (!this._isMonitoring) {
  70171. this._isMonitoring = true;
  70172. //back-comp
  70173. if (!this._scene) {
  70174. this._checkGamepadsStatus();
  70175. }
  70176. }
  70177. };
  70178. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70179. this._isMonitoring = false;
  70180. };
  70181. GamepadManager.prototype._checkGamepadsStatus = function () {
  70182. var _this = this;
  70183. // Hack to be compatible Chrome
  70184. this._updateGamepadObjects();
  70185. for (var i in this._babylonGamepads) {
  70186. var gamepad = this._babylonGamepads[i];
  70187. if (!gamepad || !gamepad.isConnected) {
  70188. continue;
  70189. }
  70190. gamepad.update();
  70191. }
  70192. if (this._isMonitoring && !this._scene) {
  70193. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70194. }
  70195. };
  70196. // This function is called only on Chrome, which does not properly support
  70197. // connection/disconnection events and forces you to recopy again the gamepad object
  70198. GamepadManager.prototype._updateGamepadObjects = function () {
  70199. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70200. for (var i = 0; i < gamepads.length; i++) {
  70201. var gamepad = gamepads[i];
  70202. if (gamepad) {
  70203. if (!this._babylonGamepads[gamepad.index]) {
  70204. var newGamepad = this._addNewGamepad(gamepad);
  70205. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70206. }
  70207. else {
  70208. // Forced to copy again this object for Chrome for unknown reason
  70209. this._babylonGamepads[i].browserGamepad = gamepad;
  70210. if (!this._babylonGamepads[i].isConnected) {
  70211. this._babylonGamepads[i]._isConnected = true;
  70212. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70213. }
  70214. }
  70215. }
  70216. }
  70217. };
  70218. return GamepadManager;
  70219. }());
  70220. BABYLON.GamepadManager = GamepadManager;
  70221. })(BABYLON || (BABYLON = {}));
  70222. //# sourceMappingURL=babylon.gamepadManager.js.map
  70223. var BABYLON;
  70224. (function (BABYLON) {
  70225. var StickValues = /** @class */ (function () {
  70226. function StickValues(x, y) {
  70227. this.x = x;
  70228. this.y = y;
  70229. }
  70230. return StickValues;
  70231. }());
  70232. BABYLON.StickValues = StickValues;
  70233. var Gamepad = /** @class */ (function () {
  70234. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70235. if (leftStickX === void 0) { leftStickX = 0; }
  70236. if (leftStickY === void 0) { leftStickY = 1; }
  70237. if (rightStickX === void 0) { rightStickX = 2; }
  70238. if (rightStickY === void 0) { rightStickY = 3; }
  70239. this.id = id;
  70240. this.index = index;
  70241. this.browserGamepad = browserGamepad;
  70242. this._isConnected = true;
  70243. this._invertLeftStickY = false;
  70244. this.type = Gamepad.GAMEPAD;
  70245. this._leftStickAxisX = leftStickX;
  70246. this._leftStickAxisY = leftStickY;
  70247. this._rightStickAxisX = rightStickX;
  70248. this._rightStickAxisY = rightStickY;
  70249. if (this.browserGamepad.axes.length >= 2) {
  70250. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70251. }
  70252. if (this.browserGamepad.axes.length >= 4) {
  70253. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70254. }
  70255. }
  70256. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70257. get: function () {
  70258. return this._isConnected;
  70259. },
  70260. enumerable: true,
  70261. configurable: true
  70262. });
  70263. Gamepad.prototype.onleftstickchanged = function (callback) {
  70264. this._onleftstickchanged = callback;
  70265. };
  70266. Gamepad.prototype.onrightstickchanged = function (callback) {
  70267. this._onrightstickchanged = callback;
  70268. };
  70269. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70270. get: function () {
  70271. return this._leftStick;
  70272. },
  70273. set: function (newValues) {
  70274. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70275. this._onleftstickchanged(newValues);
  70276. }
  70277. this._leftStick = newValues;
  70278. },
  70279. enumerable: true,
  70280. configurable: true
  70281. });
  70282. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70283. get: function () {
  70284. return this._rightStick;
  70285. },
  70286. set: function (newValues) {
  70287. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70288. this._onrightstickchanged(newValues);
  70289. }
  70290. this._rightStick = newValues;
  70291. },
  70292. enumerable: true,
  70293. configurable: true
  70294. });
  70295. Gamepad.prototype.update = function () {
  70296. if (this._leftStick) {
  70297. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70298. if (this._invertLeftStickY) {
  70299. this.leftStick.y *= -1;
  70300. }
  70301. }
  70302. if (this._rightStick) {
  70303. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70304. }
  70305. };
  70306. Gamepad.prototype.dispose = function () {
  70307. };
  70308. Gamepad.GAMEPAD = 0;
  70309. Gamepad.GENERIC = 1;
  70310. Gamepad.XBOX = 2;
  70311. Gamepad.POSE_ENABLED = 3;
  70312. return Gamepad;
  70313. }());
  70314. BABYLON.Gamepad = Gamepad;
  70315. var GenericPad = /** @class */ (function (_super) {
  70316. __extends(GenericPad, _super);
  70317. function GenericPad(id, index, browserGamepad) {
  70318. var _this = _super.call(this, id, index, browserGamepad) || this;
  70319. _this.onButtonDownObservable = new BABYLON.Observable();
  70320. _this.onButtonUpObservable = new BABYLON.Observable();
  70321. _this.type = Gamepad.GENERIC;
  70322. _this._buttons = new Array(browserGamepad.buttons.length);
  70323. return _this;
  70324. }
  70325. GenericPad.prototype.onbuttondown = function (callback) {
  70326. this._onbuttondown = callback;
  70327. };
  70328. GenericPad.prototype.onbuttonup = function (callback) {
  70329. this._onbuttonup = callback;
  70330. };
  70331. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70332. if (newValue !== currentValue) {
  70333. if (newValue === 1) {
  70334. if (this._onbuttondown) {
  70335. this._onbuttondown(buttonIndex);
  70336. }
  70337. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70338. }
  70339. if (newValue === 0) {
  70340. if (this._onbuttonup) {
  70341. this._onbuttonup(buttonIndex);
  70342. }
  70343. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70344. }
  70345. }
  70346. return newValue;
  70347. };
  70348. GenericPad.prototype.update = function () {
  70349. _super.prototype.update.call(this);
  70350. for (var index = 0; index < this._buttons.length; index++) {
  70351. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70352. }
  70353. };
  70354. GenericPad.prototype.dispose = function () {
  70355. _super.prototype.dispose.call(this);
  70356. this.onButtonDownObservable.clear();
  70357. this.onButtonUpObservable.clear();
  70358. };
  70359. return GenericPad;
  70360. }(Gamepad));
  70361. BABYLON.GenericPad = GenericPad;
  70362. })(BABYLON || (BABYLON = {}));
  70363. //# sourceMappingURL=babylon.gamepad.js.map
  70364. var BABYLON;
  70365. (function (BABYLON) {
  70366. /**
  70367. * Defines supported buttons for XBox360 compatible gamepads
  70368. */
  70369. var Xbox360Button;
  70370. (function (Xbox360Button) {
  70371. /** A */
  70372. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70373. /** B */
  70374. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70375. /** X */
  70376. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70377. /** Y */
  70378. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70379. /** Start */
  70380. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70381. /** Back */
  70382. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70383. /** Left button */
  70384. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70385. /** Right button */
  70386. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70387. /** Left stick */
  70388. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70389. /** Right stick */
  70390. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70391. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70392. /** Defines values for XBox360 DPad */
  70393. var Xbox360Dpad;
  70394. (function (Xbox360Dpad) {
  70395. /** Up */
  70396. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70397. /** Down */
  70398. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70399. /** Left */
  70400. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70401. /** Right */
  70402. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70403. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70404. /**
  70405. * Defines a XBox360 gamepad
  70406. */
  70407. var Xbox360Pad = /** @class */ (function (_super) {
  70408. __extends(Xbox360Pad, _super);
  70409. /**
  70410. * Creates a new XBox360 gamepad object
  70411. * @param id defines the id of this gamepad
  70412. * @param index defines its index
  70413. * @param gamepad defines the internal HTML gamepad object
  70414. * @param xboxOne defines if it is a XBox One gamepad
  70415. */
  70416. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70417. if (xboxOne === void 0) { xboxOne = false; }
  70418. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70419. _this._leftTrigger = 0;
  70420. _this._rightTrigger = 0;
  70421. /** Observable raised when a button is pressed */
  70422. _this.onButtonDownObservable = new BABYLON.Observable();
  70423. /** Observable raised when a button is released */
  70424. _this.onButtonUpObservable = new BABYLON.Observable();
  70425. /** Observable raised when a pad is pressed */
  70426. _this.onPadDownObservable = new BABYLON.Observable();
  70427. /** Observable raised when a pad is released */
  70428. _this.onPadUpObservable = new BABYLON.Observable();
  70429. _this._buttonA = 0;
  70430. _this._buttonB = 0;
  70431. _this._buttonX = 0;
  70432. _this._buttonY = 0;
  70433. _this._buttonBack = 0;
  70434. _this._buttonStart = 0;
  70435. _this._buttonLB = 0;
  70436. _this._buttonRB = 0;
  70437. _this._buttonLeftStick = 0;
  70438. _this._buttonRightStick = 0;
  70439. _this._dPadUp = 0;
  70440. _this._dPadDown = 0;
  70441. _this._dPadLeft = 0;
  70442. _this._dPadRight = 0;
  70443. _this._isXboxOnePad = false;
  70444. _this.type = BABYLON.Gamepad.XBOX;
  70445. _this._isXboxOnePad = xboxOne;
  70446. return _this;
  70447. }
  70448. /**
  70449. * Defines the callback to call when left trigger is pressed
  70450. * @param callback defines the callback to use
  70451. */
  70452. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70453. this._onlefttriggerchanged = callback;
  70454. };
  70455. /**
  70456. * Defines the callback to call when right trigger is pressed
  70457. * @param callback defines the callback to use
  70458. */
  70459. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70460. this._onrighttriggerchanged = callback;
  70461. };
  70462. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70463. /**
  70464. * Gets or sets left trigger value
  70465. */
  70466. get: function () {
  70467. return this._leftTrigger;
  70468. },
  70469. set: function (newValue) {
  70470. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70471. this._onlefttriggerchanged(newValue);
  70472. }
  70473. this._leftTrigger = newValue;
  70474. },
  70475. enumerable: true,
  70476. configurable: true
  70477. });
  70478. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70479. /**
  70480. * Gets or sets right trigger value
  70481. */
  70482. get: function () {
  70483. return this._rightTrigger;
  70484. },
  70485. set: function (newValue) {
  70486. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70487. this._onrighttriggerchanged(newValue);
  70488. }
  70489. this._rightTrigger = newValue;
  70490. },
  70491. enumerable: true,
  70492. configurable: true
  70493. });
  70494. /**
  70495. * Defines the callback to call when a button is pressed
  70496. * @param callback defines the callback to use
  70497. */
  70498. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70499. this._onbuttondown = callback;
  70500. };
  70501. /**
  70502. * Defines the callback to call when a button is released
  70503. * @param callback defines the callback to use
  70504. */
  70505. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70506. this._onbuttonup = callback;
  70507. };
  70508. /**
  70509. * Defines the callback to call when a pad is pressed
  70510. * @param callback defines the callback to use
  70511. */
  70512. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70513. this._ondpaddown = callback;
  70514. };
  70515. /**
  70516. * Defines the callback to call when a pad is released
  70517. * @param callback defines the callback to use
  70518. */
  70519. Xbox360Pad.prototype.ondpadup = function (callback) {
  70520. this._ondpadup = callback;
  70521. };
  70522. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70523. if (newValue !== currentValue) {
  70524. if (newValue === 1) {
  70525. if (this._onbuttondown) {
  70526. this._onbuttondown(buttonType);
  70527. }
  70528. this.onButtonDownObservable.notifyObservers(buttonType);
  70529. }
  70530. if (newValue === 0) {
  70531. if (this._onbuttonup) {
  70532. this._onbuttonup(buttonType);
  70533. }
  70534. this.onButtonUpObservable.notifyObservers(buttonType);
  70535. }
  70536. }
  70537. return newValue;
  70538. };
  70539. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70540. if (newValue !== currentValue) {
  70541. if (newValue === 1) {
  70542. if (this._ondpaddown) {
  70543. this._ondpaddown(buttonType);
  70544. }
  70545. this.onPadDownObservable.notifyObservers(buttonType);
  70546. }
  70547. if (newValue === 0) {
  70548. if (this._ondpadup) {
  70549. this._ondpadup(buttonType);
  70550. }
  70551. this.onPadUpObservable.notifyObservers(buttonType);
  70552. }
  70553. }
  70554. return newValue;
  70555. };
  70556. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70557. /** Gets or sets value of A button */
  70558. get: function () {
  70559. return this._buttonA;
  70560. },
  70561. set: function (value) {
  70562. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70563. },
  70564. enumerable: true,
  70565. configurable: true
  70566. });
  70567. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70568. /** Gets or sets value of B button */
  70569. get: function () {
  70570. return this._buttonB;
  70571. },
  70572. set: function (value) {
  70573. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70574. },
  70575. enumerable: true,
  70576. configurable: true
  70577. });
  70578. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70579. /** Gets or sets value of X button */
  70580. get: function () {
  70581. return this._buttonX;
  70582. },
  70583. set: function (value) {
  70584. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70585. },
  70586. enumerable: true,
  70587. configurable: true
  70588. });
  70589. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70590. /** Gets or sets value of Y button */
  70591. get: function () {
  70592. return this._buttonY;
  70593. },
  70594. set: function (value) {
  70595. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70596. },
  70597. enumerable: true,
  70598. configurable: true
  70599. });
  70600. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70601. /** Gets or sets value of Start button */
  70602. get: function () {
  70603. return this._buttonStart;
  70604. },
  70605. set: function (value) {
  70606. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70607. },
  70608. enumerable: true,
  70609. configurable: true
  70610. });
  70611. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70612. /** Gets or sets value of Back button */
  70613. get: function () {
  70614. return this._buttonBack;
  70615. },
  70616. set: function (value) {
  70617. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70618. },
  70619. enumerable: true,
  70620. configurable: true
  70621. });
  70622. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70623. /** Gets or sets value of Left button */
  70624. get: function () {
  70625. return this._buttonLB;
  70626. },
  70627. set: function (value) {
  70628. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70629. },
  70630. enumerable: true,
  70631. configurable: true
  70632. });
  70633. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70634. /** Gets or sets value of Right button */
  70635. get: function () {
  70636. return this._buttonRB;
  70637. },
  70638. set: function (value) {
  70639. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70640. },
  70641. enumerable: true,
  70642. configurable: true
  70643. });
  70644. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70645. /** Gets or sets value of left stick */
  70646. get: function () {
  70647. return this._buttonLeftStick;
  70648. },
  70649. set: function (value) {
  70650. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70651. },
  70652. enumerable: true,
  70653. configurable: true
  70654. });
  70655. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70656. /** Gets or sets value of right stick */
  70657. get: function () {
  70658. return this._buttonRightStick;
  70659. },
  70660. set: function (value) {
  70661. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70662. },
  70663. enumerable: true,
  70664. configurable: true
  70665. });
  70666. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70667. /** Gets or sets value of DPad up */
  70668. get: function () {
  70669. return this._dPadUp;
  70670. },
  70671. set: function (value) {
  70672. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70673. },
  70674. enumerable: true,
  70675. configurable: true
  70676. });
  70677. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70678. /** Gets or sets value of DPad down */
  70679. get: function () {
  70680. return this._dPadDown;
  70681. },
  70682. set: function (value) {
  70683. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70684. },
  70685. enumerable: true,
  70686. configurable: true
  70687. });
  70688. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70689. /** Gets or sets value of DPad left */
  70690. get: function () {
  70691. return this._dPadLeft;
  70692. },
  70693. set: function (value) {
  70694. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70695. },
  70696. enumerable: true,
  70697. configurable: true
  70698. });
  70699. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70700. /** Gets or sets value of DPad right */
  70701. get: function () {
  70702. return this._dPadRight;
  70703. },
  70704. set: function (value) {
  70705. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70706. },
  70707. enumerable: true,
  70708. configurable: true
  70709. });
  70710. /**
  70711. * Force the gamepad to synchronize with device values
  70712. */
  70713. Xbox360Pad.prototype.update = function () {
  70714. _super.prototype.update.call(this);
  70715. if (this._isXboxOnePad) {
  70716. this.buttonA = this.browserGamepad.buttons[0].value;
  70717. this.buttonB = this.browserGamepad.buttons[1].value;
  70718. this.buttonX = this.browserGamepad.buttons[2].value;
  70719. this.buttonY = this.browserGamepad.buttons[3].value;
  70720. this.buttonLB = this.browserGamepad.buttons[4].value;
  70721. this.buttonRB = this.browserGamepad.buttons[5].value;
  70722. this.leftTrigger = this.browserGamepad.axes[2];
  70723. this.rightTrigger = this.browserGamepad.axes[5];
  70724. this.buttonBack = this.browserGamepad.buttons[9].value;
  70725. this.buttonStart = this.browserGamepad.buttons[8].value;
  70726. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70727. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70728. this.dPadUp = this.browserGamepad.buttons[11].value;
  70729. this.dPadDown = this.browserGamepad.buttons[12].value;
  70730. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70731. this.dPadRight = this.browserGamepad.buttons[14].value;
  70732. }
  70733. else {
  70734. this.buttonA = this.browserGamepad.buttons[0].value;
  70735. this.buttonB = this.browserGamepad.buttons[1].value;
  70736. this.buttonX = this.browserGamepad.buttons[2].value;
  70737. this.buttonY = this.browserGamepad.buttons[3].value;
  70738. this.buttonLB = this.browserGamepad.buttons[4].value;
  70739. this.buttonRB = this.browserGamepad.buttons[5].value;
  70740. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70741. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70742. this.buttonBack = this.browserGamepad.buttons[8].value;
  70743. this.buttonStart = this.browserGamepad.buttons[9].value;
  70744. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70745. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70746. this.dPadUp = this.browserGamepad.buttons[12].value;
  70747. this.dPadDown = this.browserGamepad.buttons[13].value;
  70748. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70749. this.dPadRight = this.browserGamepad.buttons[15].value;
  70750. }
  70751. };
  70752. Xbox360Pad.prototype.dispose = function () {
  70753. _super.prototype.dispose.call(this);
  70754. this.onButtonDownObservable.clear();
  70755. this.onButtonUpObservable.clear();
  70756. this.onPadDownObservable.clear();
  70757. this.onPadUpObservable.clear();
  70758. };
  70759. return Xbox360Pad;
  70760. }(BABYLON.Gamepad));
  70761. BABYLON.Xbox360Pad = Xbox360Pad;
  70762. })(BABYLON || (BABYLON = {}));
  70763. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70764. var BABYLON;
  70765. (function (BABYLON) {
  70766. /**
  70767. * Defines the types of pose enabled controllers that are supported
  70768. */
  70769. var PoseEnabledControllerType;
  70770. (function (PoseEnabledControllerType) {
  70771. /**
  70772. * HTC Vive
  70773. */
  70774. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70775. /**
  70776. * Oculus Rift
  70777. */
  70778. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70779. /**
  70780. * Windows mixed reality
  70781. */
  70782. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70783. /**
  70784. * Samsung gear VR
  70785. */
  70786. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70787. /**
  70788. * Google Daydream
  70789. */
  70790. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70791. /**
  70792. * Generic
  70793. */
  70794. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70795. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70796. /**
  70797. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70798. */
  70799. var PoseEnabledControllerHelper = /** @class */ (function () {
  70800. function PoseEnabledControllerHelper() {
  70801. }
  70802. /**
  70803. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70804. * @param vrGamepad the gamepad to initialized
  70805. * @returns a vr controller of the type the gamepad identified as
  70806. */
  70807. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70808. // Oculus Touch
  70809. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70810. return new BABYLON.OculusTouchController(vrGamepad);
  70811. }
  70812. // Windows Mixed Reality controllers
  70813. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70814. return new BABYLON.WindowsMotionController(vrGamepad);
  70815. }
  70816. // HTC Vive
  70817. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70818. return new BABYLON.ViveController(vrGamepad);
  70819. }
  70820. // Samsung/Oculus Gear VR
  70821. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70822. return new BABYLON.GearVRController(vrGamepad);
  70823. }
  70824. // Google Daydream
  70825. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70826. return new BABYLON.DaydreamController(vrGamepad);
  70827. }
  70828. // Generic
  70829. else {
  70830. return new BABYLON.GenericController(vrGamepad);
  70831. }
  70832. };
  70833. return PoseEnabledControllerHelper;
  70834. }());
  70835. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70836. /**
  70837. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70838. */
  70839. var PoseEnabledController = /** @class */ (function (_super) {
  70840. __extends(PoseEnabledController, _super);
  70841. /**
  70842. * Creates a new PoseEnabledController from a gamepad
  70843. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70844. */
  70845. function PoseEnabledController(browserGamepad) {
  70846. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70847. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70848. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70849. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70850. /**
  70851. * The device position in babylon space
  70852. */
  70853. _this.devicePosition = BABYLON.Vector3.Zero();
  70854. /**
  70855. * The device rotation in babylon space
  70856. */
  70857. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70858. /**
  70859. * The scale factor of the device in babylon space
  70860. */
  70861. _this.deviceScaleFactor = 1;
  70862. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70863. /**
  70864. * Internal, matrix used to convert room space to babylon space
  70865. */
  70866. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70867. /**
  70868. * Node to be used when casting a ray from the controller
  70869. */
  70870. _this._pointingPoseNode = null;
  70871. _this._workingMatrix = BABYLON.Matrix.Identity();
  70872. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70873. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70874. _this.position = BABYLON.Vector3.Zero();
  70875. _this.rotationQuaternion = new BABYLON.Quaternion();
  70876. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70877. _this._calculatedRotation = new BABYLON.Quaternion();
  70878. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70879. return _this;
  70880. }
  70881. /**
  70882. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70883. */
  70884. PoseEnabledController.prototype.update = function () {
  70885. _super.prototype.update.call(this);
  70886. var pose = this.browserGamepad.pose;
  70887. this.updateFromDevice(pose);
  70888. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70889. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70890. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70891. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70892. if (this._mesh) {
  70893. this._mesh.position.copyFrom(this.devicePosition);
  70894. if (this._mesh.rotationQuaternion) {
  70895. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70896. }
  70897. }
  70898. };
  70899. /**
  70900. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70901. * @param poseData raw pose fromthe device
  70902. */
  70903. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70904. if (poseData) {
  70905. this.rawPose = poseData;
  70906. if (poseData.position) {
  70907. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70908. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70909. this._deviceRoomPosition.z *= -1;
  70910. }
  70911. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70912. this._calculatedPosition.addInPlace(this.position);
  70913. }
  70914. var pose = this.rawPose;
  70915. if (poseData.orientation && pose.orientation) {
  70916. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70917. if (this._mesh) {
  70918. if (this._mesh.getScene().useRightHandedSystem) {
  70919. this._deviceRoomRotationQuaternion.z *= -1;
  70920. this._deviceRoomRotationQuaternion.w *= -1;
  70921. }
  70922. else {
  70923. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70924. }
  70925. }
  70926. // if the camera is set, rotate to the camera's rotation
  70927. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70928. }
  70929. }
  70930. };
  70931. /**
  70932. * Attaches a mesh to the controller
  70933. * @param mesh the mesh to be attached
  70934. */
  70935. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70936. if (this._mesh) {
  70937. this._mesh.parent = null;
  70938. }
  70939. this._mesh = mesh;
  70940. if (this._poseControlledCamera) {
  70941. this._mesh.parent = this._poseControlledCamera;
  70942. }
  70943. if (!this._mesh.rotationQuaternion) {
  70944. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70945. }
  70946. };
  70947. /**
  70948. * Attaches the controllers mesh to a camera
  70949. * @param camera the camera the mesh should be attached to
  70950. */
  70951. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70952. this._poseControlledCamera = camera;
  70953. if (this._mesh) {
  70954. this._mesh.parent = this._poseControlledCamera;
  70955. }
  70956. };
  70957. /**
  70958. * Disposes of the controller
  70959. */
  70960. PoseEnabledController.prototype.dispose = function () {
  70961. if (this._mesh) {
  70962. this._mesh.dispose();
  70963. }
  70964. this._mesh = null;
  70965. _super.prototype.dispose.call(this);
  70966. };
  70967. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70968. /**
  70969. * The mesh that is attached to the controller
  70970. */
  70971. get: function () {
  70972. return this._mesh;
  70973. },
  70974. enumerable: true,
  70975. configurable: true
  70976. });
  70977. /**
  70978. * Gets the ray of the controller in the direction the controller is pointing
  70979. * @param length the length the resulting ray should be
  70980. * @returns a ray in the direction the controller is pointing
  70981. */
  70982. PoseEnabledController.prototype.getForwardRay = function (length) {
  70983. if (length === void 0) { length = 100; }
  70984. if (!this.mesh) {
  70985. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70986. }
  70987. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70988. var origin = m.getTranslation();
  70989. var forward = new BABYLON.Vector3(0, 0, -1);
  70990. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70991. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70992. return new BABYLON.Ray(origin, direction, length);
  70993. };
  70994. /**
  70995. * Name of the child mesh that can be used to cast a ray from the controller
  70996. */
  70997. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70998. return PoseEnabledController;
  70999. }(BABYLON.Gamepad));
  71000. BABYLON.PoseEnabledController = PoseEnabledController;
  71001. })(BABYLON || (BABYLON = {}));
  71002. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71003. var BABYLON;
  71004. (function (BABYLON) {
  71005. /**
  71006. * Defines the WebVRController object that represents controllers tracked in 3D space
  71007. */
  71008. var WebVRController = /** @class */ (function (_super) {
  71009. __extends(WebVRController, _super);
  71010. /**
  71011. * Creates a new WebVRController from a gamepad
  71012. * @param vrGamepad the gamepad that the WebVRController should be created from
  71013. */
  71014. function WebVRController(vrGamepad) {
  71015. var _this = _super.call(this, vrGamepad) || this;
  71016. // Observables
  71017. /**
  71018. * Fired when the trigger state has changed
  71019. */
  71020. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71021. /**
  71022. * Fired when the main button state has changed
  71023. */
  71024. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71025. /**
  71026. * Fired when the secondary button state has changed
  71027. */
  71028. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71029. /**
  71030. * Fired when the pad state has changed
  71031. */
  71032. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71033. /**
  71034. * Fired when controllers stick values have changed
  71035. */
  71036. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71037. /**
  71038. * X and Y axis corrisponding to the controllers joystick
  71039. */
  71040. _this.pad = { x: 0, y: 0 };
  71041. // avoid GC, store state in a tmp object
  71042. _this._changes = {
  71043. pressChanged: false,
  71044. touchChanged: false,
  71045. valueChanged: false,
  71046. changed: false
  71047. };
  71048. _this._buttons = new Array(vrGamepad.buttons.length);
  71049. _this.hand = vrGamepad.hand;
  71050. return _this;
  71051. }
  71052. /**
  71053. * Fired when a controller button's state has changed
  71054. * @param callback the callback containing the button that was modified
  71055. */
  71056. WebVRController.prototype.onButtonStateChange = function (callback) {
  71057. this._onButtonStateChange = callback;
  71058. };
  71059. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71060. /**
  71061. * The default controller model for the controller
  71062. */
  71063. get: function () {
  71064. return this._defaultModel;
  71065. },
  71066. enumerable: true,
  71067. configurable: true
  71068. });
  71069. /**
  71070. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71071. */
  71072. WebVRController.prototype.update = function () {
  71073. _super.prototype.update.call(this);
  71074. for (var index = 0; index < this._buttons.length; index++) {
  71075. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71076. }
  71077. ;
  71078. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71079. this.pad.x = this.leftStick.x;
  71080. this.pad.y = this.leftStick.y;
  71081. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71082. }
  71083. };
  71084. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71085. if (!newState) {
  71086. newState = {
  71087. pressed: false,
  71088. touched: false,
  71089. value: 0
  71090. };
  71091. }
  71092. if (!currentState) {
  71093. this._buttons[buttonIndex] = {
  71094. pressed: newState.pressed,
  71095. touched: newState.touched,
  71096. value: newState.value
  71097. };
  71098. return;
  71099. }
  71100. this._checkChanges(newState, currentState);
  71101. if (this._changes.changed) {
  71102. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71103. this._handleButtonChange(buttonIndex, newState, this._changes);
  71104. }
  71105. this._buttons[buttonIndex].pressed = newState.pressed;
  71106. this._buttons[buttonIndex].touched = newState.touched;
  71107. // oculus triggers are never 0, thou not touched.
  71108. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71109. };
  71110. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71111. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71112. this._changes.touchChanged = newState.touched !== currentState.touched;
  71113. this._changes.valueChanged = newState.value !== currentState.value;
  71114. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71115. return this._changes;
  71116. };
  71117. /**
  71118. * Disposes of th webVRCOntroller
  71119. */
  71120. WebVRController.prototype.dispose = function () {
  71121. _super.prototype.dispose.call(this);
  71122. this.onTriggerStateChangedObservable.clear();
  71123. this.onMainButtonStateChangedObservable.clear();
  71124. this.onSecondaryButtonStateChangedObservable.clear();
  71125. this.onPadStateChangedObservable.clear();
  71126. this.onPadValuesChangedObservable.clear();
  71127. };
  71128. return WebVRController;
  71129. }(BABYLON.PoseEnabledController));
  71130. BABYLON.WebVRController = WebVRController;
  71131. })(BABYLON || (BABYLON = {}));
  71132. //# sourceMappingURL=babylon.webVRController.js.map
  71133. var BABYLON;
  71134. (function (BABYLON) {
  71135. /**
  71136. * Oculus Touch Controller
  71137. */
  71138. var OculusTouchController = /** @class */ (function (_super) {
  71139. __extends(OculusTouchController, _super);
  71140. /**
  71141. * Creates a new OculusTouchController from a gamepad
  71142. * @param vrGamepad the gamepad that the controller should be created from
  71143. */
  71144. function OculusTouchController(vrGamepad) {
  71145. var _this = _super.call(this, vrGamepad) || this;
  71146. /**
  71147. * Fired when the secondary trigger on this controller is modified
  71148. */
  71149. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71150. /**
  71151. * Fired when the thumb rest on this controller is modified
  71152. */
  71153. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71154. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71155. return _this;
  71156. }
  71157. /**
  71158. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71159. * @param scene scene in which to add meshes
  71160. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71161. */
  71162. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71163. var _this = this;
  71164. var meshName;
  71165. // Hand
  71166. if (this.hand === 'left') {
  71167. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71168. }
  71169. else { // Right is the default if no hand is specified
  71170. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71171. }
  71172. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71173. /*
  71174. Parent Mesh name: oculus_touch_left
  71175. - body
  71176. - trigger
  71177. - thumbstick
  71178. - grip
  71179. - button_y
  71180. - button_x
  71181. - button_enter
  71182. */
  71183. _this._defaultModel = newMeshes[1];
  71184. _this.attachToMesh(_this._defaultModel);
  71185. if (meshLoaded) {
  71186. meshLoaded(_this._defaultModel);
  71187. }
  71188. });
  71189. };
  71190. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71191. /**
  71192. * Fired when the A button on this controller is modified
  71193. */
  71194. get: function () {
  71195. if (this.hand === 'right') {
  71196. return this.onMainButtonStateChangedObservable;
  71197. }
  71198. else {
  71199. throw new Error('No A button on left hand');
  71200. }
  71201. },
  71202. enumerable: true,
  71203. configurable: true
  71204. });
  71205. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71206. /**
  71207. * Fired when the B button on this controller is modified
  71208. */
  71209. get: function () {
  71210. if (this.hand === 'right') {
  71211. return this.onSecondaryButtonStateChangedObservable;
  71212. }
  71213. else {
  71214. throw new Error('No B button on left hand');
  71215. }
  71216. },
  71217. enumerable: true,
  71218. configurable: true
  71219. });
  71220. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71221. /**
  71222. * Fired when the X button on this controller is modified
  71223. */
  71224. get: function () {
  71225. if (this.hand === 'left') {
  71226. return this.onMainButtonStateChangedObservable;
  71227. }
  71228. else {
  71229. throw new Error('No X button on right hand');
  71230. }
  71231. },
  71232. enumerable: true,
  71233. configurable: true
  71234. });
  71235. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71236. /**
  71237. * Fired when the Y button on this controller is modified
  71238. */
  71239. get: function () {
  71240. if (this.hand === 'left') {
  71241. return this.onSecondaryButtonStateChangedObservable;
  71242. }
  71243. else {
  71244. throw new Error('No Y button on right hand');
  71245. }
  71246. },
  71247. enumerable: true,
  71248. configurable: true
  71249. });
  71250. /**
  71251. * Called once for each button that changed state since the last frame
  71252. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71253. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71254. * 2) secondary trigger (same)
  71255. * 3) A (right) X (left), touch, pressed = value
  71256. * 4) B / Y
  71257. * 5) thumb rest
  71258. * @param buttonIdx Which button index changed
  71259. * @param state New state of the button
  71260. * @param changes Which properties on the state changed since last frame
  71261. */
  71262. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71263. var notifyObject = state; //{ state: state, changes: changes };
  71264. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71265. switch (buttonIdx) {
  71266. case 0:
  71267. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71268. return;
  71269. case 1: // index trigger
  71270. if (this._defaultModel) {
  71271. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71272. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71273. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71274. }
  71275. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71276. return;
  71277. case 2: // secondary trigger
  71278. if (this._defaultModel) {
  71279. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71280. }
  71281. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71282. return;
  71283. case 3:
  71284. if (this._defaultModel) {
  71285. if (notifyObject.pressed) {
  71286. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71287. }
  71288. else {
  71289. (this._defaultModel.getChildren()[1]).position.y = 0;
  71290. }
  71291. }
  71292. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71293. return;
  71294. case 4:
  71295. if (this._defaultModel) {
  71296. if (notifyObject.pressed) {
  71297. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71298. }
  71299. else {
  71300. (this._defaultModel.getChildren()[2]).position.y = 0;
  71301. }
  71302. }
  71303. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71304. return;
  71305. case 5:
  71306. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71307. return;
  71308. }
  71309. };
  71310. /**
  71311. * Base Url for the controller model.
  71312. */
  71313. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71314. /**
  71315. * File name for the left controller model.
  71316. */
  71317. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71318. /**
  71319. * File name for the right controller model.
  71320. */
  71321. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71322. return OculusTouchController;
  71323. }(BABYLON.WebVRController));
  71324. BABYLON.OculusTouchController = OculusTouchController;
  71325. })(BABYLON || (BABYLON = {}));
  71326. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71327. var BABYLON;
  71328. (function (BABYLON) {
  71329. /**
  71330. * Vive Controller
  71331. */
  71332. var ViveController = /** @class */ (function (_super) {
  71333. __extends(ViveController, _super);
  71334. /**
  71335. * Creates a new ViveController from a gamepad
  71336. * @param vrGamepad the gamepad that the controller should be created from
  71337. */
  71338. function ViveController(vrGamepad) {
  71339. var _this = _super.call(this, vrGamepad) || this;
  71340. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71341. _this._invertLeftStickY = true;
  71342. return _this;
  71343. }
  71344. /**
  71345. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71346. * @param scene scene in which to add meshes
  71347. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71348. */
  71349. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71350. var _this = this;
  71351. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71352. /*
  71353. Parent Mesh name: ViveWand
  71354. - body
  71355. - r_gripper
  71356. - l_gripper
  71357. - menu_button
  71358. - system_button
  71359. - trackpad
  71360. - trigger
  71361. - LED
  71362. */
  71363. _this._defaultModel = newMeshes[1];
  71364. _this.attachToMesh(_this._defaultModel);
  71365. if (meshLoaded) {
  71366. meshLoaded(_this._defaultModel);
  71367. }
  71368. });
  71369. };
  71370. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71371. /**
  71372. * Fired when the left button on this controller is modified
  71373. */
  71374. get: function () {
  71375. return this.onMainButtonStateChangedObservable;
  71376. },
  71377. enumerable: true,
  71378. configurable: true
  71379. });
  71380. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71381. /**
  71382. * Fired when the right button on this controller is modified
  71383. */
  71384. get: function () {
  71385. return this.onMainButtonStateChangedObservable;
  71386. },
  71387. enumerable: true,
  71388. configurable: true
  71389. });
  71390. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71391. /**
  71392. * Fired when the menu button on this controller is modified
  71393. */
  71394. get: function () {
  71395. return this.onSecondaryButtonStateChangedObservable;
  71396. },
  71397. enumerable: true,
  71398. configurable: true
  71399. });
  71400. /**
  71401. * Called once for each button that changed state since the last frame
  71402. * Vive mapping:
  71403. * 0: touchpad
  71404. * 1: trigger
  71405. * 2: left AND right buttons
  71406. * 3: menu button
  71407. * @param buttonIdx Which button index changed
  71408. * @param state New state of the button
  71409. * @param changes Which properties on the state changed since last frame
  71410. */
  71411. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71412. var notifyObject = state; //{ state: state, changes: changes };
  71413. switch (buttonIdx) {
  71414. case 0:
  71415. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71416. return;
  71417. case 1: // index trigger
  71418. if (this._defaultModel) {
  71419. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71420. }
  71421. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71422. return;
  71423. case 2: // left AND right button
  71424. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71425. return;
  71426. case 3:
  71427. if (this._defaultModel) {
  71428. if (notifyObject.pressed) {
  71429. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71430. }
  71431. else {
  71432. (this._defaultModel.getChildren()[2]).position.y = 0;
  71433. }
  71434. }
  71435. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71436. return;
  71437. }
  71438. };
  71439. /**
  71440. * Base Url for the controller model.
  71441. */
  71442. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71443. /**
  71444. * File name for the controller model.
  71445. */
  71446. ViveController.MODEL_FILENAME = 'wand.babylon';
  71447. return ViveController;
  71448. }(BABYLON.WebVRController));
  71449. BABYLON.ViveController = ViveController;
  71450. })(BABYLON || (BABYLON = {}));
  71451. //# sourceMappingURL=babylon.viveController.js.map
  71452. var BABYLON;
  71453. (function (BABYLON) {
  71454. /**
  71455. * Generic Controller
  71456. */
  71457. var GenericController = /** @class */ (function (_super) {
  71458. __extends(GenericController, _super);
  71459. /**
  71460. * Creates a new GenericController from a gamepad
  71461. * @param vrGamepad the gamepad that the controller should be created from
  71462. */
  71463. function GenericController(vrGamepad) {
  71464. return _super.call(this, vrGamepad) || this;
  71465. }
  71466. /**
  71467. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71468. * @param scene scene in which to add meshes
  71469. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71470. */
  71471. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71472. var _this = this;
  71473. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71474. _this._defaultModel = newMeshes[1];
  71475. _this.attachToMesh(_this._defaultModel);
  71476. if (meshLoaded) {
  71477. meshLoaded(_this._defaultModel);
  71478. }
  71479. });
  71480. };
  71481. /**
  71482. * Called once for each button that changed state since the last frame
  71483. * @param buttonIdx Which button index changed
  71484. * @param state New state of the button
  71485. * @param changes Which properties on the state changed since last frame
  71486. */
  71487. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71488. console.log("Button id: " + buttonIdx + "state: ");
  71489. console.dir(state);
  71490. };
  71491. /**
  71492. * Base Url for the controller model.
  71493. */
  71494. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71495. /**
  71496. * File name for the controller model.
  71497. */
  71498. GenericController.MODEL_FILENAME = 'generic.babylon';
  71499. return GenericController;
  71500. }(BABYLON.WebVRController));
  71501. BABYLON.GenericController = GenericController;
  71502. })(BABYLON || (BABYLON = {}));
  71503. //# sourceMappingURL=babylon.genericController.js.map
  71504. var BABYLON;
  71505. (function (BABYLON) {
  71506. /**
  71507. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71508. */
  71509. var LoadedMeshInfo = /** @class */ (function () {
  71510. function LoadedMeshInfo() {
  71511. /**
  71512. * Map of the button meshes contained in the controller
  71513. */
  71514. this.buttonMeshes = {};
  71515. /**
  71516. * Map of the axis meshes contained in the controller
  71517. */
  71518. this.axisMeshes = {};
  71519. }
  71520. return LoadedMeshInfo;
  71521. }());
  71522. /**
  71523. * Defines the WindowsMotionController object that the state of the windows motion controller
  71524. */
  71525. var WindowsMotionController = /** @class */ (function (_super) {
  71526. __extends(WindowsMotionController, _super);
  71527. /**
  71528. * Creates a new WindowsMotionController from a gamepad
  71529. * @param vrGamepad the gamepad that the controller should be created from
  71530. */
  71531. function WindowsMotionController(vrGamepad) {
  71532. var _this = _super.call(this, vrGamepad) || this;
  71533. _this._mapping = {
  71534. // Semantic button names
  71535. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71536. // A mapping of the button name to glTF model node name
  71537. // that should be transformed by button value.
  71538. buttonMeshNames: {
  71539. 'trigger': 'SELECT',
  71540. 'menu': 'MENU',
  71541. 'grip': 'GRASP',
  71542. 'thumbstick': 'THUMBSTICK_PRESS',
  71543. 'trackpad': 'TOUCHPAD_PRESS'
  71544. },
  71545. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71546. buttonObservableNames: {
  71547. 'trigger': 'onTriggerStateChangedObservable',
  71548. 'menu': 'onSecondaryButtonStateChangedObservable',
  71549. 'grip': 'onMainButtonStateChangedObservable',
  71550. 'thumbstick': 'onPadStateChangedObservable',
  71551. 'trackpad': 'onTrackpadChangedObservable'
  71552. },
  71553. // A mapping of the axis name to glTF model node name
  71554. // that should be transformed by axis value.
  71555. // This array mirrors the browserGamepad.axes array, such that
  71556. // the mesh corresponding to axis 0 is in this array index 0.
  71557. axisMeshNames: [
  71558. 'THUMBSTICK_X',
  71559. 'THUMBSTICK_Y',
  71560. 'TOUCHPAD_TOUCH_X',
  71561. 'TOUCHPAD_TOUCH_Y'
  71562. ],
  71563. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71564. };
  71565. /**
  71566. * Fired when the trackpad on this controller is clicked
  71567. */
  71568. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71569. /**
  71570. * Fired when the trackpad on this controller is modified
  71571. */
  71572. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71573. /**
  71574. * The current x and y values of this controller's trackpad
  71575. */
  71576. _this.trackpad = { x: 0, y: 0 };
  71577. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71578. _this._loadedMeshInfo = null;
  71579. return _this;
  71580. }
  71581. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71582. /**
  71583. * Fired when the trigger on this controller is modified
  71584. */
  71585. get: function () {
  71586. return this.onTriggerStateChangedObservable;
  71587. },
  71588. enumerable: true,
  71589. configurable: true
  71590. });
  71591. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71592. /**
  71593. * Fired when the menu button on this controller is modified
  71594. */
  71595. get: function () {
  71596. return this.onSecondaryButtonStateChangedObservable;
  71597. },
  71598. enumerable: true,
  71599. configurable: true
  71600. });
  71601. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71602. /**
  71603. * Fired when the grip button on this controller is modified
  71604. */
  71605. get: function () {
  71606. return this.onMainButtonStateChangedObservable;
  71607. },
  71608. enumerable: true,
  71609. configurable: true
  71610. });
  71611. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71612. /**
  71613. * Fired when the thumbstick button on this controller is modified
  71614. */
  71615. get: function () {
  71616. return this.onPadStateChangedObservable;
  71617. },
  71618. enumerable: true,
  71619. configurable: true
  71620. });
  71621. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71622. /**
  71623. * Fired when the touchpad button on this controller is modified
  71624. */
  71625. get: function () {
  71626. return this.onTrackpadChangedObservable;
  71627. },
  71628. enumerable: true,
  71629. configurable: true
  71630. });
  71631. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71632. /**
  71633. * Fired when the touchpad values on this controller are modified
  71634. */
  71635. get: function () {
  71636. return this.onTrackpadValuesChangedObservable;
  71637. },
  71638. enumerable: true,
  71639. configurable: true
  71640. });
  71641. /**
  71642. * Called once per frame by the engine.
  71643. */
  71644. WindowsMotionController.prototype.update = function () {
  71645. _super.prototype.update.call(this);
  71646. if (this.browserGamepad.axes) {
  71647. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71648. this.trackpad.x = this.browserGamepad["axes"][2];
  71649. this.trackpad.y = this.browserGamepad["axes"][3];
  71650. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71651. }
  71652. // Only need to animate axes if there is a loaded mesh
  71653. if (this._loadedMeshInfo) {
  71654. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71655. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71656. }
  71657. }
  71658. }
  71659. };
  71660. /**
  71661. * Called once for each button that changed state since the last frame
  71662. * @param buttonIdx Which button index changed
  71663. * @param state New state of the button
  71664. * @param changes Which properties on the state changed since last frame
  71665. */
  71666. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71667. var buttonName = this._mapping.buttons[buttonIdx];
  71668. if (!buttonName) {
  71669. return;
  71670. }
  71671. // Only emit events for buttons that we know how to map from index to name
  71672. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71673. if (observable) {
  71674. observable.notifyObservers(state);
  71675. }
  71676. this._lerpButtonTransform(buttonName, state.value);
  71677. };
  71678. /**
  71679. * Moves the buttons on the controller mesh based on their current state
  71680. * @param buttonName the name of the button to move
  71681. * @param buttonValue the value of the button which determines the buttons new position
  71682. */
  71683. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71684. // If there is no loaded mesh, there is nothing to transform.
  71685. if (!this._loadedMeshInfo) {
  71686. return;
  71687. }
  71688. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71689. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71690. return;
  71691. }
  71692. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71693. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71694. };
  71695. /**
  71696. * Moves the axis on the controller mesh based on its current state
  71697. * @param axis the index of the axis
  71698. * @param axisValue the value of the axis which determines the meshes new position
  71699. * @hidden
  71700. */
  71701. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71702. if (!this._loadedMeshInfo) {
  71703. return;
  71704. }
  71705. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71706. if (!meshInfo) {
  71707. return;
  71708. }
  71709. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71710. return;
  71711. }
  71712. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71713. var lerpValue = axisValue * 0.5 + 0.5;
  71714. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71715. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71716. };
  71717. /**
  71718. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71719. * @param scene scene in which to add meshes
  71720. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71721. */
  71722. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71723. var _this = this;
  71724. if (forceDefault === void 0) { forceDefault = false; }
  71725. var path;
  71726. var filename;
  71727. // Checking if GLB loader is present
  71728. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71729. // Determine the device specific folder based on the ID suffix
  71730. var device = 'default';
  71731. if (this.id && !forceDefault) {
  71732. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71733. device = ((match && match[0]) || device);
  71734. }
  71735. // Hand
  71736. if (this.hand === 'left') {
  71737. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71738. }
  71739. else { // Right is the default if no hand is specified
  71740. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71741. }
  71742. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71743. }
  71744. else {
  71745. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71746. path = BABYLON.GenericController.MODEL_BASE_URL;
  71747. filename = BABYLON.GenericController.MODEL_FILENAME;
  71748. }
  71749. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71750. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71751. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71752. if (!_this._loadedMeshInfo) {
  71753. return;
  71754. }
  71755. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71756. _this.attachToMesh(_this._defaultModel);
  71757. if (meshLoaded) {
  71758. meshLoaded(_this._defaultModel);
  71759. }
  71760. }, null, function (scene, message) {
  71761. BABYLON.Tools.Log(message);
  71762. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71763. if (!forceDefault) {
  71764. _this.initControllerMesh(scene, meshLoaded, true);
  71765. }
  71766. });
  71767. };
  71768. /**
  71769. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71770. * can be transformed by button presses and axes values, based on this._mapping.
  71771. *
  71772. * @param scene scene in which the meshes exist
  71773. * @param meshes list of meshes that make up the controller model to process
  71774. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71775. */
  71776. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71777. var loadedMeshInfo = null;
  71778. // Create a new mesh to contain the glTF hierarchy
  71779. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71780. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71781. var childMesh = null;
  71782. for (var i = 0; i < meshes.length; i++) {
  71783. var mesh = meshes[i];
  71784. if (!mesh.parent) {
  71785. // Exclude controller meshes from picking results
  71786. mesh.isPickable = false;
  71787. // Handle root node, attach to the new parentMesh
  71788. childMesh = mesh;
  71789. break;
  71790. }
  71791. }
  71792. if (childMesh) {
  71793. childMesh.setParent(parentMesh);
  71794. // Create our mesh info. Note that this method will always return non-null.
  71795. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71796. }
  71797. else {
  71798. BABYLON.Tools.Warn('Could not find root node in model file.');
  71799. }
  71800. return loadedMeshInfo;
  71801. };
  71802. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71803. var loadedMeshInfo = new LoadedMeshInfo();
  71804. var i;
  71805. loadedMeshInfo.rootNode = rootNode;
  71806. // Reset the caches
  71807. loadedMeshInfo.buttonMeshes = {};
  71808. loadedMeshInfo.axisMeshes = {};
  71809. // Button Meshes
  71810. for (i = 0; i < this._mapping.buttons.length; i++) {
  71811. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71812. if (!buttonMeshName) {
  71813. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71814. continue;
  71815. }
  71816. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71817. if (!buttonMesh) {
  71818. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71819. continue;
  71820. }
  71821. var buttonMeshInfo = {
  71822. index: i,
  71823. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71824. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71825. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71826. };
  71827. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71828. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71829. }
  71830. else {
  71831. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71832. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71833. '(VALUE: ' + !!buttonMeshInfo.value +
  71834. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71835. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71836. ')');
  71837. }
  71838. }
  71839. // Axis Meshes
  71840. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71841. var axisMeshName = this._mapping.axisMeshNames[i];
  71842. if (!axisMeshName) {
  71843. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71844. continue;
  71845. }
  71846. var axisMesh = getChildByName(rootNode, axisMeshName);
  71847. if (!axisMesh) {
  71848. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71849. continue;
  71850. }
  71851. var axisMeshInfo = {
  71852. index: i,
  71853. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71854. min: getImmediateChildByName(axisMesh, 'MIN'),
  71855. max: getImmediateChildByName(axisMesh, 'MAX')
  71856. };
  71857. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71858. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71859. }
  71860. else {
  71861. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71862. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71863. '(VALUE: ' + !!axisMeshInfo.value +
  71864. ', MIN: ' + !!axisMeshInfo.min +
  71865. ', MAX:' + !!axisMeshInfo.max +
  71866. ')');
  71867. }
  71868. }
  71869. // Pointing Ray
  71870. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71871. if (!loadedMeshInfo.pointingPoseNode) {
  71872. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71873. }
  71874. return loadedMeshInfo;
  71875. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71876. function getChildByName(node, name) {
  71877. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71878. }
  71879. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71880. function getImmediateChildByName(node, name) {
  71881. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71882. }
  71883. };
  71884. /**
  71885. * Gets the ray of the controller in the direction the controller is pointing
  71886. * @param length the length the resulting ray should be
  71887. * @returns a ray in the direction the controller is pointing
  71888. */
  71889. WindowsMotionController.prototype.getForwardRay = function (length) {
  71890. if (length === void 0) { length = 100; }
  71891. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71892. return _super.prototype.getForwardRay.call(this, length);
  71893. }
  71894. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71895. var origin = m.getTranslation();
  71896. var forward = new BABYLON.Vector3(0, 0, -1);
  71897. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71898. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71899. return new BABYLON.Ray(origin, direction, length);
  71900. };
  71901. /**
  71902. * Disposes of the controller
  71903. */
  71904. WindowsMotionController.prototype.dispose = function () {
  71905. _super.prototype.dispose.call(this);
  71906. this.onTrackpadChangedObservable.clear();
  71907. };
  71908. /**
  71909. * The base url used to load the left and right controller models
  71910. */
  71911. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71912. /**
  71913. * The name of the left controller model file
  71914. */
  71915. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71916. /**
  71917. * The name of the right controller model file
  71918. */
  71919. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71920. /**
  71921. * The controller name prefix for this controller type
  71922. */
  71923. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71924. /**
  71925. * The controller id pattern for this controller type
  71926. */
  71927. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71928. return WindowsMotionController;
  71929. }(BABYLON.WebVRController));
  71930. BABYLON.WindowsMotionController = WindowsMotionController;
  71931. })(BABYLON || (BABYLON = {}));
  71932. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71933. var BABYLON;
  71934. (function (BABYLON) {
  71935. /**
  71936. * Gear VR Controller
  71937. */
  71938. var GearVRController = /** @class */ (function (_super) {
  71939. __extends(GearVRController, _super);
  71940. /**
  71941. * Creates a new GearVRController from a gamepad
  71942. * @param vrGamepad the gamepad that the controller should be created from
  71943. */
  71944. function GearVRController(vrGamepad) {
  71945. var _this = _super.call(this, vrGamepad) || this;
  71946. _this._buttonIndexToObservableNameMap = [
  71947. 'onTrackpadChangedObservable',
  71948. 'onTriggerStateChangedObservable' // Trigger
  71949. ];
  71950. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71951. return _this;
  71952. }
  71953. /**
  71954. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71955. * @param scene scene in which to add meshes
  71956. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71957. */
  71958. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71959. var _this = this;
  71960. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71961. _this._defaultModel = newMeshes[1];
  71962. _this.attachToMesh(_this._defaultModel);
  71963. if (meshLoaded) {
  71964. meshLoaded(_this._defaultModel);
  71965. }
  71966. });
  71967. };
  71968. /**
  71969. * Called once for each button that changed state since the last frame
  71970. * @param buttonIdx Which button index changed
  71971. * @param state New state of the button
  71972. * @param changes Which properties on the state changed since last frame
  71973. */
  71974. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71975. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71976. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71977. // Only emit events for buttons that we know how to map from index to observable
  71978. var observable = this[observableName];
  71979. if (observable) {
  71980. observable.notifyObservers(state);
  71981. }
  71982. }
  71983. };
  71984. /**
  71985. * Base Url for the controller model.
  71986. */
  71987. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71988. /**
  71989. * File name for the controller model.
  71990. */
  71991. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71992. /**
  71993. * Gamepad Id prefix used to identify this controller.
  71994. */
  71995. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71996. return GearVRController;
  71997. }(BABYLON.WebVRController));
  71998. BABYLON.GearVRController = GearVRController;
  71999. })(BABYLON || (BABYLON = {}));
  72000. //# sourceMappingURL=babylon.gearVRController.js.map
  72001. var BABYLON;
  72002. (function (BABYLON) {
  72003. /**
  72004. * Google Daydream controller
  72005. */
  72006. var DaydreamController = /** @class */ (function (_super) {
  72007. __extends(DaydreamController, _super);
  72008. /**
  72009. * Creates a new DaydreamController from a gamepad
  72010. * @param vrGamepad the gamepad that the controller should be created from
  72011. */
  72012. function DaydreamController(vrGamepad) {
  72013. var _this = _super.call(this, vrGamepad) || this;
  72014. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72015. return _this;
  72016. }
  72017. /**
  72018. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72019. * @param scene scene in which to add meshes
  72020. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72021. */
  72022. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72023. var _this = this;
  72024. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72025. _this._defaultModel = newMeshes[1];
  72026. _this.attachToMesh(_this._defaultModel);
  72027. if (meshLoaded) {
  72028. meshLoaded(_this._defaultModel);
  72029. }
  72030. });
  72031. };
  72032. /**
  72033. * Called once for each button that changed state since the last frame
  72034. * @param buttonIdx Which button index changed
  72035. * @param state New state of the button
  72036. * @param changes Which properties on the state changed since last frame
  72037. */
  72038. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72039. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72040. if (buttonIdx === 0) {
  72041. var observable = this.onTriggerStateChangedObservable;
  72042. if (observable) {
  72043. observable.notifyObservers(state);
  72044. }
  72045. }
  72046. else {
  72047. // If the app or home buttons are ever made available
  72048. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72049. }
  72050. };
  72051. /**
  72052. * Base Url for the controller model.
  72053. */
  72054. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72055. /**
  72056. * File name for the controller model.
  72057. */
  72058. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72059. /**
  72060. * Gamepad Id prefix used to identify Daydream Controller.
  72061. */
  72062. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72063. return DaydreamController;
  72064. }(BABYLON.WebVRController));
  72065. BABYLON.DaydreamController = DaydreamController;
  72066. })(BABYLON || (BABYLON = {}));
  72067. //# sourceMappingURL=babylon.daydreamController.js.map
  72068. var BABYLON;
  72069. (function (BABYLON) {
  72070. var FollowCamera = /** @class */ (function (_super) {
  72071. __extends(FollowCamera, _super);
  72072. function FollowCamera(name, position, scene, lockedTarget) {
  72073. if (lockedTarget === void 0) { lockedTarget = null; }
  72074. var _this = _super.call(this, name, position, scene) || this;
  72075. _this.radius = 12;
  72076. _this.rotationOffset = 0;
  72077. _this.heightOffset = 4;
  72078. _this.cameraAcceleration = 0.05;
  72079. _this.maxCameraSpeed = 20;
  72080. _this.lockedTarget = lockedTarget;
  72081. return _this;
  72082. }
  72083. FollowCamera.prototype.getRadians = function (degrees) {
  72084. return degrees * Math.PI / 180;
  72085. };
  72086. FollowCamera.prototype.follow = function (cameraTarget) {
  72087. if (!cameraTarget)
  72088. return;
  72089. var yRotation;
  72090. if (cameraTarget.rotationQuaternion) {
  72091. var rotMatrix = new BABYLON.Matrix();
  72092. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72093. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72094. }
  72095. else {
  72096. yRotation = cameraTarget.rotation.y;
  72097. }
  72098. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72099. var targetPosition = cameraTarget.getAbsolutePosition();
  72100. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72101. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72102. var dx = targetX - this.position.x;
  72103. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72104. var dz = (targetZ) - this.position.z;
  72105. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72106. var vy = dy * this.cameraAcceleration;
  72107. var vz = dz * this.cameraAcceleration * 2;
  72108. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72109. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72110. }
  72111. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72112. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72113. }
  72114. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72115. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72116. }
  72117. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72118. this.setTarget(targetPosition);
  72119. };
  72120. FollowCamera.prototype._checkInputs = function () {
  72121. _super.prototype._checkInputs.call(this);
  72122. if (this.lockedTarget) {
  72123. this.follow(this.lockedTarget);
  72124. }
  72125. };
  72126. FollowCamera.prototype.getClassName = function () {
  72127. return "FollowCamera";
  72128. };
  72129. __decorate([
  72130. BABYLON.serialize()
  72131. ], FollowCamera.prototype, "radius", void 0);
  72132. __decorate([
  72133. BABYLON.serialize()
  72134. ], FollowCamera.prototype, "rotationOffset", void 0);
  72135. __decorate([
  72136. BABYLON.serialize()
  72137. ], FollowCamera.prototype, "heightOffset", void 0);
  72138. __decorate([
  72139. BABYLON.serialize()
  72140. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72141. __decorate([
  72142. BABYLON.serialize()
  72143. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72144. __decorate([
  72145. BABYLON.serializeAsMeshReference("lockedTargetId")
  72146. ], FollowCamera.prototype, "lockedTarget", void 0);
  72147. return FollowCamera;
  72148. }(BABYLON.TargetCamera));
  72149. BABYLON.FollowCamera = FollowCamera;
  72150. var ArcFollowCamera = /** @class */ (function (_super) {
  72151. __extends(ArcFollowCamera, _super);
  72152. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72153. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72154. _this.alpha = alpha;
  72155. _this.beta = beta;
  72156. _this.radius = radius;
  72157. _this.target = target;
  72158. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72159. _this.follow();
  72160. return _this;
  72161. }
  72162. ArcFollowCamera.prototype.follow = function () {
  72163. if (!this.target) {
  72164. return;
  72165. }
  72166. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72167. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72168. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72169. var targetPosition = this.target.getAbsolutePosition();
  72170. this.position = targetPosition.add(this._cartesianCoordinates);
  72171. this.setTarget(targetPosition);
  72172. };
  72173. ArcFollowCamera.prototype._checkInputs = function () {
  72174. _super.prototype._checkInputs.call(this);
  72175. this.follow();
  72176. };
  72177. ArcFollowCamera.prototype.getClassName = function () {
  72178. return "ArcFollowCamera";
  72179. };
  72180. return ArcFollowCamera;
  72181. }(BABYLON.TargetCamera));
  72182. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72183. })(BABYLON || (BABYLON = {}));
  72184. //# sourceMappingURL=babylon.followCamera.js.map
  72185. var BABYLON;
  72186. (function (BABYLON) {
  72187. // We're mainly based on the logic defined into the FreeCamera code
  72188. var UniversalCamera = /** @class */ (function (_super) {
  72189. __extends(UniversalCamera, _super);
  72190. //-- end properties for backward compatibility for inputs
  72191. function UniversalCamera(name, position, scene) {
  72192. var _this = _super.call(this, name, position, scene) || this;
  72193. _this.inputs.addGamepad();
  72194. return _this;
  72195. }
  72196. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72197. //-- Begin properties for backward compatibility for inputs
  72198. get: function () {
  72199. var gamepad = this.inputs.attached["gamepad"];
  72200. if (gamepad)
  72201. return gamepad.gamepadAngularSensibility;
  72202. return 0;
  72203. },
  72204. set: function (value) {
  72205. var gamepad = this.inputs.attached["gamepad"];
  72206. if (gamepad)
  72207. gamepad.gamepadAngularSensibility = value;
  72208. },
  72209. enumerable: true,
  72210. configurable: true
  72211. });
  72212. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72213. get: function () {
  72214. var gamepad = this.inputs.attached["gamepad"];
  72215. if (gamepad)
  72216. return gamepad.gamepadMoveSensibility;
  72217. return 0;
  72218. },
  72219. set: function (value) {
  72220. var gamepad = this.inputs.attached["gamepad"];
  72221. if (gamepad)
  72222. gamepad.gamepadMoveSensibility = value;
  72223. },
  72224. enumerable: true,
  72225. configurable: true
  72226. });
  72227. UniversalCamera.prototype.getClassName = function () {
  72228. return "UniversalCamera";
  72229. };
  72230. return UniversalCamera;
  72231. }(BABYLON.TouchCamera));
  72232. BABYLON.UniversalCamera = UniversalCamera;
  72233. })(BABYLON || (BABYLON = {}));
  72234. //# sourceMappingURL=babylon.universalCamera.js.map
  72235. var BABYLON;
  72236. (function (BABYLON) {
  72237. // We're mainly based on the logic defined into the FreeCamera code
  72238. var GamepadCamera = /** @class */ (function (_super) {
  72239. __extends(GamepadCamera, _super);
  72240. //-- end properties for backward compatibility for inputs
  72241. function GamepadCamera(name, position, scene) {
  72242. return _super.call(this, name, position, scene) || this;
  72243. }
  72244. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72245. //-- Begin properties for backward compatibility for inputs
  72246. get: function () {
  72247. var gamepad = this.inputs.attached["gamepad"];
  72248. if (gamepad)
  72249. return gamepad.gamepadAngularSensibility;
  72250. return 0;
  72251. },
  72252. set: function (value) {
  72253. var gamepad = this.inputs.attached["gamepad"];
  72254. if (gamepad)
  72255. gamepad.gamepadAngularSensibility = value;
  72256. },
  72257. enumerable: true,
  72258. configurable: true
  72259. });
  72260. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72261. get: function () {
  72262. var gamepad = this.inputs.attached["gamepad"];
  72263. if (gamepad)
  72264. return gamepad.gamepadMoveSensibility;
  72265. return 0;
  72266. },
  72267. set: function (value) {
  72268. var gamepad = this.inputs.attached["gamepad"];
  72269. if (gamepad)
  72270. gamepad.gamepadMoveSensibility = value;
  72271. },
  72272. enumerable: true,
  72273. configurable: true
  72274. });
  72275. GamepadCamera.prototype.getClassName = function () {
  72276. return "GamepadCamera";
  72277. };
  72278. return GamepadCamera;
  72279. }(BABYLON.UniversalCamera));
  72280. BABYLON.GamepadCamera = GamepadCamera;
  72281. })(BABYLON || (BABYLON = {}));
  72282. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72283. var BABYLON;
  72284. (function (BABYLON) {
  72285. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72286. function PostProcessRenderPipelineManager() {
  72287. this._renderPipelines = {};
  72288. }
  72289. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72290. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72291. };
  72292. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72293. if (unique === void 0) { unique = false; }
  72294. var renderPipeline = this._renderPipelines[renderPipelineName];
  72295. if (!renderPipeline) {
  72296. return;
  72297. }
  72298. renderPipeline._attachCameras(cameras, unique);
  72299. };
  72300. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72301. var renderPipeline = this._renderPipelines[renderPipelineName];
  72302. if (!renderPipeline) {
  72303. return;
  72304. }
  72305. renderPipeline._detachCameras(cameras);
  72306. };
  72307. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72308. var renderPipeline = this._renderPipelines[renderPipelineName];
  72309. if (!renderPipeline) {
  72310. return;
  72311. }
  72312. renderPipeline._enableEffect(renderEffectName, cameras);
  72313. };
  72314. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72315. var renderPipeline = this._renderPipelines[renderPipelineName];
  72316. if (!renderPipeline) {
  72317. return;
  72318. }
  72319. renderPipeline._disableEffect(renderEffectName, cameras);
  72320. };
  72321. PostProcessRenderPipelineManager.prototype.update = function () {
  72322. for (var renderPipelineName in this._renderPipelines) {
  72323. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72324. var pipeline = this._renderPipelines[renderPipelineName];
  72325. if (!pipeline.isSupported) {
  72326. pipeline.dispose();
  72327. delete this._renderPipelines[renderPipelineName];
  72328. }
  72329. else {
  72330. pipeline._update();
  72331. }
  72332. }
  72333. }
  72334. };
  72335. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72336. for (var renderPipelineName in this._renderPipelines) {
  72337. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72338. var pipeline = this._renderPipelines[renderPipelineName];
  72339. pipeline._rebuild();
  72340. }
  72341. }
  72342. };
  72343. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72344. for (var renderPipelineName in this._renderPipelines) {
  72345. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72346. var pipeline = this._renderPipelines[renderPipelineName];
  72347. pipeline.dispose();
  72348. }
  72349. }
  72350. };
  72351. return PostProcessRenderPipelineManager;
  72352. }());
  72353. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72354. })(BABYLON || (BABYLON = {}));
  72355. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72356. var BABYLON;
  72357. (function (BABYLON) {
  72358. /**
  72359. * This represents a set of one or more post processes in Babylon.
  72360. * A post process can be used to apply a shader to a texture after it is rendered.
  72361. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72362. */
  72363. var PostProcessRenderEffect = /** @class */ (function () {
  72364. /**
  72365. * Instantiates a post process render effect.
  72366. * A post process can be used to apply a shader to a texture after it is rendered.
  72367. * @param engine The engine the effect is tied to
  72368. * @param name The name of the effect
  72369. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72370. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72371. */
  72372. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72373. this._name = name;
  72374. this._singleInstance = singleInstance || true;
  72375. this._getPostProcesses = getPostProcesses;
  72376. this._cameras = {};
  72377. this._indicesForCamera = {};
  72378. this._postProcesses = {};
  72379. }
  72380. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72381. /**
  72382. * Checks if all the post processes in the effect are supported.
  72383. */
  72384. get: function () {
  72385. for (var index in this._postProcesses) {
  72386. if (this._postProcesses.hasOwnProperty(index)) {
  72387. var pps = this._postProcesses[index];
  72388. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72389. if (!pps[ppIndex].isSupported) {
  72390. return false;
  72391. }
  72392. }
  72393. }
  72394. }
  72395. return true;
  72396. },
  72397. enumerable: true,
  72398. configurable: true
  72399. });
  72400. /**
  72401. * Updates the current state of the effect
  72402. */
  72403. PostProcessRenderEffect.prototype._update = function () {
  72404. };
  72405. /**
  72406. * Attaches the effect on cameras
  72407. * @param cameras The camera to attach to.
  72408. */
  72409. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72410. var _this = this;
  72411. var cameraKey;
  72412. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72413. if (!cams) {
  72414. return;
  72415. }
  72416. for (var i = 0; i < cams.length; i++) {
  72417. var camera = cams[i];
  72418. var cameraName = camera.name;
  72419. if (this._singleInstance) {
  72420. cameraKey = 0;
  72421. }
  72422. else {
  72423. cameraKey = cameraName;
  72424. }
  72425. if (!this._postProcesses[cameraKey]) {
  72426. var postProcess = this._getPostProcesses();
  72427. if (postProcess) {
  72428. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72429. }
  72430. }
  72431. if (!this._indicesForCamera[cameraName]) {
  72432. this._indicesForCamera[cameraName] = [];
  72433. }
  72434. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72435. var index = camera.attachPostProcess(postProcess);
  72436. _this._indicesForCamera[cameraName].push(index);
  72437. });
  72438. if (!this._cameras[cameraName]) {
  72439. this._cameras[cameraName] = camera;
  72440. }
  72441. }
  72442. };
  72443. /**
  72444. * Detatches the effect on cameras
  72445. * @param cameras The camera to detatch from.
  72446. */
  72447. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72448. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72449. if (!cams) {
  72450. return;
  72451. }
  72452. for (var i = 0; i < cams.length; i++) {
  72453. var camera = cams[i];
  72454. var cameraName = camera.name;
  72455. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72456. camera.detachPostProcess(postProcess);
  72457. });
  72458. if (this._cameras[cameraName]) {
  72459. //this._indicesForCamera.splice(index, 1);
  72460. this._cameras[cameraName] = null;
  72461. }
  72462. }
  72463. };
  72464. /**
  72465. * Enables the effect on given cameras
  72466. * @param cameras The camera to enable.
  72467. */
  72468. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72469. var _this = this;
  72470. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72471. if (!cams) {
  72472. return;
  72473. }
  72474. for (var i = 0; i < cams.length; i++) {
  72475. var camera = cams[i];
  72476. var cameraName = camera.name;
  72477. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72478. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72479. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72480. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72481. });
  72482. }
  72483. }
  72484. }
  72485. };
  72486. /**
  72487. * Disables the effect on the given cameras
  72488. * @param cameras The camera to disable.
  72489. */
  72490. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72491. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72492. if (!cams) {
  72493. return;
  72494. }
  72495. for (var i = 0; i < cams.length; i++) {
  72496. var camera = cams[i];
  72497. var cameraName = camera.name;
  72498. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72499. camera.detachPostProcess(postProcess);
  72500. });
  72501. }
  72502. };
  72503. /**
  72504. * Gets a list of the post processes contained in the effect.
  72505. * @param camera The camera to get the post processes on.
  72506. * @returns The list of the post processes in the effect.
  72507. */
  72508. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72509. if (this._singleInstance) {
  72510. return this._postProcesses[0];
  72511. }
  72512. else {
  72513. if (!camera) {
  72514. return null;
  72515. }
  72516. return this._postProcesses[camera.name];
  72517. }
  72518. };
  72519. return PostProcessRenderEffect;
  72520. }());
  72521. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72522. })(BABYLON || (BABYLON = {}));
  72523. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72524. var BABYLON;
  72525. (function (BABYLON) {
  72526. var PostProcessRenderPipeline = /** @class */ (function () {
  72527. function PostProcessRenderPipeline(engine, name) {
  72528. this.engine = engine;
  72529. this._name = name;
  72530. this._renderEffects = {};
  72531. this._renderEffectsForIsolatedPass = new Array();
  72532. this._cameras = [];
  72533. }
  72534. PostProcessRenderPipeline.prototype.getClassName = function () {
  72535. return "PostProcessRenderPipeline";
  72536. };
  72537. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72538. get: function () {
  72539. for (var renderEffectName in this._renderEffects) {
  72540. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72541. if (!this._renderEffects[renderEffectName].isSupported) {
  72542. return false;
  72543. }
  72544. }
  72545. }
  72546. return true;
  72547. },
  72548. enumerable: true,
  72549. configurable: true
  72550. });
  72551. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72552. this._renderEffects[renderEffect._name] = renderEffect;
  72553. };
  72554. // private
  72555. PostProcessRenderPipeline.prototype._rebuild = function () {
  72556. };
  72557. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72558. var renderEffects = this._renderEffects[renderEffectName];
  72559. if (!renderEffects) {
  72560. return;
  72561. }
  72562. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72563. };
  72564. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72565. var renderEffects = this._renderEffects[renderEffectName];
  72566. if (!renderEffects) {
  72567. return;
  72568. }
  72569. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72570. };
  72571. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72572. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72573. if (!cams) {
  72574. return;
  72575. }
  72576. var indicesToDelete = [];
  72577. var i;
  72578. for (i = 0; i < cams.length; i++) {
  72579. var camera = cams[i];
  72580. var cameraName = camera.name;
  72581. if (this._cameras.indexOf(camera) === -1) {
  72582. this._cameras[cameraName] = camera;
  72583. }
  72584. else if (unique) {
  72585. indicesToDelete.push(i);
  72586. }
  72587. }
  72588. for (i = 0; i < indicesToDelete.length; i++) {
  72589. cameras.splice(indicesToDelete[i], 1);
  72590. }
  72591. for (var renderEffectName in this._renderEffects) {
  72592. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72593. this._renderEffects[renderEffectName]._attachCameras(cams);
  72594. }
  72595. }
  72596. };
  72597. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72598. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72599. if (!cams) {
  72600. return;
  72601. }
  72602. for (var renderEffectName in this._renderEffects) {
  72603. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72604. this._renderEffects[renderEffectName]._detachCameras(cams);
  72605. }
  72606. }
  72607. for (var i = 0; i < cams.length; i++) {
  72608. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72609. }
  72610. };
  72611. PostProcessRenderPipeline.prototype._update = function () {
  72612. for (var renderEffectName in this._renderEffects) {
  72613. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72614. this._renderEffects[renderEffectName]._update();
  72615. }
  72616. }
  72617. for (var i = 0; i < this._cameras.length; i++) {
  72618. var cameraName = this._cameras[i].name;
  72619. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72620. this._renderEffectsForIsolatedPass[cameraName]._update();
  72621. }
  72622. }
  72623. };
  72624. PostProcessRenderPipeline.prototype._reset = function () {
  72625. this._renderEffects = {};
  72626. this._renderEffectsForIsolatedPass = new Array();
  72627. };
  72628. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72629. // 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)
  72630. var effectKeys = Object.keys(this._renderEffects);
  72631. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72632. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72633. if (postProcesses) {
  72634. postProcesses[0].samples = sampleCount;
  72635. return true;
  72636. }
  72637. }
  72638. return false;
  72639. };
  72640. PostProcessRenderPipeline.prototype.dispose = function () {
  72641. // Must be implemented by children
  72642. };
  72643. __decorate([
  72644. BABYLON.serialize()
  72645. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72646. return PostProcessRenderPipeline;
  72647. }());
  72648. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72649. })(BABYLON || (BABYLON = {}));
  72650. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72651. var BABYLON;
  72652. (function (BABYLON) {
  72653. /**
  72654. * This represents a depth renderer in Babylon.
  72655. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72656. */
  72657. var DepthRenderer = /** @class */ (function () {
  72658. /**
  72659. * Instantiates a depth renderer
  72660. * @param scene The scene the renderer belongs to
  72661. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72662. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72663. */
  72664. function DepthRenderer(scene, type, camera) {
  72665. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72666. if (camera === void 0) { camera = null; }
  72667. var _this = this;
  72668. this._scene = scene;
  72669. this._camera = camera;
  72670. var engine = scene.getEngine();
  72671. // Render target
  72672. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72673. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72674. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72675. this._depthMap.refreshRate = 1;
  72676. this._depthMap.renderParticles = false;
  72677. this._depthMap.renderList = null;
  72678. // Camera to get depth map from to support multiple concurrent cameras
  72679. this._depthMap.activeCamera = this._camera;
  72680. this._depthMap.ignoreCameraViewport = true;
  72681. this._depthMap.useCameraPostProcesses = false;
  72682. // set default depth value to 1.0 (far away)
  72683. this._depthMap.onClearObservable.add(function (engine) {
  72684. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72685. });
  72686. // Custom render function
  72687. var renderSubMesh = function (subMesh) {
  72688. var mesh = subMesh.getRenderingMesh();
  72689. var scene = _this._scene;
  72690. var engine = scene.getEngine();
  72691. var material = subMesh.getMaterial();
  72692. if (!material) {
  72693. return;
  72694. }
  72695. // Culling and reverse (right handed system)
  72696. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72697. // Managing instances
  72698. var batch = mesh._getInstancesRenderList(subMesh._id);
  72699. if (batch.mustReturn) {
  72700. return;
  72701. }
  72702. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72703. var camera = _this._camera || scene.activeCamera;
  72704. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72705. engine.enableEffect(_this._effect);
  72706. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72707. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72708. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72709. // Alpha test
  72710. if (material && material.needAlphaTesting()) {
  72711. var alphaTexture = material.getAlphaTestTexture();
  72712. if (alphaTexture) {
  72713. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72714. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72715. }
  72716. }
  72717. // Bones
  72718. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72719. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72720. }
  72721. // Draw
  72722. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72723. }
  72724. };
  72725. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72726. var index;
  72727. if (depthOnlySubMeshes.length) {
  72728. engine.setColorWrite(false);
  72729. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72730. renderSubMesh(depthOnlySubMeshes.data[index]);
  72731. }
  72732. engine.setColorWrite(true);
  72733. }
  72734. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72735. renderSubMesh(opaqueSubMeshes.data[index]);
  72736. }
  72737. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72738. renderSubMesh(alphaTestSubMeshes.data[index]);
  72739. }
  72740. };
  72741. }
  72742. /**
  72743. * Creates the depth rendering effect and checks if the effect is ready.
  72744. * @param subMesh The submesh to be used to render the depth map of
  72745. * @param useInstances If multiple world instances should be used
  72746. * @returns if the depth renderer is ready to render the depth map
  72747. */
  72748. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72749. var material = subMesh.getMaterial();
  72750. if (material.disableDepthWrite) {
  72751. return false;
  72752. }
  72753. var defines = [];
  72754. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72755. var mesh = subMesh.getMesh();
  72756. // Alpha test
  72757. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72758. defines.push("#define ALPHATEST");
  72759. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72760. attribs.push(BABYLON.VertexBuffer.UVKind);
  72761. defines.push("#define UV1");
  72762. }
  72763. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72764. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72765. defines.push("#define UV2");
  72766. }
  72767. }
  72768. // Bones
  72769. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72770. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72771. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72772. if (mesh.numBoneInfluencers > 4) {
  72773. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72774. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72775. }
  72776. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72777. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72778. }
  72779. else {
  72780. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72781. }
  72782. // Instances
  72783. if (useInstances) {
  72784. defines.push("#define INSTANCES");
  72785. attribs.push("world0");
  72786. attribs.push("world1");
  72787. attribs.push("world2");
  72788. attribs.push("world3");
  72789. }
  72790. // Get correct effect
  72791. var join = defines.join("\n");
  72792. if (this._cachedDefines !== join) {
  72793. this._cachedDefines = join;
  72794. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72795. }
  72796. return this._effect.isReady();
  72797. };
  72798. /**
  72799. * Gets the texture which the depth map will be written to.
  72800. * @returns The depth map texture
  72801. */
  72802. DepthRenderer.prototype.getDepthMap = function () {
  72803. return this._depthMap;
  72804. };
  72805. /**
  72806. * Disposes of the depth renderer.
  72807. */
  72808. DepthRenderer.prototype.dispose = function () {
  72809. this._depthMap.dispose();
  72810. };
  72811. return DepthRenderer;
  72812. }());
  72813. BABYLON.DepthRenderer = DepthRenderer;
  72814. })(BABYLON || (BABYLON = {}));
  72815. //# sourceMappingURL=babylon.depthRenderer.js.map
  72816. var BABYLON;
  72817. (function (BABYLON) {
  72818. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72819. __extends(SSAORenderingPipeline, _super);
  72820. /**
  72821. * @constructor
  72822. * @param {string} name - The rendering pipeline name
  72823. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72824. * @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 }
  72825. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72826. */
  72827. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72828. var _this = _super.call(this, scene.getEngine(), name) || this;
  72829. // Members
  72830. /**
  72831. * The PassPostProcess id in the pipeline that contains the original scene color
  72832. */
  72833. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72834. /**
  72835. * The SSAO PostProcess id in the pipeline
  72836. */
  72837. _this.SSAORenderEffect = "SSAORenderEffect";
  72838. /**
  72839. * The horizontal blur PostProcess id in the pipeline
  72840. */
  72841. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72842. /**
  72843. * The vertical blur PostProcess id in the pipeline
  72844. */
  72845. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72846. /**
  72847. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72848. */
  72849. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72850. /**
  72851. * The output strength of the SSAO post-process. Default value is 1.0.
  72852. */
  72853. _this.totalStrength = 1.0;
  72854. /**
  72855. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72856. */
  72857. _this.radius = 0.0001;
  72858. /**
  72859. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72860. * Must not be equal to fallOff and superior to fallOff.
  72861. * Default value is 0.975
  72862. */
  72863. _this.area = 0.0075;
  72864. /**
  72865. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72866. * Must not be equal to area and inferior to area.
  72867. * Default value is 0.0
  72868. */
  72869. _this.fallOff = 0.000001;
  72870. /**
  72871. * The base color of the SSAO post-process
  72872. * The final result is "base + ssao" between [0, 1]
  72873. */
  72874. _this.base = 0.5;
  72875. _this._firstUpdate = true;
  72876. _this._scene = scene;
  72877. // Set up assets
  72878. _this._createRandomTexture();
  72879. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72880. var ssaoRatio = ratio.ssaoRatio || ratio;
  72881. var combineRatio = ratio.combineRatio || ratio;
  72882. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72883. _this._createSSAOPostProcess(ssaoRatio);
  72884. _this._createBlurPostProcess(ssaoRatio);
  72885. _this._createSSAOCombinePostProcess(combineRatio);
  72886. // Set up pipeline
  72887. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72888. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72889. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72890. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72891. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72892. // Finish
  72893. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72894. if (cameras)
  72895. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72896. return _this;
  72897. }
  72898. // Public Methods
  72899. /**
  72900. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72901. */
  72902. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72903. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72904. for (var i = 0; i < this._scene.cameras.length; i++) {
  72905. var camera = this._scene.cameras[i];
  72906. this._originalColorPostProcess.dispose(camera);
  72907. this._ssaoPostProcess.dispose(camera);
  72908. this._blurHPostProcess.dispose(camera);
  72909. this._blurVPostProcess.dispose(camera);
  72910. this._ssaoCombinePostProcess.dispose(camera);
  72911. }
  72912. this._randomTexture.dispose();
  72913. if (disableDepthRender)
  72914. this._scene.disableDepthRenderer();
  72915. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72916. _super.prototype.dispose.call(this);
  72917. };
  72918. // Private Methods
  72919. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72920. var _this = this;
  72921. var size = 16;
  72922. 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);
  72923. 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);
  72924. this._blurHPostProcess.onActivateObservable.add(function () {
  72925. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72926. _this._blurHPostProcess.kernel = size * dw;
  72927. });
  72928. this._blurVPostProcess.onActivateObservable.add(function () {
  72929. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72930. _this._blurVPostProcess.kernel = size * dw;
  72931. });
  72932. };
  72933. SSAORenderingPipeline.prototype._rebuild = function () {
  72934. this._firstUpdate = true;
  72935. _super.prototype._rebuild.call(this);
  72936. };
  72937. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72938. var _this = this;
  72939. var numSamples = 16;
  72940. var sampleSphere = [
  72941. 0.5381, 0.1856, -0.4319,
  72942. 0.1379, 0.2486, 0.4430,
  72943. 0.3371, 0.5679, -0.0057,
  72944. -0.6999, -0.0451, -0.0019,
  72945. 0.0689, -0.1598, -0.8547,
  72946. 0.0560, 0.0069, -0.1843,
  72947. -0.0146, 0.1402, 0.0762,
  72948. 0.0100, -0.1924, -0.0344,
  72949. -0.3577, -0.5301, -0.4358,
  72950. -0.3169, 0.1063, 0.0158,
  72951. 0.0103, -0.5869, 0.0046,
  72952. -0.0897, -0.4940, 0.3287,
  72953. 0.7119, -0.0154, -0.0918,
  72954. -0.0533, 0.0596, -0.5411,
  72955. 0.0352, -0.0631, 0.5460,
  72956. -0.4776, 0.2847, -0.0271
  72957. ];
  72958. var samplesFactor = 1.0 / numSamples;
  72959. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72960. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72961. "area", "fallOff", "base", "range", "viewport"
  72962. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72963. this._ssaoPostProcess.onApply = function (effect) {
  72964. if (_this._firstUpdate) {
  72965. effect.setArray3("sampleSphere", sampleSphere);
  72966. effect.setFloat("samplesFactor", samplesFactor);
  72967. effect.setFloat("randTextureTiles", 4.0);
  72968. }
  72969. effect.setFloat("totalStrength", _this.totalStrength);
  72970. effect.setFloat("radius", _this.radius);
  72971. effect.setFloat("area", _this.area);
  72972. effect.setFloat("fallOff", _this.fallOff);
  72973. effect.setFloat("base", _this.base);
  72974. effect.setTexture("textureSampler", _this._depthTexture);
  72975. effect.setTexture("randomSampler", _this._randomTexture);
  72976. };
  72977. };
  72978. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72979. var _this = this;
  72980. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72981. this._ssaoCombinePostProcess.onApply = function (effect) {
  72982. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72983. };
  72984. };
  72985. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72986. var size = 512;
  72987. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72988. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72989. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72990. var context = this._randomTexture.getContext();
  72991. var rand = function (min, max) {
  72992. return Math.random() * (max - min) + min;
  72993. };
  72994. var randVector = BABYLON.Vector3.Zero();
  72995. for (var x = 0; x < size; x++) {
  72996. for (var y = 0; y < size; y++) {
  72997. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72998. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72999. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73000. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73001. context.fillRect(x, y, 1, 1);
  73002. }
  73003. }
  73004. this._randomTexture.update(false);
  73005. };
  73006. __decorate([
  73007. BABYLON.serialize()
  73008. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73009. __decorate([
  73010. BABYLON.serialize()
  73011. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73012. __decorate([
  73013. BABYLON.serialize()
  73014. ], SSAORenderingPipeline.prototype, "area", void 0);
  73015. __decorate([
  73016. BABYLON.serialize()
  73017. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73018. __decorate([
  73019. BABYLON.serialize()
  73020. ], SSAORenderingPipeline.prototype, "base", void 0);
  73021. return SSAORenderingPipeline;
  73022. }(BABYLON.PostProcessRenderPipeline));
  73023. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73024. })(BABYLON || (BABYLON = {}));
  73025. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73026. var BABYLON;
  73027. (function (BABYLON) {
  73028. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73029. __extends(SSAO2RenderingPipeline, _super);
  73030. /**
  73031. * @constructor
  73032. * @param {string} name - The rendering pipeline name
  73033. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73034. * @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 }
  73035. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73036. */
  73037. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73038. var _this = _super.call(this, scene.getEngine(), name) || this;
  73039. // Members
  73040. /**
  73041. * The PassPostProcess id in the pipeline that contains the original scene color
  73042. */
  73043. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73044. /**
  73045. * The SSAO PostProcess id in the pipeline
  73046. */
  73047. _this.SSAORenderEffect = "SSAORenderEffect";
  73048. /**
  73049. * The horizontal blur PostProcess id in the pipeline
  73050. */
  73051. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73052. /**
  73053. * The vertical blur PostProcess id in the pipeline
  73054. */
  73055. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73056. /**
  73057. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73058. */
  73059. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73060. /**
  73061. * The output strength of the SSAO post-process. Default value is 1.0.
  73062. */
  73063. _this.totalStrength = 1.0;
  73064. /**
  73065. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73066. */
  73067. _this.maxZ = 100.0;
  73068. /**
  73069. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73070. */
  73071. _this.minZAspect = 0.2;
  73072. /**
  73073. * Number of samples used for the SSAO calculations. Default value is 8
  73074. */
  73075. _this._samples = 8;
  73076. /**
  73077. * Are we using bilateral blur ?
  73078. */
  73079. _this._expensiveBlur = true;
  73080. /**
  73081. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73082. */
  73083. _this.radius = 2.0;
  73084. /**
  73085. * The base color of the SSAO post-process
  73086. * The final result is "base + ssao" between [0, 1]
  73087. */
  73088. _this.base = 0.1;
  73089. _this._firstUpdate = true;
  73090. _this._scene = scene;
  73091. _this._ratio = ratio;
  73092. if (!_this.isSupported) {
  73093. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73094. return _this;
  73095. }
  73096. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73097. var blurRatio = _this._ratio.blurRatio || ratio;
  73098. // Set up assets
  73099. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73100. _this._createRandomTexture();
  73101. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73102. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73103. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73104. _this._createSSAOPostProcess(1.0);
  73105. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73106. _this._createSSAOCombinePostProcess(blurRatio);
  73107. // Set up pipeline
  73108. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73109. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73110. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73111. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73112. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73113. // Finish
  73114. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73115. if (cameras)
  73116. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73117. return _this;
  73118. }
  73119. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73120. get: function () {
  73121. return this._samples;
  73122. },
  73123. set: function (n) {
  73124. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73125. this._samples = n;
  73126. this._sampleSphere = this._generateHemisphere();
  73127. this._firstUpdate = true;
  73128. },
  73129. enumerable: true,
  73130. configurable: true
  73131. });
  73132. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73133. get: function () {
  73134. return this._expensiveBlur;
  73135. },
  73136. set: function (b) {
  73137. 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"]);
  73138. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73139. this._expensiveBlur = b;
  73140. this._firstUpdate = true;
  73141. },
  73142. enumerable: true,
  73143. configurable: true
  73144. });
  73145. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73146. /**
  73147. * Support test.
  73148. */
  73149. get: function () {
  73150. var engine = BABYLON.Engine.LastCreatedEngine;
  73151. if (!engine) {
  73152. return false;
  73153. }
  73154. return engine.getCaps().drawBuffersExtension;
  73155. },
  73156. enumerable: true,
  73157. configurable: true
  73158. });
  73159. // Public Methods
  73160. /**
  73161. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73162. */
  73163. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73164. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73165. for (var i = 0; i < this._scene.cameras.length; i++) {
  73166. var camera = this._scene.cameras[i];
  73167. this._originalColorPostProcess.dispose(camera);
  73168. this._ssaoPostProcess.dispose(camera);
  73169. this._blurHPostProcess.dispose(camera);
  73170. this._blurVPostProcess.dispose(camera);
  73171. this._ssaoCombinePostProcess.dispose(camera);
  73172. }
  73173. this._randomTexture.dispose();
  73174. if (disableGeometryBufferRenderer)
  73175. this._scene.disableGeometryBufferRenderer();
  73176. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73177. _super.prototype.dispose.call(this);
  73178. };
  73179. // Private Methods
  73180. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73181. var _this = this;
  73182. this._samplerOffsets = [];
  73183. var expensive = this.expensiveBlur;
  73184. for (var i = -8; i < 8; i++) {
  73185. this._samplerOffsets.push(i * 2 + 0.5);
  73186. }
  73187. 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");
  73188. this._blurHPostProcess.onApply = function (effect) {
  73189. if (!_this._scene.activeCamera) {
  73190. return;
  73191. }
  73192. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73193. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73194. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73195. effect.setFloat("radius", _this.radius);
  73196. effect.setTexture("depthSampler", _this._depthTexture);
  73197. if (_this._firstUpdate) {
  73198. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73199. }
  73200. };
  73201. 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");
  73202. this._blurVPostProcess.onApply = function (effect) {
  73203. if (!_this._scene.activeCamera) {
  73204. return;
  73205. }
  73206. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73207. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73208. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73209. effect.setFloat("radius", _this.radius);
  73210. effect.setTexture("depthSampler", _this._depthTexture);
  73211. if (_this._firstUpdate) {
  73212. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73213. _this._firstUpdate = false;
  73214. }
  73215. };
  73216. };
  73217. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73218. this._firstUpdate = true;
  73219. _super.prototype._rebuild.call(this);
  73220. };
  73221. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73222. var numSamples = this.samples;
  73223. var result = [];
  73224. var vector, scale;
  73225. var rand = function (min, max) {
  73226. return Math.random() * (max - min) + min;
  73227. };
  73228. var i = 0;
  73229. while (i < numSamples) {
  73230. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73231. vector.normalize();
  73232. scale = i / numSamples;
  73233. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73234. vector.scaleInPlace(scale);
  73235. result.push(vector.x, vector.y, vector.z);
  73236. i++;
  73237. }
  73238. return result;
  73239. };
  73240. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73241. var _this = this;
  73242. var numSamples = this.samples;
  73243. this._sampleSphere = this._generateHemisphere();
  73244. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73245. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73246. "base", "range", "projection", "near", "far", "texelSize",
  73247. "xViewport", "yViewport", "maxZ", "minZAspect"
  73248. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73249. this._ssaoPostProcess.onApply = function (effect) {
  73250. if (_this._firstUpdate) {
  73251. effect.setArray3("sampleSphere", _this._sampleSphere);
  73252. effect.setFloat("randTextureTiles", 4.0);
  73253. }
  73254. if (!_this._scene.activeCamera) {
  73255. return;
  73256. }
  73257. effect.setFloat("samplesFactor", 1 / _this.samples);
  73258. effect.setFloat("totalStrength", _this.totalStrength);
  73259. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73260. effect.setFloat("radius", _this.radius);
  73261. effect.setFloat("maxZ", _this.maxZ);
  73262. effect.setFloat("minZAspect", _this.minZAspect);
  73263. effect.setFloat("base", _this.base);
  73264. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73265. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73266. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73267. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73268. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73269. effect.setTexture("textureSampler", _this._depthTexture);
  73270. effect.setTexture("normalSampler", _this._normalTexture);
  73271. effect.setTexture("randomSampler", _this._randomTexture);
  73272. };
  73273. };
  73274. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73275. var _this = this;
  73276. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73277. this._ssaoCombinePostProcess.onApply = function (effect) {
  73278. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73279. };
  73280. };
  73281. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73282. var size = 512;
  73283. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73284. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73285. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73286. var context = this._randomTexture.getContext();
  73287. var rand = function (min, max) {
  73288. return Math.random() * (max - min) + min;
  73289. };
  73290. var randVector = BABYLON.Vector3.Zero();
  73291. for (var x = 0; x < size; x++) {
  73292. for (var y = 0; y < size; y++) {
  73293. randVector.x = rand(0.0, 1.0);
  73294. randVector.y = rand(0.0, 1.0);
  73295. randVector.z = 0.0;
  73296. randVector.normalize();
  73297. randVector.scaleInPlace(255);
  73298. randVector.x = Math.floor(randVector.x);
  73299. randVector.y = Math.floor(randVector.y);
  73300. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73301. context.fillRect(x, y, 1, 1);
  73302. }
  73303. }
  73304. this._randomTexture.update(false);
  73305. };
  73306. /**
  73307. * Serialize the rendering pipeline (Used when exporting)
  73308. * @returns the serialized object
  73309. */
  73310. SSAO2RenderingPipeline.prototype.serialize = function () {
  73311. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73312. serializationObject.customType = "SSAO2RenderingPipeline";
  73313. return serializationObject;
  73314. };
  73315. /**
  73316. * Parse the serialized pipeline
  73317. * @param source Source pipeline.
  73318. * @param scene The scene to load the pipeline to.
  73319. * @param rootUrl The URL of the serialized pipeline.
  73320. * @returns An instantiated pipeline from the serialized object.
  73321. */
  73322. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73323. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73324. };
  73325. __decorate([
  73326. BABYLON.serialize()
  73327. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73328. __decorate([
  73329. BABYLON.serialize()
  73330. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73331. __decorate([
  73332. BABYLON.serialize()
  73333. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73334. __decorate([
  73335. BABYLON.serialize("samples")
  73336. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73337. __decorate([
  73338. BABYLON.serialize()
  73339. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73340. __decorate([
  73341. BABYLON.serialize("expensiveBlur")
  73342. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73343. __decorate([
  73344. BABYLON.serialize()
  73345. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73346. __decorate([
  73347. BABYLON.serialize()
  73348. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73349. return SSAO2RenderingPipeline;
  73350. }(BABYLON.PostProcessRenderPipeline));
  73351. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73352. })(BABYLON || (BABYLON = {}));
  73353. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73354. // BABYLON.JS Chromatic Aberration GLSL Shader
  73355. // Author: Olivier Guyot
  73356. // Separates very slightly R, G and B colors on the edges of the screen
  73357. // Inspired by Francois Tarlier & Martins Upitis
  73358. var BABYLON;
  73359. (function (BABYLON) {
  73360. var LensRenderingPipeline = /** @class */ (function (_super) {
  73361. __extends(LensRenderingPipeline, _super);
  73362. /**
  73363. * @constructor
  73364. *
  73365. * Effect parameters are as follow:
  73366. * {
  73367. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73368. * edge_blur: number; // from 0 to x (1 for realism)
  73369. * distortion: number; // from 0 to x (1 for realism)
  73370. * grain_amount: number; // from 0 to 1
  73371. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73372. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73373. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73374. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73375. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73376. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73377. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73378. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73379. * }
  73380. * Note: if an effect parameter is unset, effect is disabled
  73381. *
  73382. * @param {string} name - The rendering pipeline name
  73383. * @param {object} parameters - An object containing all parameters (see above)
  73384. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73385. * @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)
  73386. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73387. */
  73388. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73389. if (ratio === void 0) { ratio = 1.0; }
  73390. var _this = _super.call(this, scene.getEngine(), name) || this;
  73391. // Lens effects can be of the following:
  73392. // - chromatic aberration (slight shift of RGB colors)
  73393. // - blur on the edge of the lens
  73394. // - lens distortion
  73395. // - depth-of-field blur & highlights enhancing
  73396. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73397. // - grain effect (noise or custom texture)
  73398. // Two additional texture samplers are needed:
  73399. // - depth map (for depth-of-field)
  73400. // - grain texture
  73401. /**
  73402. * The chromatic aberration PostProcess id in the pipeline
  73403. */
  73404. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73405. /**
  73406. * The highlights enhancing PostProcess id in the pipeline
  73407. */
  73408. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73409. /**
  73410. * The depth-of-field PostProcess id in the pipeline
  73411. */
  73412. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73413. _this._scene = scene;
  73414. // Fetch texture samplers
  73415. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73416. if (parameters.grain_texture) {
  73417. _this._grainTexture = parameters.grain_texture;
  73418. }
  73419. else {
  73420. _this._createGrainTexture();
  73421. }
  73422. // save parameters
  73423. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73424. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73425. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73426. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73427. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73428. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73429. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73430. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73431. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73432. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73433. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73434. // Create effects
  73435. _this._createChromaticAberrationPostProcess(ratio);
  73436. _this._createHighlightsPostProcess(ratio);
  73437. _this._createDepthOfFieldPostProcess(ratio / 4);
  73438. // Set up pipeline
  73439. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73440. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73441. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73442. if (_this._highlightsGain === -1) {
  73443. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73444. }
  73445. // Finish
  73446. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73447. if (cameras) {
  73448. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73449. }
  73450. return _this;
  73451. }
  73452. // public methods (self explanatory)
  73453. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73454. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73455. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73456. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73457. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73458. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73459. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73460. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73461. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73462. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73463. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73464. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73465. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73466. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73467. };
  73468. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73469. this._highlightsPostProcess.updateEffect();
  73470. };
  73471. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73472. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73473. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73474. this._highlightsGain = amount;
  73475. };
  73476. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73477. if (this._highlightsGain === -1) {
  73478. this._highlightsGain = 1.0;
  73479. }
  73480. this._highlightsThreshold = amount;
  73481. };
  73482. LensRenderingPipeline.prototype.disableHighlights = function () {
  73483. this._highlightsGain = -1;
  73484. };
  73485. /**
  73486. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73487. */
  73488. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73489. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73490. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73491. this._chromaticAberrationPostProcess = null;
  73492. this._highlightsPostProcess = null;
  73493. this._depthOfFieldPostProcess = null;
  73494. this._grainTexture.dispose();
  73495. if (disableDepthRender)
  73496. this._scene.disableDepthRenderer();
  73497. };
  73498. // colors shifting and distortion
  73499. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73500. var _this = this;
  73501. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73502. [], // samplers
  73503. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73504. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73505. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73506. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73507. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73508. effect.setFloat('radialIntensity', 1);
  73509. effect.setFloat2('direction', 17, 17);
  73510. effect.setFloat2('centerPosition', 0.5, 0.5);
  73511. };
  73512. };
  73513. // highlights enhancing
  73514. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73515. var _this = this;
  73516. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73517. [], // samplers
  73518. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73519. this._highlightsPostProcess.onApply = function (effect) {
  73520. effect.setFloat('gain', _this._highlightsGain);
  73521. effect.setFloat('threshold', _this._highlightsThreshold);
  73522. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73523. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73524. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73525. };
  73526. };
  73527. // colors shifting and distortion
  73528. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73529. var _this = this;
  73530. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73531. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73532. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73533. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73534. this._depthOfFieldPostProcess.onApply = function (effect) {
  73535. effect.setTexture("depthSampler", _this._depthTexture);
  73536. effect.setTexture("grainSampler", _this._grainTexture);
  73537. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73538. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73539. effect.setFloat('grain_amount', _this._grainAmount);
  73540. effect.setBool('blur_noise', _this._blurNoise);
  73541. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73542. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73543. effect.setFloat('distortion', _this._distortion);
  73544. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73545. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73546. effect.setFloat('aperture', _this._dofAperture);
  73547. effect.setFloat('darken', _this._dofDarken);
  73548. effect.setFloat('edge_blur', _this._edgeBlur);
  73549. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73550. if (_this._scene.activeCamera) {
  73551. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73552. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73553. }
  73554. };
  73555. };
  73556. // creates a black and white random noise texture, 512x512
  73557. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73558. var size = 512;
  73559. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73560. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73561. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73562. var context = this._grainTexture.getContext();
  73563. var rand = function (min, max) {
  73564. return Math.random() * (max - min) + min;
  73565. };
  73566. var value;
  73567. for (var x = 0; x < size; x++) {
  73568. for (var y = 0; y < size; y++) {
  73569. value = Math.floor(rand(0.42, 0.58) * 255);
  73570. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73571. context.fillRect(x, y, 1, 1);
  73572. }
  73573. }
  73574. this._grainTexture.update(false);
  73575. };
  73576. return LensRenderingPipeline;
  73577. }(BABYLON.PostProcessRenderPipeline));
  73578. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73579. })(BABYLON || (BABYLON = {}));
  73580. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73581. var BABYLON;
  73582. (function (BABYLON) {
  73583. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73584. __extends(StandardRenderingPipeline, _super);
  73585. /**
  73586. * @constructor
  73587. * @param {string} name - The rendering pipeline name
  73588. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73589. * @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)
  73590. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73591. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73592. */
  73593. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73594. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73595. var _this = _super.call(this, scene.getEngine(), name) || this;
  73596. _this.downSampleX4PostProcess = null;
  73597. _this.brightPassPostProcess = null;
  73598. _this.blurHPostProcesses = [];
  73599. _this.blurVPostProcesses = [];
  73600. _this.textureAdderPostProcess = null;
  73601. _this.volumetricLightPostProcess = null;
  73602. _this.volumetricLightSmoothXPostProcess = null;
  73603. _this.volumetricLightSmoothYPostProcess = null;
  73604. _this.volumetricLightMergePostProces = null;
  73605. _this.volumetricLightFinalPostProcess = null;
  73606. _this.luminancePostProcess = null;
  73607. _this.luminanceDownSamplePostProcesses = [];
  73608. _this.hdrPostProcess = null;
  73609. _this.textureAdderFinalPostProcess = null;
  73610. _this.lensFlareFinalPostProcess = null;
  73611. _this.hdrFinalPostProcess = null;
  73612. _this.lensFlarePostProcess = null;
  73613. _this.lensFlareComposePostProcess = null;
  73614. _this.motionBlurPostProcess = null;
  73615. _this.depthOfFieldPostProcess = null;
  73616. // Values
  73617. _this.brightThreshold = 1.0;
  73618. _this.blurWidth = 512.0;
  73619. _this.horizontalBlur = false;
  73620. _this.exposure = 1.0;
  73621. _this.lensTexture = null;
  73622. _this.volumetricLightCoefficient = 0.2;
  73623. _this.volumetricLightPower = 4.0;
  73624. _this.volumetricLightBlurScale = 64.0;
  73625. _this.sourceLight = null;
  73626. _this.hdrMinimumLuminance = 1.0;
  73627. _this.hdrDecreaseRate = 0.5;
  73628. _this.hdrIncreaseRate = 0.5;
  73629. _this.lensColorTexture = null;
  73630. _this.lensFlareStrength = 20.0;
  73631. _this.lensFlareGhostDispersal = 1.4;
  73632. _this.lensFlareHaloWidth = 0.7;
  73633. _this.lensFlareDistortionStrength = 16.0;
  73634. _this.lensStarTexture = null;
  73635. _this.lensFlareDirtTexture = null;
  73636. _this.depthOfFieldDistance = 10.0;
  73637. _this.depthOfFieldBlurWidth = 64.0;
  73638. _this.motionStrength = 1.0;
  73639. // IAnimatable
  73640. _this.animations = [];
  73641. _this._currentDepthOfFieldSource = null;
  73642. _this._hdrCurrentLuminance = 1.0;
  73643. // Getters and setters
  73644. _this._bloomEnabled = true;
  73645. _this._depthOfFieldEnabled = false;
  73646. _this._vlsEnabled = false;
  73647. _this._lensFlareEnabled = false;
  73648. _this._hdrEnabled = false;
  73649. _this._motionBlurEnabled = false;
  73650. _this._motionBlurSamples = 64.0;
  73651. _this._volumetricLightStepsCount = 50.0;
  73652. _this._cameras = cameras || [];
  73653. // Initialize
  73654. _this._scene = scene;
  73655. _this._basePostProcess = originalPostProcess;
  73656. _this._ratio = ratio;
  73657. // Misc
  73658. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73659. // Finish
  73660. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73661. _this._buildPipeline();
  73662. return _this;
  73663. }
  73664. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73665. get: function () {
  73666. return this._bloomEnabled;
  73667. },
  73668. set: function (enabled) {
  73669. if (this._bloomEnabled === enabled) {
  73670. return;
  73671. }
  73672. this._bloomEnabled = enabled;
  73673. this._buildPipeline();
  73674. },
  73675. enumerable: true,
  73676. configurable: true
  73677. });
  73678. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73679. get: function () {
  73680. return this._depthOfFieldEnabled;
  73681. },
  73682. set: function (enabled) {
  73683. if (this._depthOfFieldEnabled === enabled) {
  73684. return;
  73685. }
  73686. this._depthOfFieldEnabled = enabled;
  73687. this._buildPipeline();
  73688. },
  73689. enumerable: true,
  73690. configurable: true
  73691. });
  73692. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73693. get: function () {
  73694. return this._lensFlareEnabled;
  73695. },
  73696. set: function (enabled) {
  73697. if (this._lensFlareEnabled === enabled) {
  73698. return;
  73699. }
  73700. this._lensFlareEnabled = enabled;
  73701. this._buildPipeline();
  73702. },
  73703. enumerable: true,
  73704. configurable: true
  73705. });
  73706. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73707. get: function () {
  73708. return this._hdrEnabled;
  73709. },
  73710. set: function (enabled) {
  73711. if (this._hdrEnabled === enabled) {
  73712. return;
  73713. }
  73714. this._hdrEnabled = enabled;
  73715. this._buildPipeline();
  73716. },
  73717. enumerable: true,
  73718. configurable: true
  73719. });
  73720. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73721. get: function () {
  73722. return this._vlsEnabled;
  73723. },
  73724. set: function (enabled) {
  73725. if (this._vlsEnabled === enabled) {
  73726. return;
  73727. }
  73728. if (enabled) {
  73729. var geometry = this._scene.enableGeometryBufferRenderer();
  73730. if (!geometry) {
  73731. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73732. return;
  73733. }
  73734. }
  73735. this._vlsEnabled = enabled;
  73736. this._buildPipeline();
  73737. },
  73738. enumerable: true,
  73739. configurable: true
  73740. });
  73741. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73742. get: function () {
  73743. return this._motionBlurEnabled;
  73744. },
  73745. set: function (enabled) {
  73746. if (this._motionBlurEnabled === enabled) {
  73747. return;
  73748. }
  73749. this._motionBlurEnabled = enabled;
  73750. this._buildPipeline();
  73751. },
  73752. enumerable: true,
  73753. configurable: true
  73754. });
  73755. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73756. get: function () {
  73757. return this._volumetricLightStepsCount;
  73758. },
  73759. set: function (count) {
  73760. if (this.volumetricLightPostProcess) {
  73761. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73762. }
  73763. this._volumetricLightStepsCount = count;
  73764. },
  73765. enumerable: true,
  73766. configurable: true
  73767. });
  73768. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73769. get: function () {
  73770. return this._motionBlurSamples;
  73771. },
  73772. set: function (samples) {
  73773. if (this.motionBlurPostProcess) {
  73774. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73775. }
  73776. this._motionBlurSamples = samples;
  73777. },
  73778. enumerable: true,
  73779. configurable: true
  73780. });
  73781. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73782. var _this = this;
  73783. var ratio = this._ratio;
  73784. var scene = this._scene;
  73785. this._disposePostProcesses();
  73786. this._reset();
  73787. // Create pass post-process
  73788. if (!this._basePostProcess) {
  73789. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73790. this.originalPostProcess.onApply = function (effect) {
  73791. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73792. };
  73793. }
  73794. else {
  73795. this.originalPostProcess = this._basePostProcess;
  73796. }
  73797. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73798. this._currentDepthOfFieldSource = this.originalPostProcess;
  73799. if (this._bloomEnabled) {
  73800. // Create down sample X4 post-process
  73801. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73802. // Create bright pass post-process
  73803. this._createBrightPassPostProcess(scene, ratio / 2);
  73804. // Create gaussian blur post-processes (down sampling blurs)
  73805. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73806. // Create texture adder post-process
  73807. this._createTextureAdderPostProcess(scene, ratio);
  73808. // Create depth-of-field source post-process
  73809. 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);
  73810. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73811. }
  73812. if (this._vlsEnabled) {
  73813. // Create volumetric light
  73814. this._createVolumetricLightPostProcess(scene, ratio);
  73815. // Create volumetric light final post-process
  73816. 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);
  73817. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73818. }
  73819. if (this._lensFlareEnabled) {
  73820. // Create lens flare post-process
  73821. this._createLensFlarePostProcess(scene, ratio);
  73822. // Create depth-of-field source post-process post lens-flare and disable it now
  73823. 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);
  73824. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73825. }
  73826. if (this._hdrEnabled) {
  73827. // Create luminance
  73828. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73829. // Create HDR
  73830. this._createHdrPostProcess(scene, ratio);
  73831. // Create depth-of-field source post-process post hdr and disable it now
  73832. 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);
  73833. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73834. }
  73835. if (this._depthOfFieldEnabled) {
  73836. // Create gaussian blur used by depth-of-field
  73837. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73838. // Create depth-of-field post-process
  73839. this._createDepthOfFieldPostProcess(scene, ratio);
  73840. }
  73841. if (this._motionBlurEnabled) {
  73842. // Create motion blur post-process
  73843. this._createMotionBlurPostProcess(scene, ratio);
  73844. }
  73845. if (this._cameras !== null) {
  73846. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73847. }
  73848. };
  73849. // Down Sample X4 Post-Processs
  73850. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73851. var _this = this;
  73852. var downSampleX4Offsets = new Array(32);
  73853. 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);
  73854. this.downSampleX4PostProcess.onApply = function (effect) {
  73855. var id = 0;
  73856. var width = _this.downSampleX4PostProcess.width;
  73857. var height = _this.downSampleX4PostProcess.height;
  73858. for (var i = -2; i < 2; i++) {
  73859. for (var j = -2; j < 2; j++) {
  73860. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73861. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73862. id += 2;
  73863. }
  73864. }
  73865. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73866. };
  73867. // Add to pipeline
  73868. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73869. };
  73870. // Brightpass Post-Process
  73871. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73872. var _this = this;
  73873. var brightOffsets = new Array(8);
  73874. 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);
  73875. this.brightPassPostProcess.onApply = function (effect) {
  73876. var sU = (1.0 / _this.brightPassPostProcess.width);
  73877. var sV = (1.0 / _this.brightPassPostProcess.height);
  73878. brightOffsets[0] = -0.5 * sU;
  73879. brightOffsets[1] = 0.5 * sV;
  73880. brightOffsets[2] = 0.5 * sU;
  73881. brightOffsets[3] = 0.5 * sV;
  73882. brightOffsets[4] = -0.5 * sU;
  73883. brightOffsets[5] = -0.5 * sV;
  73884. brightOffsets[6] = 0.5 * sU;
  73885. brightOffsets[7] = -0.5 * sV;
  73886. effect.setArray2("dsOffsets", brightOffsets);
  73887. effect.setFloat("brightThreshold", _this.brightThreshold);
  73888. };
  73889. // Add to pipeline
  73890. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73891. };
  73892. // Create blur H&V post-processes
  73893. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73894. var _this = this;
  73895. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73896. var engine = scene.getEngine();
  73897. 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);
  73898. 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);
  73899. blurX.onActivateObservable.add(function () {
  73900. var dw = blurX.width / engine.getRenderWidth();
  73901. blurX.kernel = _this[blurWidthKey] * dw;
  73902. });
  73903. blurY.onActivateObservable.add(function () {
  73904. var dw = blurY.height / engine.getRenderHeight();
  73905. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73906. });
  73907. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73908. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73909. this.blurHPostProcesses.push(blurX);
  73910. this.blurVPostProcesses.push(blurY);
  73911. };
  73912. // Create texture adder post-process
  73913. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73914. var _this = this;
  73915. 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);
  73916. this.textureAdderPostProcess.onApply = function (effect) {
  73917. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73918. effect.setTexture("lensSampler", _this.lensTexture);
  73919. effect.setFloat("exposure", _this.exposure);
  73920. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73921. };
  73922. // Add to pipeline
  73923. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73924. };
  73925. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73926. var _this = this;
  73927. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73928. geometryRenderer.enablePosition = true;
  73929. var geometry = geometryRenderer.getGBuffer();
  73930. // Base post-process
  73931. 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));
  73932. var depthValues = BABYLON.Vector2.Zero();
  73933. this.volumetricLightPostProcess.onApply = function (effect) {
  73934. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73935. var generator = _this.sourceLight.getShadowGenerator();
  73936. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73937. effect.setTexture("positionSampler", geometry.textures[2]);
  73938. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73939. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73940. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73941. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73942. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73943. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73944. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73945. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73946. effect.setVector2("depthValues", depthValues);
  73947. }
  73948. };
  73949. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73950. // Smooth
  73951. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73952. // Merge
  73953. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73954. this.volumetricLightMergePostProces.onApply = function (effect) {
  73955. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  73956. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73957. };
  73958. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73959. };
  73960. // Create luminance
  73961. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73962. var _this = this;
  73963. // Create luminance
  73964. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73965. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73966. var offsets = [];
  73967. this.luminancePostProcess.onApply = function (effect) {
  73968. var sU = (1.0 / _this.luminancePostProcess.width);
  73969. var sV = (1.0 / _this.luminancePostProcess.height);
  73970. offsets[0] = -0.5 * sU;
  73971. offsets[1] = 0.5 * sV;
  73972. offsets[2] = 0.5 * sU;
  73973. offsets[3] = 0.5 * sV;
  73974. offsets[4] = -0.5 * sU;
  73975. offsets[5] = -0.5 * sV;
  73976. offsets[6] = 0.5 * sU;
  73977. offsets[7] = -0.5 * sV;
  73978. effect.setArray2("lumOffsets", offsets);
  73979. };
  73980. // Add to pipeline
  73981. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73982. // Create down sample luminance
  73983. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73984. var size = Math.pow(3, i);
  73985. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73986. if (i === 0) {
  73987. defines += "#define FINAL_DOWN_SAMPLER";
  73988. }
  73989. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73990. this.luminanceDownSamplePostProcesses.push(postProcess);
  73991. }
  73992. // Create callbacks and add effects
  73993. var lastLuminance = this.luminancePostProcess;
  73994. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73995. var downSampleOffsets = new Array(18);
  73996. pp.onApply = function (effect) {
  73997. if (!lastLuminance) {
  73998. return;
  73999. }
  74000. var id = 0;
  74001. for (var x = -1; x < 2; x++) {
  74002. for (var y = -1; y < 2; y++) {
  74003. downSampleOffsets[id] = x / lastLuminance.width;
  74004. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74005. id += 2;
  74006. }
  74007. }
  74008. effect.setArray2("dsOffsets", downSampleOffsets);
  74009. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74010. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74011. lastLuminance = _this.luminancePostProcess;
  74012. }
  74013. else {
  74014. lastLuminance = pp;
  74015. }
  74016. };
  74017. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74018. pp.onAfterRender = function (effect) {
  74019. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74020. 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);
  74021. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74022. };
  74023. }
  74024. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74025. });
  74026. };
  74027. // Create HDR post-process
  74028. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74029. var _this = this;
  74030. 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);
  74031. var outputLiminance = 1;
  74032. var time = 0;
  74033. var lastTime = 0;
  74034. this.hdrPostProcess.onApply = function (effect) {
  74035. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74036. time += scene.getEngine().getDeltaTime();
  74037. if (outputLiminance < 0) {
  74038. outputLiminance = _this._hdrCurrentLuminance;
  74039. }
  74040. else {
  74041. var dt = (lastTime - time) / 1000.0;
  74042. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74043. outputLiminance += _this.hdrDecreaseRate * dt;
  74044. }
  74045. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74046. outputLiminance -= _this.hdrIncreaseRate * dt;
  74047. }
  74048. else {
  74049. outputLiminance = _this._hdrCurrentLuminance;
  74050. }
  74051. }
  74052. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74053. effect.setFloat("averageLuminance", outputLiminance);
  74054. lastTime = time;
  74055. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74056. };
  74057. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74058. };
  74059. // Create lens flare post-process
  74060. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74061. var _this = this;
  74062. 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);
  74063. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74064. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74065. 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);
  74066. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74067. var resolution = new BABYLON.Vector2(0, 0);
  74068. // Lens flare
  74069. this.lensFlarePostProcess.onApply = function (effect) {
  74070. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74071. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74072. effect.setFloat("strength", _this.lensFlareStrength);
  74073. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74074. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74075. // Shift
  74076. resolution.x = _this.lensFlarePostProcess.width;
  74077. resolution.y = _this.lensFlarePostProcess.height;
  74078. effect.setVector2("resolution", resolution);
  74079. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74080. };
  74081. // Compose
  74082. 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);
  74083. 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);
  74084. this.lensFlareComposePostProcess.onApply = function (effect) {
  74085. if (!_this._scene.activeCamera) {
  74086. return;
  74087. }
  74088. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74089. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74090. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74091. // Lens start rotation matrix
  74092. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74093. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74094. 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));
  74095. camRot *= 4.0;
  74096. 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);
  74097. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74098. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74099. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74100. };
  74101. };
  74102. // Create depth-of-field post-process
  74103. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74104. var _this = this;
  74105. 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);
  74106. this.depthOfFieldPostProcess.onApply = function (effect) {
  74107. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74108. effect.setTexture("depthSampler", _this._getDepthTexture());
  74109. effect.setFloat("distance", _this.depthOfFieldDistance);
  74110. };
  74111. // Add to pipeline
  74112. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74113. };
  74114. // Create motion blur post-process
  74115. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74116. var _this = this;
  74117. 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);
  74118. var motionScale = 0;
  74119. var prevViewProjection = BABYLON.Matrix.Identity();
  74120. var invViewProjection = BABYLON.Matrix.Identity();
  74121. var viewProjection = BABYLON.Matrix.Identity();
  74122. var screenSize = BABYLON.Vector2.Zero();
  74123. this.motionBlurPostProcess.onApply = function (effect) {
  74124. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74125. viewProjection.invertToRef(invViewProjection);
  74126. effect.setMatrix("inverseViewProjection", invViewProjection);
  74127. effect.setMatrix("prevViewProjection", prevViewProjection);
  74128. prevViewProjection = viewProjection;
  74129. screenSize.x = _this.motionBlurPostProcess.width;
  74130. screenSize.y = _this.motionBlurPostProcess.height;
  74131. effect.setVector2("screenSize", screenSize);
  74132. motionScale = scene.getEngine().getFps() / 60.0;
  74133. effect.setFloat("motionScale", motionScale);
  74134. effect.setFloat("motionStrength", _this.motionStrength);
  74135. effect.setTexture("depthSampler", _this._getDepthTexture());
  74136. };
  74137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74138. };
  74139. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74140. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74141. var renderer = this._scene.enableGeometryBufferRenderer();
  74142. return renderer.getGBuffer().textures[0];
  74143. }
  74144. return this._scene.enableDepthRenderer().getDepthMap();
  74145. };
  74146. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74147. for (var i = 0; i < this._cameras.length; i++) {
  74148. var camera = this._cameras[i];
  74149. if (this.originalPostProcess) {
  74150. this.originalPostProcess.dispose(camera);
  74151. }
  74152. if (this.downSampleX4PostProcess) {
  74153. this.downSampleX4PostProcess.dispose(camera);
  74154. }
  74155. if (this.brightPassPostProcess) {
  74156. this.brightPassPostProcess.dispose(camera);
  74157. }
  74158. if (this.textureAdderPostProcess) {
  74159. this.textureAdderPostProcess.dispose(camera);
  74160. }
  74161. if (this.textureAdderFinalPostProcess) {
  74162. this.textureAdderFinalPostProcess.dispose(camera);
  74163. }
  74164. if (this.volumetricLightPostProcess) {
  74165. this.volumetricLightPostProcess.dispose(camera);
  74166. }
  74167. if (this.volumetricLightSmoothXPostProcess) {
  74168. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74169. }
  74170. if (this.volumetricLightSmoothYPostProcess) {
  74171. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74172. }
  74173. if (this.volumetricLightMergePostProces) {
  74174. this.volumetricLightMergePostProces.dispose(camera);
  74175. }
  74176. if (this.volumetricLightFinalPostProcess) {
  74177. this.volumetricLightFinalPostProcess.dispose(camera);
  74178. }
  74179. if (this.lensFlarePostProcess) {
  74180. this.lensFlarePostProcess.dispose(camera);
  74181. }
  74182. if (this.lensFlareComposePostProcess) {
  74183. this.lensFlareComposePostProcess.dispose(camera);
  74184. }
  74185. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74186. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74187. }
  74188. if (this.luminancePostProcess) {
  74189. this.luminancePostProcess.dispose(camera);
  74190. }
  74191. if (this.hdrPostProcess) {
  74192. this.hdrPostProcess.dispose(camera);
  74193. }
  74194. if (this.hdrFinalPostProcess) {
  74195. this.hdrFinalPostProcess.dispose(camera);
  74196. }
  74197. if (this.depthOfFieldPostProcess) {
  74198. this.depthOfFieldPostProcess.dispose(camera);
  74199. }
  74200. if (this.motionBlurPostProcess) {
  74201. this.motionBlurPostProcess.dispose(camera);
  74202. }
  74203. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74204. this.blurHPostProcesses[j].dispose(camera);
  74205. }
  74206. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74207. this.blurVPostProcesses[j].dispose(camera);
  74208. }
  74209. }
  74210. this.originalPostProcess = null;
  74211. this.downSampleX4PostProcess = null;
  74212. this.brightPassPostProcess = null;
  74213. this.textureAdderPostProcess = null;
  74214. this.textureAdderFinalPostProcess = null;
  74215. this.volumetricLightPostProcess = null;
  74216. this.volumetricLightSmoothXPostProcess = null;
  74217. this.volumetricLightSmoothYPostProcess = null;
  74218. this.volumetricLightMergePostProces = null;
  74219. this.volumetricLightFinalPostProcess = null;
  74220. this.lensFlarePostProcess = null;
  74221. this.lensFlareComposePostProcess = null;
  74222. this.luminancePostProcess = null;
  74223. this.hdrPostProcess = null;
  74224. this.hdrFinalPostProcess = null;
  74225. this.depthOfFieldPostProcess = null;
  74226. this.motionBlurPostProcess = null;
  74227. this.luminanceDownSamplePostProcesses = [];
  74228. this.blurHPostProcesses = [];
  74229. this.blurVPostProcesses = [];
  74230. };
  74231. /**
  74232. * Dispose of the pipeline and stop all post processes
  74233. */
  74234. StandardRenderingPipeline.prototype.dispose = function () {
  74235. this._disposePostProcesses();
  74236. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74237. _super.prototype.dispose.call(this);
  74238. };
  74239. /**
  74240. * Serialize the rendering pipeline (Used when exporting)
  74241. * @returns the serialized object
  74242. */
  74243. StandardRenderingPipeline.prototype.serialize = function () {
  74244. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74245. if (this.sourceLight) {
  74246. serializationObject.sourceLightId = this.sourceLight.id;
  74247. }
  74248. serializationObject.customType = "StandardRenderingPipeline";
  74249. return serializationObject;
  74250. };
  74251. /**
  74252. * Parse the serialized pipeline
  74253. * @param source Source pipeline.
  74254. * @param scene The scene to load the pipeline to.
  74255. * @param rootUrl The URL of the serialized pipeline.
  74256. * @returns An instantiated pipeline from the serialized object.
  74257. */
  74258. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74259. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74260. if (source.sourceLightId) {
  74261. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74262. }
  74263. return p;
  74264. };
  74265. // Luminance steps
  74266. StandardRenderingPipeline.LuminanceSteps = 6;
  74267. __decorate([
  74268. BABYLON.serialize()
  74269. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74270. __decorate([
  74271. BABYLON.serialize()
  74272. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74273. __decorate([
  74274. BABYLON.serialize()
  74275. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74276. __decorate([
  74277. BABYLON.serialize()
  74278. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74279. __decorate([
  74280. BABYLON.serializeAsTexture("lensTexture")
  74281. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74282. __decorate([
  74283. BABYLON.serialize()
  74284. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74285. __decorate([
  74286. BABYLON.serialize()
  74287. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74288. __decorate([
  74289. BABYLON.serialize()
  74290. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74291. __decorate([
  74292. BABYLON.serialize()
  74293. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74294. __decorate([
  74295. BABYLON.serialize()
  74296. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74297. __decorate([
  74298. BABYLON.serialize()
  74299. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74300. __decorate([
  74301. BABYLON.serializeAsTexture("lensColorTexture")
  74302. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74303. __decorate([
  74304. BABYLON.serialize()
  74305. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74306. __decorate([
  74307. BABYLON.serialize()
  74308. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74309. __decorate([
  74310. BABYLON.serialize()
  74311. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74312. __decorate([
  74313. BABYLON.serialize()
  74314. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74315. __decorate([
  74316. BABYLON.serializeAsTexture("lensStarTexture")
  74317. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74318. __decorate([
  74319. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74320. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74321. __decorate([
  74322. BABYLON.serialize()
  74323. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74324. __decorate([
  74325. BABYLON.serialize()
  74326. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74327. __decorate([
  74328. BABYLON.serialize()
  74329. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74330. __decorate([
  74331. BABYLON.serialize()
  74332. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74333. __decorate([
  74334. BABYLON.serialize()
  74335. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74336. __decorate([
  74337. BABYLON.serialize()
  74338. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74339. __decorate([
  74340. BABYLON.serialize()
  74341. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74342. __decorate([
  74343. BABYLON.serialize()
  74344. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74345. __decorate([
  74346. BABYLON.serialize()
  74347. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74348. __decorate([
  74349. BABYLON.serialize()
  74350. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74351. __decorate([
  74352. BABYLON.serialize()
  74353. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74354. __decorate([
  74355. BABYLON.serialize()
  74356. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74357. return StandardRenderingPipeline;
  74358. }(BABYLON.PostProcessRenderPipeline));
  74359. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74360. })(BABYLON || (BABYLON = {}));
  74361. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74362. var BABYLON;
  74363. (function (BABYLON) {
  74364. var FxaaPostProcess = /** @class */ (function (_super) {
  74365. __extends(FxaaPostProcess, _super);
  74366. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74367. if (camera === void 0) { camera = null; }
  74368. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74369. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  74370. _this.onApplyObservable.add(function (effect) {
  74371. var texelSize = _this.texelSize;
  74372. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74373. });
  74374. return _this;
  74375. }
  74376. return FxaaPostProcess;
  74377. }(BABYLON.PostProcess));
  74378. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74379. })(BABYLON || (BABYLON = {}));
  74380. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74381. var BABYLON;
  74382. (function (BABYLON) {
  74383. /**
  74384. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74385. */
  74386. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74387. __extends(ChromaticAberrationPostProcess, _super);
  74388. /**
  74389. * Creates a new instance ChromaticAberrationPostProcess
  74390. * @param name The name of the effect.
  74391. * @param screenWidth The width of the screen to apply the effect on.
  74392. * @param screenHeight The height of the screen to apply the effect on.
  74393. * @param options The required width/height ratio to downsize to before computing the render pass.
  74394. * @param camera The camera to apply the render pass to.
  74395. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74396. * @param engine The engine which the post process will be applied. (default: current engine)
  74397. * @param reusable If the post process can be reused on the same frame. (default: false)
  74398. * @param textureType Type of textures used when performing the post process. (default: 0)
  74399. * @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)
  74400. */
  74401. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74402. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74403. if (blockCompilation === void 0) { blockCompilation = false; }
  74404. 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;
  74405. /**
  74406. * The amount of seperation of rgb channels (default: 30)
  74407. */
  74408. _this.aberrationAmount = 30;
  74409. /**
  74410. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74411. */
  74412. _this.radialIntensity = 0;
  74413. /**
  74414. * 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))
  74415. */
  74416. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74417. /**
  74418. * 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))
  74419. */
  74420. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74421. _this.onApplyObservable.add(function (effect) {
  74422. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74423. effect.setFloat('screen_width', screenWidth);
  74424. effect.setFloat('screen_height', screenHeight);
  74425. effect.setFloat('radialIntensity', _this.radialIntensity);
  74426. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74427. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74428. });
  74429. return _this;
  74430. }
  74431. return ChromaticAberrationPostProcess;
  74432. }(BABYLON.PostProcess));
  74433. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74434. })(BABYLON || (BABYLON = {}));
  74435. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74436. var BABYLON;
  74437. (function (BABYLON) {
  74438. /**
  74439. * The GrainPostProcess adds noise to the image at mid luminance levels
  74440. */
  74441. var GrainPostProcess = /** @class */ (function (_super) {
  74442. __extends(GrainPostProcess, _super);
  74443. /**
  74444. * Creates a new instance of @see GrainPostProcess
  74445. * @param name The name of the effect.
  74446. * @param options The required width/height ratio to downsize to before computing the render pass.
  74447. * @param camera The camera to apply the render pass to.
  74448. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74449. * @param engine The engine which the post process will be applied. (default: current engine)
  74450. * @param reusable If the post process can be reused on the same frame. (default: false)
  74451. * @param textureType Type of textures used when performing the post process. (default: 0)
  74452. * @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)
  74453. */
  74454. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74455. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74456. if (blockCompilation === void 0) { blockCompilation = false; }
  74457. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74458. /**
  74459. * The intensity of the grain added (default: 30)
  74460. */
  74461. _this.intensity = 30;
  74462. /**
  74463. * If the grain should be randomized on every frame
  74464. */
  74465. _this.animated = false;
  74466. _this.onApplyObservable.add(function (effect) {
  74467. effect.setFloat('intensity', _this.intensity);
  74468. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74469. });
  74470. return _this;
  74471. }
  74472. return GrainPostProcess;
  74473. }(BABYLON.PostProcess));
  74474. BABYLON.GrainPostProcess = GrainPostProcess;
  74475. })(BABYLON || (BABYLON = {}));
  74476. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74477. var BABYLON;
  74478. (function (BABYLON) {
  74479. /**
  74480. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74481. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74482. */
  74483. var SharpenPostProcess = /** @class */ (function (_super) {
  74484. __extends(SharpenPostProcess, _super);
  74485. /**
  74486. * Creates a new instance ConvolutionPostProcess
  74487. * @param name The name of the effect.
  74488. * @param options The required width/height ratio to downsize to before computing the render pass.
  74489. * @param camera The camera to apply the render pass to.
  74490. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74491. * @param engine The engine which the post process will be applied. (default: current engine)
  74492. * @param reusable If the post process can be reused on the same frame. (default: false)
  74493. * @param textureType Type of textures used when performing the post process. (default: 0)
  74494. * @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)
  74495. */
  74496. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74497. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74498. if (blockCompilation === void 0) { blockCompilation = false; }
  74499. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74500. /**
  74501. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74502. */
  74503. _this.colorAmount = 1.0;
  74504. /**
  74505. * How much sharpness should be applied (default: 0.3)
  74506. */
  74507. _this.edgeAmount = 0.3;
  74508. _this.onApply = function (effect) {
  74509. effect.setFloat2("screenSize", _this.width, _this.height);
  74510. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74511. };
  74512. return _this;
  74513. }
  74514. return SharpenPostProcess;
  74515. }(BABYLON.PostProcess));
  74516. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74517. })(BABYLON || (BABYLON = {}));
  74518. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74519. var BABYLON;
  74520. (function (BABYLON) {
  74521. /**
  74522. * The Blur Post Process which blurs an image based on a kernel and direction.
  74523. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74524. */
  74525. var BlurPostProcess = /** @class */ (function (_super) {
  74526. __extends(BlurPostProcess, _super);
  74527. /**
  74528. * Creates a new instance BlurPostProcess
  74529. * @param name The name of the effect.
  74530. * @param direction The direction in which to blur the image.
  74531. * @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.
  74532. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74533. * @param camera The camera to apply the render pass to.
  74534. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74535. * @param engine The engine which the post process will be applied. (default: current engine)
  74536. * @param reusable If the post process can be reused on the same frame. (default: false)
  74537. * @param textureType Type of textures used when performing the post process. (default: 0)
  74538. * @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)
  74539. */
  74540. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74541. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74542. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74543. if (defines === void 0) { defines = ""; }
  74544. if (blockCompilation === void 0) { blockCompilation = false; }
  74545. 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;
  74546. _this.direction = direction;
  74547. _this.blockCompilation = blockCompilation;
  74548. _this._packedFloat = false;
  74549. _this._staticDefines = "";
  74550. _this._staticDefines = defines;
  74551. _this.onApplyObservable.add(function (effect) {
  74552. if (_this._outputTexture) {
  74553. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74554. }
  74555. else {
  74556. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74557. }
  74558. });
  74559. _this.kernel = kernel;
  74560. return _this;
  74561. }
  74562. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74563. /**
  74564. * Gets the length in pixels of the blur sample region
  74565. */
  74566. get: function () {
  74567. return this._idealKernel;
  74568. },
  74569. /**
  74570. * Sets the length in pixels of the blur sample region
  74571. */
  74572. set: function (v) {
  74573. if (this._idealKernel === v) {
  74574. return;
  74575. }
  74576. v = Math.max(v, 1);
  74577. this._idealKernel = v;
  74578. this._kernel = this._nearestBestKernel(v);
  74579. if (!this.blockCompilation) {
  74580. this._updateParameters();
  74581. }
  74582. },
  74583. enumerable: true,
  74584. configurable: true
  74585. });
  74586. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74587. /**
  74588. * Gets wether or not the blur is unpacking/repacking floats
  74589. */
  74590. get: function () {
  74591. return this._packedFloat;
  74592. },
  74593. /**
  74594. * Sets wether or not the blur needs to unpack/repack floats
  74595. */
  74596. set: function (v) {
  74597. if (this._packedFloat === v) {
  74598. return;
  74599. }
  74600. this._packedFloat = v;
  74601. if (!this.blockCompilation) {
  74602. this._updateParameters();
  74603. }
  74604. },
  74605. enumerable: true,
  74606. configurable: true
  74607. });
  74608. /**
  74609. * Updates the effect with the current post process compile time values and recompiles the shader.
  74610. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74611. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74612. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74613. * @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
  74614. * @param onCompiled Called when the shader has been compiled.
  74615. * @param onError Called if there is an error when compiling a shader.
  74616. */
  74617. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74618. if (defines === void 0) { defines = null; }
  74619. if (uniforms === void 0) { uniforms = null; }
  74620. if (samplers === void 0) { samplers = null; }
  74621. this._updateParameters(onCompiled, onError);
  74622. };
  74623. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74624. // Generate sampling offsets and weights
  74625. var N = this._kernel;
  74626. var centerIndex = (N - 1) / 2;
  74627. // Generate Gaussian sampling weights over kernel
  74628. var offsets = [];
  74629. var weights = [];
  74630. var totalWeight = 0;
  74631. for (var i = 0; i < N; i++) {
  74632. var u = i / (N - 1);
  74633. var w = this._gaussianWeight(u * 2.0 - 1);
  74634. offsets[i] = (i - centerIndex);
  74635. weights[i] = w;
  74636. totalWeight += w;
  74637. }
  74638. // Normalize weights
  74639. for (var i = 0; i < weights.length; i++) {
  74640. weights[i] /= totalWeight;
  74641. }
  74642. // Optimize: combine samples to take advantage of hardware linear sampling
  74643. // Walk from left to center, combining pairs (symmetrically)
  74644. var linearSamplingWeights = [];
  74645. var linearSamplingOffsets = [];
  74646. var linearSamplingMap = [];
  74647. for (var i = 0; i <= centerIndex; i += 2) {
  74648. var j = Math.min(i + 1, Math.floor(centerIndex));
  74649. var singleCenterSample = i === j;
  74650. if (singleCenterSample) {
  74651. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74652. }
  74653. else {
  74654. var sharedCell = j === centerIndex;
  74655. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74656. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74657. if (offsetLinear === 0) {
  74658. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74659. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74660. }
  74661. else {
  74662. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74663. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74664. }
  74665. }
  74666. }
  74667. for (var i = 0; i < linearSamplingMap.length; i++) {
  74668. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74669. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74670. }
  74671. // Replace with optimized
  74672. offsets = linearSamplingOffsets;
  74673. weights = linearSamplingWeights;
  74674. // Generate shaders
  74675. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74676. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74677. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74678. var defines = "";
  74679. defines += this._staticDefines;
  74680. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74681. if (this._staticDefines.indexOf("DOF") != -1) {
  74682. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74683. varyingCount--;
  74684. }
  74685. for (var i = 0; i < varyingCount; i++) {
  74686. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74687. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74688. }
  74689. var depCount = 0;
  74690. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74691. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74692. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74693. depCount++;
  74694. }
  74695. if (this.packedFloat) {
  74696. defines += "#define PACKEDFLOAT 1";
  74697. }
  74698. this.blockCompilation = false;
  74699. _super.prototype.updateEffect.call(this, defines, null, null, {
  74700. varyingCount: varyingCount,
  74701. depCount: depCount
  74702. }, onCompiled, onError);
  74703. };
  74704. /**
  74705. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74706. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74707. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74708. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74709. * The gaps between physical kernels are compensated for in the weighting of the samples
  74710. * @param idealKernel Ideal blur kernel.
  74711. * @return Nearest best kernel.
  74712. */
  74713. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74714. var v = Math.round(idealKernel);
  74715. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74716. var k = _a[_i];
  74717. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74718. return Math.max(k, 3);
  74719. }
  74720. }
  74721. return Math.max(v, 3);
  74722. };
  74723. /**
  74724. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74725. * @param x The point on the Gaussian distribution to sample.
  74726. * @return the value of the Gaussian function at x.
  74727. */
  74728. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74729. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74730. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74731. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74732. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74733. // truncated at around 1.3% of peak strength.
  74734. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74735. var sigma = (1 / 3);
  74736. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74737. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74738. var weight = (1.0 / denominator) * Math.exp(exponent);
  74739. return weight;
  74740. };
  74741. /**
  74742. * Generates a string that can be used as a floating point number in GLSL.
  74743. * @param x Value to print.
  74744. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74745. * @return GLSL float string.
  74746. */
  74747. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74748. if (decimalFigures === void 0) { decimalFigures = 8; }
  74749. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74750. };
  74751. return BlurPostProcess;
  74752. }(BABYLON.PostProcess));
  74753. BABYLON.BlurPostProcess = BlurPostProcess;
  74754. })(BABYLON || (BABYLON = {}));
  74755. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74756. var BABYLON;
  74757. (function (BABYLON) {
  74758. /**
  74759. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74760. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74761. * based on samples that have a large difference in distance than the center pixel.
  74762. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74763. */
  74764. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74765. __extends(DepthOfFieldBlurPostProcess, _super);
  74766. /**
  74767. * Creates a new instance CircleOfConfusionPostProcess
  74768. * @param name The name of the effect.
  74769. * @param scene The scene the effect belongs to.
  74770. * @param direction The direction the blur should be applied.
  74771. * @param kernel The size of the kernel used to blur.
  74772. * @param options The required width/height ratio to downsize to before computing the render pass.
  74773. * @param camera The camera to apply the render pass to.
  74774. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74775. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74776. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74777. * @param engine The engine which the post process will be applied. (default: current engine)
  74778. * @param reusable If the post process can be reused on the same frame. (default: false)
  74779. * @param textureType Type of textures used when performing the post process. (default: 0)
  74780. * @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)
  74781. */
  74782. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74783. if (imageToBlur === void 0) { imageToBlur = null; }
  74784. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74785. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74786. if (blockCompilation === void 0) { blockCompilation = false; }
  74787. 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;
  74788. _this.direction = direction;
  74789. _this.onApplyObservable.add(function (effect) {
  74790. if (imageToBlur != null) {
  74791. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74792. }
  74793. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74794. if (scene.activeCamera) {
  74795. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74796. }
  74797. });
  74798. return _this;
  74799. }
  74800. return DepthOfFieldBlurPostProcess;
  74801. }(BABYLON.BlurPostProcess));
  74802. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74803. })(BABYLON || (BABYLON = {}));
  74804. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74805. var BABYLON;
  74806. (function (BABYLON) {
  74807. /**
  74808. * Options to be set when merging outputs from the default pipeline.
  74809. */
  74810. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74811. function DepthOfFieldMergePostProcessOptions() {
  74812. }
  74813. return DepthOfFieldMergePostProcessOptions;
  74814. }());
  74815. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74816. /**
  74817. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74818. */
  74819. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74820. __extends(DepthOfFieldMergePostProcess, _super);
  74821. /**
  74822. * Creates a new instance of DepthOfFieldMergePostProcess
  74823. * @param name The name of the effect.
  74824. * @param originalFromInput Post process which's input will be used for the merge.
  74825. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74826. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74827. * @param options The required width/height ratio to downsize to before computing the render pass.
  74828. * @param camera The camera to apply the render pass to.
  74829. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74830. * @param engine The engine which the post process will be applied. (default: current engine)
  74831. * @param reusable If the post process can be reused on the same frame. (default: false)
  74832. * @param textureType Type of textures used when performing the post process. (default: 0)
  74833. * @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)
  74834. */
  74835. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74836. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74837. if (blockCompilation === void 0) { blockCompilation = false; }
  74838. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74839. _this.blurSteps = blurSteps;
  74840. _this.onApplyObservable.add(function (effect) {
  74841. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74842. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74843. blurSteps.forEach(function (step, index) {
  74844. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74845. });
  74846. });
  74847. if (!blockCompilation) {
  74848. _this.updateEffect();
  74849. }
  74850. return _this;
  74851. }
  74852. /**
  74853. * Updates the effect with the current post process compile time values and recompiles the shader.
  74854. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74855. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74856. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74857. * @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
  74858. * @param onCompiled Called when the shader has been compiled.
  74859. * @param onError Called if there is an error when compiling a shader.
  74860. */
  74861. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74862. if (defines === void 0) { defines = null; }
  74863. if (uniforms === void 0) { uniforms = null; }
  74864. if (samplers === void 0) { samplers = null; }
  74865. if (!defines) {
  74866. defines = "";
  74867. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74868. }
  74869. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74870. };
  74871. return DepthOfFieldMergePostProcess;
  74872. }(BABYLON.PostProcess));
  74873. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74874. })(BABYLON || (BABYLON = {}));
  74875. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74876. var BABYLON;
  74877. (function (BABYLON) {
  74878. /**
  74879. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74880. */
  74881. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74882. __extends(CircleOfConfusionPostProcess, _super);
  74883. /**
  74884. * Creates a new instance CircleOfConfusionPostProcess
  74885. * @param name The name of the effect.
  74886. * @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.
  74887. * @param options The required width/height ratio to downsize to before computing the render pass.
  74888. * @param camera The camera to apply the render pass to.
  74889. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74890. * @param engine The engine which the post process will be applied. (default: current engine)
  74891. * @param reusable If the post process can be reused on the same frame. (default: false)
  74892. * @param textureType Type of textures used when performing the post process. (default: 0)
  74893. * @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)
  74894. */
  74895. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74896. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74897. if (blockCompilation === void 0) { blockCompilation = false; }
  74898. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74899. /**
  74900. * 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.
  74901. */
  74902. _this.lensSize = 50;
  74903. /**
  74904. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74905. */
  74906. _this.fStop = 1.4;
  74907. /**
  74908. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74909. */
  74910. _this.focusDistance = 2000;
  74911. /**
  74912. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74913. */
  74914. _this.focalLength = 50;
  74915. _this._depthTexture = null;
  74916. _this._depthTexture = depthTexture;
  74917. _this.onApplyObservable.add(function (effect) {
  74918. if (!_this._depthTexture) {
  74919. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74920. return;
  74921. }
  74922. effect.setTexture("depthSampler", _this._depthTexture);
  74923. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74924. var aperture = _this.lensSize / _this.fStop;
  74925. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74926. effect.setFloat('focusDistance', _this.focusDistance);
  74927. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74928. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74929. });
  74930. return _this;
  74931. }
  74932. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74933. /**
  74934. * 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.
  74935. */
  74936. set: function (value) {
  74937. this._depthTexture = value;
  74938. },
  74939. enumerable: true,
  74940. configurable: true
  74941. });
  74942. return CircleOfConfusionPostProcess;
  74943. }(BABYLON.PostProcess));
  74944. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74945. })(BABYLON || (BABYLON = {}));
  74946. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74947. var BABYLON;
  74948. (function (BABYLON) {
  74949. /**
  74950. * Specifies the level of max blur that should be applied when using the depth of field effect
  74951. */
  74952. var DepthOfFieldEffectBlurLevel;
  74953. (function (DepthOfFieldEffectBlurLevel) {
  74954. /**
  74955. * Subtle blur
  74956. */
  74957. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74958. /**
  74959. * Medium blur
  74960. */
  74961. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74962. /**
  74963. * Large blur
  74964. */
  74965. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74966. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74967. ;
  74968. /**
  74969. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74970. */
  74971. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74972. __extends(DepthOfFieldEffect, _super);
  74973. /**
  74974. * Creates a new instance DepthOfFieldEffect
  74975. * @param scene The scene the effect belongs to.
  74976. * @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.
  74977. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74978. * @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)
  74979. */
  74980. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74981. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74982. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74983. if (blockCompilation === void 0) { blockCompilation = false; }
  74984. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74985. return _this._effects;
  74986. }, true) || this;
  74987. /**
  74988. * Internal post processes in depth of field effect
  74989. */
  74990. _this._effects = [];
  74991. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74992. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74993. // 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)
  74994. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74995. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74996. _this._depthOfFieldBlurY = [];
  74997. _this._depthOfFieldBlurX = [];
  74998. var blurCount = 1;
  74999. var kernelSize = 15;
  75000. switch (blurLevel) {
  75001. case DepthOfFieldEffectBlurLevel.High: {
  75002. blurCount = 3;
  75003. kernelSize = 51;
  75004. break;
  75005. }
  75006. case DepthOfFieldEffectBlurLevel.Medium: {
  75007. blurCount = 2;
  75008. kernelSize = 31;
  75009. break;
  75010. }
  75011. default: {
  75012. kernelSize = 15;
  75013. blurCount = 1;
  75014. break;
  75015. }
  75016. }
  75017. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75018. var ratio = 1.0;
  75019. for (var i = 0; i < blurCount; i++) {
  75020. 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);
  75021. blurY.autoClear = false;
  75022. ratio = 0.75 / Math.pow(2, i);
  75023. 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);
  75024. blurX.autoClear = false;
  75025. _this._depthOfFieldBlurY.push(blurY);
  75026. _this._depthOfFieldBlurX.push(blurX);
  75027. }
  75028. // Set all post processes on the effect.
  75029. _this._effects = [_this._circleOfConfusion];
  75030. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75031. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75032. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75033. }
  75034. // Merge blurred images with original image based on circleOfConfusion
  75035. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75036. _this._dofMerge.autoClear = false;
  75037. _this._effects.push(_this._dofMerge);
  75038. return _this;
  75039. }
  75040. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75041. get: function () {
  75042. return this._circleOfConfusion.focalLength;
  75043. },
  75044. /**
  75045. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75046. */
  75047. set: function (value) {
  75048. this._circleOfConfusion.focalLength = value;
  75049. },
  75050. enumerable: true,
  75051. configurable: true
  75052. });
  75053. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75054. get: function () {
  75055. return this._circleOfConfusion.fStop;
  75056. },
  75057. /**
  75058. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75059. */
  75060. set: function (value) {
  75061. this._circleOfConfusion.fStop = value;
  75062. },
  75063. enumerable: true,
  75064. configurable: true
  75065. });
  75066. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75067. get: function () {
  75068. return this._circleOfConfusion.focusDistance;
  75069. },
  75070. /**
  75071. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75072. */
  75073. set: function (value) {
  75074. this._circleOfConfusion.focusDistance = value;
  75075. },
  75076. enumerable: true,
  75077. configurable: true
  75078. });
  75079. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75080. get: function () {
  75081. return this._circleOfConfusion.lensSize;
  75082. },
  75083. /**
  75084. * 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.
  75085. */
  75086. set: function (value) {
  75087. this._circleOfConfusion.lensSize = value;
  75088. },
  75089. enumerable: true,
  75090. configurable: true
  75091. });
  75092. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75093. /**
  75094. * 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.
  75095. */
  75096. set: function (value) {
  75097. this._circleOfConfusion.depthTexture = value;
  75098. },
  75099. enumerable: true,
  75100. configurable: true
  75101. });
  75102. /**
  75103. * Disposes each of the internal effects for a given camera.
  75104. * @param camera The camera to dispose the effect on.
  75105. */
  75106. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75107. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75108. this._effects[effectIndex].dispose(camera);
  75109. }
  75110. };
  75111. /**
  75112. * Internal
  75113. */
  75114. DepthOfFieldEffect.prototype._updateEffects = function () {
  75115. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75116. this._effects[effectIndex].updateEffect();
  75117. }
  75118. };
  75119. /**
  75120. * Internal
  75121. * @returns if all the contained post processes are ready.
  75122. */
  75123. DepthOfFieldEffect.prototype._isReady = function () {
  75124. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75125. if (!this._effects[effectIndex].isReady()) {
  75126. return false;
  75127. }
  75128. }
  75129. return true;
  75130. };
  75131. return DepthOfFieldEffect;
  75132. }(BABYLON.PostProcessRenderEffect));
  75133. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75134. })(BABYLON || (BABYLON = {}));
  75135. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75136. var BABYLON;
  75137. (function (BABYLON) {
  75138. /**
  75139. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75140. */
  75141. var BloomMergePostProcess = /** @class */ (function (_super) {
  75142. __extends(BloomMergePostProcess, _super);
  75143. /**
  75144. * Creates a new instance of @see BloomMergePostProcess
  75145. * @param name The name of the effect.
  75146. * @param originalFromInput Post process which's input will be used for the merge.
  75147. * @param blurred Blurred highlights post process which's output will be used.
  75148. * @param weight Weight of the bloom to be added to the original input.
  75149. * @param options The required width/height ratio to downsize to before computing the render pass.
  75150. * @param camera The camera to apply the render pass to.
  75151. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75152. * @param engine The engine which the post process will be applied. (default: current engine)
  75153. * @param reusable If the post process can be reused on the same frame. (default: false)
  75154. * @param textureType Type of textures used when performing the post process. (default: 0)
  75155. * @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)
  75156. */
  75157. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75158. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75159. if (blockCompilation === void 0) { blockCompilation = false; }
  75160. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75161. _this.weight = weight;
  75162. _this.onApplyObservable.add(function (effect) {
  75163. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75164. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75165. effect.setFloat("bloomWeight", _this.weight);
  75166. });
  75167. if (!blockCompilation) {
  75168. _this.updateEffect();
  75169. }
  75170. return _this;
  75171. }
  75172. return BloomMergePostProcess;
  75173. }(BABYLON.PostProcess));
  75174. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75175. })(BABYLON || (BABYLON = {}));
  75176. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75177. var BABYLON;
  75178. (function (BABYLON) {
  75179. /**
  75180. * 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.
  75181. */
  75182. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75183. __extends(ExtractHighlightsPostProcess, _super);
  75184. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75185. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75186. if (blockCompilation === void 0) { blockCompilation = false; }
  75187. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75188. /**
  75189. * The luminance threshold, pixels below this value will be set to black.
  75190. */
  75191. _this.threshold = 0.9;
  75192. /**
  75193. * Internal
  75194. */
  75195. _this._exposure = 1;
  75196. /**
  75197. * Post process which has the input texture to be used when performing highlight extraction
  75198. */
  75199. _this._inputPostProcess = null;
  75200. _this.onApplyObservable.add(function (effect) {
  75201. if (_this._inputPostProcess) {
  75202. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75203. }
  75204. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75205. effect.setFloat('exposure', _this._exposure);
  75206. });
  75207. return _this;
  75208. }
  75209. return ExtractHighlightsPostProcess;
  75210. }(BABYLON.PostProcess));
  75211. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75212. })(BABYLON || (BABYLON = {}));
  75213. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75214. var BABYLON;
  75215. (function (BABYLON) {
  75216. /**
  75217. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75218. */
  75219. var BloomEffect = /** @class */ (function (_super) {
  75220. __extends(BloomEffect, _super);
  75221. /**
  75222. * Creates a new instance of @see BloomEffect
  75223. * @param scene The scene the effect belongs to.
  75224. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75225. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75226. * @param bloomWeight The the strength of bloom.
  75227. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75228. * @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)
  75229. */
  75230. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75231. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75232. if (blockCompilation === void 0) { blockCompilation = false; }
  75233. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75234. return _this._effects;
  75235. }, true) || this;
  75236. _this.bloomScale = bloomScale;
  75237. /**
  75238. * Internal
  75239. */
  75240. _this._effects = [];
  75241. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75242. _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);
  75243. _this._blurX.alwaysForcePOT = true;
  75244. _this._blurX.autoClear = false;
  75245. _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);
  75246. _this._blurY.alwaysForcePOT = true;
  75247. _this._blurY.autoClear = false;
  75248. _this.kernel = bloomKernel;
  75249. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75250. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75251. _this._merge.autoClear = false;
  75252. _this._effects.push(_this._merge);
  75253. return _this;
  75254. }
  75255. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75256. /**
  75257. * The luminance threshold to find bright areas of the image to bloom.
  75258. */
  75259. get: function () {
  75260. return this._downscale.threshold;
  75261. },
  75262. set: function (value) {
  75263. this._downscale.threshold = value;
  75264. },
  75265. enumerable: true,
  75266. configurable: true
  75267. });
  75268. Object.defineProperty(BloomEffect.prototype, "weight", {
  75269. /**
  75270. * The strength of the bloom.
  75271. */
  75272. get: function () {
  75273. return this._merge.weight;
  75274. },
  75275. set: function (value) {
  75276. this._merge.weight = value;
  75277. },
  75278. enumerable: true,
  75279. configurable: true
  75280. });
  75281. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75282. /**
  75283. * Specifies the size of the bloom blur kernel, relative to the final output size
  75284. */
  75285. get: function () {
  75286. return this._blurX.kernel / this.bloomScale;
  75287. },
  75288. set: function (value) {
  75289. this._blurX.kernel = value * this.bloomScale;
  75290. this._blurY.kernel = value * this.bloomScale;
  75291. },
  75292. enumerable: true,
  75293. configurable: true
  75294. });
  75295. /**
  75296. * Disposes each of the internal effects for a given camera.
  75297. * @param camera The camera to dispose the effect on.
  75298. */
  75299. BloomEffect.prototype.disposeEffects = function (camera) {
  75300. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75301. this._effects[effectIndex].dispose(camera);
  75302. }
  75303. };
  75304. /**
  75305. * Internal
  75306. */
  75307. BloomEffect.prototype._updateEffects = function () {
  75308. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75309. this._effects[effectIndex].updateEffect();
  75310. }
  75311. };
  75312. /**
  75313. * Internal
  75314. * @returns if all the contained post processes are ready.
  75315. */
  75316. BloomEffect.prototype._isReady = function () {
  75317. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75318. if (!this._effects[effectIndex].isReady()) {
  75319. return false;
  75320. }
  75321. }
  75322. return true;
  75323. };
  75324. return BloomEffect;
  75325. }(BABYLON.PostProcessRenderEffect));
  75326. BABYLON.BloomEffect = BloomEffect;
  75327. })(BABYLON || (BABYLON = {}));
  75328. //# sourceMappingURL=babylon.bloomEffect.js.map
  75329. var BABYLON;
  75330. (function (BABYLON) {
  75331. /**
  75332. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75333. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75334. */
  75335. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75336. __extends(DefaultRenderingPipeline, _super);
  75337. /**
  75338. * @constructor
  75339. * @param {string} name - The rendering pipeline name
  75340. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75341. * @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)
  75342. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75343. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75344. */
  75345. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75346. if (automaticBuild === void 0) { automaticBuild = true; }
  75347. var _this = _super.call(this, scene.getEngine(), name) || this;
  75348. _this._originalCameras = [];
  75349. /**
  75350. * ID of the sharpen post process,
  75351. */
  75352. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75353. /**
  75354. * ID of the image processing post process;
  75355. */
  75356. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75357. /**
  75358. * ID of the Fast Approximate Anti-Aliasing post process;
  75359. */
  75360. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75361. /**
  75362. * ID of the chromatic aberration post process,
  75363. */
  75364. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75365. /**
  75366. * ID of the grain post process
  75367. */
  75368. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75369. /**
  75370. * Animations which can be used to tweak settings over a period of time
  75371. */
  75372. _this.animations = [];
  75373. _this._imageProcessingConfigurationObserver = null;
  75374. // Values
  75375. _this._sharpenEnabled = false;
  75376. _this._bloomEnabled = false;
  75377. _this._depthOfFieldEnabled = false;
  75378. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75379. _this._fxaaEnabled = false;
  75380. _this._imageProcessingEnabled = true;
  75381. _this._bloomScale = 0.5;
  75382. _this._chromaticAberrationEnabled = false;
  75383. _this._grainEnabled = false;
  75384. _this._buildAllowed = true;
  75385. _this._resizeObserver = null;
  75386. _this._hardwareScaleLevel = 1.0;
  75387. _this._bloomKernel = 64;
  75388. /**
  75389. * Specifies the weight of the bloom in the final rendering
  75390. */
  75391. _this._bloomWeight = 0.15;
  75392. /**
  75393. * Specifies the luma threshold for the area that will be blurred by the bloom
  75394. */
  75395. _this._bloomThreshold = 0.9;
  75396. _this._samples = 1;
  75397. _this._hasCleared = false;
  75398. _this._prevPostProcess = null;
  75399. _this._prevPrevPostProcess = null;
  75400. _this._cameras = cameras || [];
  75401. _this._originalCameras = _this._cameras.slice();
  75402. _this._buildAllowed = automaticBuild;
  75403. // Initialize
  75404. _this._scene = scene;
  75405. var caps = _this._scene.getEngine().getCaps();
  75406. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75407. // Misc
  75408. if (_this._hdr) {
  75409. if (caps.textureHalfFloatRender) {
  75410. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75411. }
  75412. else if (caps.textureFloatRender) {
  75413. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75414. }
  75415. }
  75416. else {
  75417. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75418. }
  75419. // Attach
  75420. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75421. var engine = _this._scene.getEngine();
  75422. // Create post processes before hand so they can be modified before enabled.
  75423. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75424. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75425. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75426. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75427. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75428. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75429. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75430. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75431. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75432. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75433. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75434. _this.bloomKernel = _this.bloomKernel;
  75435. });
  75436. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75437. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75438. });
  75439. _this._buildPipeline();
  75440. return _this;
  75441. }
  75442. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75443. get: function () {
  75444. return this._sharpenEnabled;
  75445. },
  75446. /**
  75447. * Enable or disable the sharpen process from the pipeline
  75448. */
  75449. set: function (enabled) {
  75450. if (this._sharpenEnabled === enabled) {
  75451. return;
  75452. }
  75453. this._sharpenEnabled = enabled;
  75454. this._buildPipeline();
  75455. },
  75456. enumerable: true,
  75457. configurable: true
  75458. });
  75459. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75460. /**
  75461. * Specifies the size of the bloom blur kernel, relative to the final output size
  75462. */
  75463. get: function () {
  75464. return this._bloomKernel;
  75465. },
  75466. set: function (value) {
  75467. this._bloomKernel = value;
  75468. this.bloom.kernel = value / this._hardwareScaleLevel;
  75469. },
  75470. enumerable: true,
  75471. configurable: true
  75472. });
  75473. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75474. get: function () {
  75475. return this._bloomWeight;
  75476. },
  75477. /**
  75478. * The strength of the bloom.
  75479. */
  75480. set: function (value) {
  75481. if (this._bloomWeight === value) {
  75482. return;
  75483. }
  75484. this.bloom.weight = value;
  75485. this._bloomWeight = value;
  75486. },
  75487. enumerable: true,
  75488. configurable: true
  75489. });
  75490. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75491. get: function () {
  75492. return this._bloomThreshold;
  75493. },
  75494. /**
  75495. * The strength of the bloom.
  75496. */
  75497. set: function (value) {
  75498. if (this._bloomThreshold === value) {
  75499. return;
  75500. }
  75501. this.bloom.threshold = value;
  75502. this._bloomThreshold = value;
  75503. },
  75504. enumerable: true,
  75505. configurable: true
  75506. });
  75507. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75508. get: function () {
  75509. return this._bloomScale;
  75510. },
  75511. /**
  75512. * The scale of the bloom, lower value will provide better performance.
  75513. */
  75514. set: function (value) {
  75515. if (this._bloomScale === value) {
  75516. return;
  75517. }
  75518. this._bloomScale = value;
  75519. // recreate bloom and dispose old as this setting is not dynamic
  75520. this._rebuildBloom();
  75521. this._buildPipeline();
  75522. },
  75523. enumerable: true,
  75524. configurable: true
  75525. });
  75526. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75527. get: function () {
  75528. return this._bloomEnabled;
  75529. },
  75530. /**
  75531. * Enable or disable the bloom from the pipeline
  75532. */
  75533. set: function (enabled) {
  75534. if (this._bloomEnabled === enabled) {
  75535. return;
  75536. }
  75537. this._bloomEnabled = enabled;
  75538. this._buildPipeline();
  75539. },
  75540. enumerable: true,
  75541. configurable: true
  75542. });
  75543. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75544. // recreate bloom and dispose old as this setting is not dynamic
  75545. var oldBloom = this.bloom;
  75546. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75547. this.bloom.threshold = oldBloom.threshold;
  75548. for (var i = 0; i < this._cameras.length; i++) {
  75549. oldBloom.disposeEffects(this._cameras[i]);
  75550. }
  75551. };
  75552. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75553. /**
  75554. * If the depth of field is enabled.
  75555. */
  75556. get: function () {
  75557. return this._depthOfFieldEnabled;
  75558. },
  75559. set: function (enabled) {
  75560. if (this._depthOfFieldEnabled === enabled) {
  75561. return;
  75562. }
  75563. this._depthOfFieldEnabled = enabled;
  75564. this._buildPipeline();
  75565. },
  75566. enumerable: true,
  75567. configurable: true
  75568. });
  75569. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75570. /**
  75571. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75572. */
  75573. get: function () {
  75574. return this._depthOfFieldBlurLevel;
  75575. },
  75576. set: function (value) {
  75577. if (this._depthOfFieldBlurLevel === value) {
  75578. return;
  75579. }
  75580. this._depthOfFieldBlurLevel = value;
  75581. // recreate dof and dispose old as this setting is not dynamic
  75582. var oldDof = this.depthOfField;
  75583. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75584. this.depthOfField.focalLength = oldDof.focalLength;
  75585. this.depthOfField.focusDistance = oldDof.focusDistance;
  75586. this.depthOfField.fStop = oldDof.fStop;
  75587. this.depthOfField.lensSize = oldDof.lensSize;
  75588. for (var i = 0; i < this._cameras.length; i++) {
  75589. oldDof.disposeEffects(this._cameras[i]);
  75590. }
  75591. this._buildPipeline();
  75592. },
  75593. enumerable: true,
  75594. configurable: true
  75595. });
  75596. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75597. get: function () {
  75598. return this._fxaaEnabled;
  75599. },
  75600. /**
  75601. * If the anti aliasing is enabled.
  75602. */
  75603. set: function (enabled) {
  75604. if (this._fxaaEnabled === enabled) {
  75605. return;
  75606. }
  75607. this._fxaaEnabled = enabled;
  75608. this._buildPipeline();
  75609. },
  75610. enumerable: true,
  75611. configurable: true
  75612. });
  75613. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75614. get: function () {
  75615. return this._samples;
  75616. },
  75617. /**
  75618. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75619. */
  75620. set: function (sampleCount) {
  75621. if (this._samples === sampleCount) {
  75622. return;
  75623. }
  75624. this._samples = sampleCount;
  75625. this._buildPipeline();
  75626. },
  75627. enumerable: true,
  75628. configurable: true
  75629. });
  75630. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75631. get: function () {
  75632. return this._imageProcessingEnabled;
  75633. },
  75634. /**
  75635. * If image processing is enabled.
  75636. */
  75637. set: function (enabled) {
  75638. if (this._imageProcessingEnabled === enabled) {
  75639. return;
  75640. }
  75641. this._imageProcessingEnabled = enabled;
  75642. this._buildPipeline();
  75643. },
  75644. enumerable: true,
  75645. configurable: true
  75646. });
  75647. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75648. get: function () {
  75649. return this._chromaticAberrationEnabled;
  75650. },
  75651. /**
  75652. * Enable or disable the chromaticAberration process from the pipeline
  75653. */
  75654. set: function (enabled) {
  75655. if (this._chromaticAberrationEnabled === enabled) {
  75656. return;
  75657. }
  75658. this._chromaticAberrationEnabled = enabled;
  75659. this._buildPipeline();
  75660. },
  75661. enumerable: true,
  75662. configurable: true
  75663. });
  75664. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75665. get: function () {
  75666. return this._grainEnabled;
  75667. },
  75668. /**
  75669. * Enable or disable the grain process from the pipeline
  75670. */
  75671. set: function (enabled) {
  75672. if (this._grainEnabled === enabled) {
  75673. return;
  75674. }
  75675. this._grainEnabled = enabled;
  75676. this._buildPipeline();
  75677. },
  75678. enumerable: true,
  75679. configurable: true
  75680. });
  75681. /**
  75682. * Force the compilation of the entire pipeline.
  75683. */
  75684. DefaultRenderingPipeline.prototype.prepare = function () {
  75685. var previousState = this._buildAllowed;
  75686. this._buildAllowed = true;
  75687. this._buildPipeline();
  75688. this._buildAllowed = previousState;
  75689. };
  75690. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75691. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75692. if (this._hasCleared) {
  75693. postProcess.autoClear = false;
  75694. }
  75695. else {
  75696. postProcess.autoClear = true;
  75697. this._scene.autoClear = false;
  75698. this._hasCleared = true;
  75699. }
  75700. if (!skipTextureSharing) {
  75701. if (this._prevPrevPostProcess) {
  75702. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75703. }
  75704. else {
  75705. postProcess.useOwnOutput();
  75706. }
  75707. if (this._prevPostProcess) {
  75708. this._prevPrevPostProcess = this._prevPostProcess;
  75709. }
  75710. this._prevPostProcess = postProcess;
  75711. }
  75712. };
  75713. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75714. var _this = this;
  75715. if (!this._buildAllowed) {
  75716. return;
  75717. }
  75718. this._scene.autoClear = true;
  75719. var engine = this._scene.getEngine();
  75720. this._disposePostProcesses();
  75721. if (this._cameras !== null) {
  75722. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75723. // get back cameras to be used to reattach pipeline
  75724. this._cameras = this._originalCameras.slice();
  75725. }
  75726. this._reset();
  75727. this._prevPostProcess = null;
  75728. this._prevPrevPostProcess = null;
  75729. this._hasCleared = false;
  75730. if (this.depthOfFieldEnabled) {
  75731. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75732. this.depthOfField.depthTexture = depthTexture;
  75733. if (!this.depthOfField._isReady()) {
  75734. this.depthOfField._updateEffects();
  75735. }
  75736. this.addEffect(this.depthOfField);
  75737. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75738. }
  75739. if (this.bloomEnabled) {
  75740. if (!this.bloom._isReady()) {
  75741. this.bloom._updateEffects();
  75742. }
  75743. this.addEffect(this.bloom);
  75744. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75745. }
  75746. if (this._imageProcessingEnabled) {
  75747. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75748. if (this._hdr) {
  75749. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75750. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75751. }
  75752. else {
  75753. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75754. }
  75755. }
  75756. if (this.sharpenEnabled) {
  75757. if (!this.sharpen.isReady()) {
  75758. this.sharpen.updateEffect();
  75759. }
  75760. this.addEffect(this._sharpenEffect);
  75761. this._setAutoClearAndTextureSharing(this.sharpen);
  75762. }
  75763. if (this.grainEnabled) {
  75764. if (!this.grain.isReady()) {
  75765. this.grain.updateEffect();
  75766. }
  75767. this.addEffect(this._grainEffect);
  75768. this._setAutoClearAndTextureSharing(this.grain);
  75769. }
  75770. if (this.chromaticAberrationEnabled) {
  75771. if (!this.chromaticAberration.isReady()) {
  75772. this.chromaticAberration.updateEffect();
  75773. }
  75774. this.addEffect(this._chromaticAberrationEffect);
  75775. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75776. }
  75777. if (this.fxaaEnabled) {
  75778. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75779. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75780. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75781. }
  75782. if (this._cameras !== null) {
  75783. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75784. }
  75785. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75786. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75787. }
  75788. };
  75789. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75790. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75791. for (var i = 0; i < this._cameras.length; i++) {
  75792. var camera = this._cameras[i];
  75793. if (this.imageProcessing) {
  75794. this.imageProcessing.dispose(camera);
  75795. }
  75796. if (this.fxaa) {
  75797. this.fxaa.dispose(camera);
  75798. }
  75799. // These are created in the constructor and should not be disposed on every pipeline change
  75800. if (disposeNonRecreated) {
  75801. if (this.sharpen) {
  75802. this.sharpen.dispose(camera);
  75803. }
  75804. if (this.depthOfField) {
  75805. this.depthOfField.disposeEffects(camera);
  75806. }
  75807. if (this.bloom) {
  75808. this.bloom.disposeEffects(camera);
  75809. }
  75810. if (this.chromaticAberration) {
  75811. this.chromaticAberration.dispose(camera);
  75812. }
  75813. if (this.grain) {
  75814. this.grain.dispose(camera);
  75815. }
  75816. }
  75817. }
  75818. this.imageProcessing = null;
  75819. this.fxaa = null;
  75820. if (disposeNonRecreated) {
  75821. this.sharpen = null;
  75822. this._sharpenEffect = null;
  75823. this.depthOfField = null;
  75824. this.bloom = null;
  75825. this.chromaticAberration = null;
  75826. this._chromaticAberrationEffect = null;
  75827. this.grain = null;
  75828. this._grainEffect = null;
  75829. }
  75830. };
  75831. /**
  75832. * Dispose of the pipeline and stop all post processes
  75833. */
  75834. DefaultRenderingPipeline.prototype.dispose = function () {
  75835. this._disposePostProcesses(true);
  75836. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75837. this._scene.autoClear = true;
  75838. if (this._resizeObserver) {
  75839. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75840. this._resizeObserver = null;
  75841. }
  75842. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75843. _super.prototype.dispose.call(this);
  75844. };
  75845. /**
  75846. * Serialize the rendering pipeline (Used when exporting)
  75847. * @returns the serialized object
  75848. */
  75849. DefaultRenderingPipeline.prototype.serialize = function () {
  75850. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75851. serializationObject.customType = "DefaultRenderingPipeline";
  75852. return serializationObject;
  75853. };
  75854. /**
  75855. * Parse the serialized pipeline
  75856. * @param source Source pipeline.
  75857. * @param scene The scene to load the pipeline to.
  75858. * @param rootUrl The URL of the serialized pipeline.
  75859. * @returns An instantiated pipeline from the serialized object.
  75860. */
  75861. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75862. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75863. };
  75864. __decorate([
  75865. BABYLON.serialize()
  75866. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75867. __decorate([
  75868. BABYLON.serialize()
  75869. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75870. __decorate([
  75871. BABYLON.serialize()
  75872. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75873. __decorate([
  75874. BABYLON.serialize()
  75875. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75876. __decorate([
  75877. BABYLON.serialize()
  75878. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75879. __decorate([
  75880. BABYLON.serialize()
  75881. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75882. __decorate([
  75883. BABYLON.serialize()
  75884. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75885. __decorate([
  75886. BABYLON.serialize()
  75887. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75888. __decorate([
  75889. BABYLON.serialize()
  75890. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75891. __decorate([
  75892. BABYLON.serialize()
  75893. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75894. __decorate([
  75895. BABYLON.serialize()
  75896. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75897. __decorate([
  75898. BABYLON.serialize()
  75899. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75900. __decorate([
  75901. BABYLON.serialize()
  75902. ], DefaultRenderingPipeline.prototype, "samples", null);
  75903. __decorate([
  75904. BABYLON.serialize()
  75905. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75906. __decorate([
  75907. BABYLON.serialize()
  75908. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75909. __decorate([
  75910. BABYLON.serialize()
  75911. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75912. return DefaultRenderingPipeline;
  75913. }(BABYLON.PostProcessRenderPipeline));
  75914. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75915. })(BABYLON || (BABYLON = {}));
  75916. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75917. var BABYLON;
  75918. (function (BABYLON) {
  75919. /**
  75920. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75921. */
  75922. var GeometryBufferRenderer = /** @class */ (function () {
  75923. /**
  75924. * Creates a new G Buffer for the scene
  75925. * @param scene The scene the buffer belongs to
  75926. * @param ratio How big is the buffer related to the main canvas.
  75927. */
  75928. function GeometryBufferRenderer(scene, ratio) {
  75929. if (ratio === void 0) { ratio = 1; }
  75930. this._enablePosition = false;
  75931. this._scene = scene;
  75932. this._ratio = ratio;
  75933. // Render target
  75934. this._createRenderTargets();
  75935. }
  75936. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75937. /**
  75938. * Set the render list (meshes to be rendered) used in the G buffer.
  75939. */
  75940. set: function (meshes) {
  75941. this._multiRenderTarget.renderList = meshes;
  75942. },
  75943. enumerable: true,
  75944. configurable: true
  75945. });
  75946. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75947. /**
  75948. * Gets wether or not G buffer are supported by the running hardware.
  75949. * This requires draw buffer supports
  75950. */
  75951. get: function () {
  75952. return this._multiRenderTarget.isSupported;
  75953. },
  75954. enumerable: true,
  75955. configurable: true
  75956. });
  75957. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75958. /**
  75959. * Gets wether or not position are enabled for the G buffer.
  75960. */
  75961. get: function () {
  75962. return this._enablePosition;
  75963. },
  75964. /**
  75965. * Sets wether or not position are enabled for the G buffer.
  75966. */
  75967. set: function (enable) {
  75968. this._enablePosition = enable;
  75969. this.dispose();
  75970. this._createRenderTargets();
  75971. },
  75972. enumerable: true,
  75973. configurable: true
  75974. });
  75975. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75976. /**
  75977. * Gets the scene associated with the buffer.
  75978. */
  75979. get: function () {
  75980. return this._scene;
  75981. },
  75982. enumerable: true,
  75983. configurable: true
  75984. });
  75985. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75986. /**
  75987. * Gets the ratio used by the buffer during its creation.
  75988. * How big is the buffer related to the main canvas.
  75989. */
  75990. get: function () {
  75991. return this._ratio;
  75992. },
  75993. enumerable: true,
  75994. configurable: true
  75995. });
  75996. /**
  75997. * Checks wether everything is ready to render a submesh to the G buffer.
  75998. * @param subMesh the submesh to check readiness for
  75999. * @param useInstances is the mesh drawn using instance or not
  76000. * @returns true if ready otherwise false
  76001. */
  76002. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76003. var material = subMesh.getMaterial();
  76004. if (material && material.disableDepthWrite) {
  76005. return false;
  76006. }
  76007. var defines = [];
  76008. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76009. var mesh = subMesh.getMesh();
  76010. // Alpha test
  76011. if (material && material.needAlphaTesting()) {
  76012. defines.push("#define ALPHATEST");
  76013. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76014. attribs.push(BABYLON.VertexBuffer.UVKind);
  76015. defines.push("#define UV1");
  76016. }
  76017. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76018. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76019. defines.push("#define UV2");
  76020. }
  76021. }
  76022. // Buffers
  76023. if (this._enablePosition) {
  76024. defines.push("#define POSITION");
  76025. }
  76026. // Bones
  76027. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76028. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76029. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76030. if (mesh.numBoneInfluencers > 4) {
  76031. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76032. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76033. }
  76034. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76035. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76036. }
  76037. else {
  76038. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76039. }
  76040. // Instances
  76041. if (useInstances) {
  76042. defines.push("#define INSTANCES");
  76043. attribs.push("world0");
  76044. attribs.push("world1");
  76045. attribs.push("world2");
  76046. attribs.push("world3");
  76047. }
  76048. // Get correct effect
  76049. var join = defines.join("\n");
  76050. if (this._cachedDefines !== join) {
  76051. this._cachedDefines = join;
  76052. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76053. }
  76054. return this._effect.isReady();
  76055. };
  76056. /**
  76057. * Gets the current underlying G Buffer.
  76058. * @returns the buffer
  76059. */
  76060. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76061. return this._multiRenderTarget;
  76062. };
  76063. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76064. /**
  76065. * Gets the number of samples used to render the buffer (anti aliasing).
  76066. */
  76067. get: function () {
  76068. return this._multiRenderTarget.samples;
  76069. },
  76070. /**
  76071. * Sets the number of samples used to render the buffer (anti aliasing).
  76072. */
  76073. set: function (value) {
  76074. this._multiRenderTarget.samples = value;
  76075. },
  76076. enumerable: true,
  76077. configurable: true
  76078. });
  76079. /**
  76080. * Disposes the renderer and frees up associated resources.
  76081. */
  76082. GeometryBufferRenderer.prototype.dispose = function () {
  76083. this.getGBuffer().dispose();
  76084. };
  76085. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76086. var _this = this;
  76087. var engine = this._scene.getEngine();
  76088. var count = this._enablePosition ? 3 : 2;
  76089. 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 });
  76090. if (!this.isSupported) {
  76091. return;
  76092. }
  76093. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76094. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76095. this._multiRenderTarget.refreshRate = 1;
  76096. this._multiRenderTarget.renderParticles = false;
  76097. this._multiRenderTarget.renderList = null;
  76098. // set default depth value to 1.0 (far away)
  76099. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76100. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76101. });
  76102. // Custom render function
  76103. var renderSubMesh = function (subMesh) {
  76104. var mesh = subMesh.getRenderingMesh();
  76105. var scene = _this._scene;
  76106. var engine = scene.getEngine();
  76107. var material = subMesh.getMaterial();
  76108. if (!material) {
  76109. return;
  76110. }
  76111. // Culling
  76112. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76113. // Managing instances
  76114. var batch = mesh._getInstancesRenderList(subMesh._id);
  76115. if (batch.mustReturn) {
  76116. return;
  76117. }
  76118. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76119. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76120. engine.enableEffect(_this._effect);
  76121. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76122. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76123. _this._effect.setMatrix("view", scene.getViewMatrix());
  76124. // Alpha test
  76125. if (material && material.needAlphaTesting()) {
  76126. var alphaTexture = material.getAlphaTestTexture();
  76127. if (alphaTexture) {
  76128. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76129. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76130. }
  76131. }
  76132. // Bones
  76133. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76134. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76135. }
  76136. // Draw
  76137. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76138. }
  76139. };
  76140. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76141. var index;
  76142. if (depthOnlySubMeshes.length) {
  76143. engine.setColorWrite(false);
  76144. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76145. renderSubMesh(depthOnlySubMeshes.data[index]);
  76146. }
  76147. engine.setColorWrite(true);
  76148. }
  76149. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76150. renderSubMesh(opaqueSubMeshes.data[index]);
  76151. }
  76152. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76153. renderSubMesh(alphaTestSubMeshes.data[index]);
  76154. }
  76155. };
  76156. };
  76157. return GeometryBufferRenderer;
  76158. }());
  76159. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76160. })(BABYLON || (BABYLON = {}));
  76161. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76162. var BABYLON;
  76163. (function (BABYLON) {
  76164. var RefractionPostProcess = /** @class */ (function (_super) {
  76165. __extends(RefractionPostProcess, _super);
  76166. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76167. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76168. _this.color = color;
  76169. _this.depth = depth;
  76170. _this.colorLevel = colorLevel;
  76171. _this._ownRefractionTexture = true;
  76172. _this.onActivateObservable.add(function (cam) {
  76173. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76174. });
  76175. _this.onApplyObservable.add(function (effect) {
  76176. effect.setColor3("baseColor", _this.color);
  76177. effect.setFloat("depth", _this.depth);
  76178. effect.setFloat("colorLevel", _this.colorLevel);
  76179. effect.setTexture("refractionSampler", _this._refTexture);
  76180. });
  76181. return _this;
  76182. }
  76183. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76184. /**
  76185. * Gets or sets the refraction texture
  76186. * Please note that you are responsible for disposing the texture if you set it manually
  76187. */
  76188. get: function () {
  76189. return this._refTexture;
  76190. },
  76191. set: function (value) {
  76192. if (this._refTexture && this._ownRefractionTexture) {
  76193. this._refTexture.dispose();
  76194. }
  76195. this._refTexture = value;
  76196. this._ownRefractionTexture = false;
  76197. },
  76198. enumerable: true,
  76199. configurable: true
  76200. });
  76201. // Methods
  76202. RefractionPostProcess.prototype.dispose = function (camera) {
  76203. if (this._refTexture && this._ownRefractionTexture) {
  76204. this._refTexture.dispose();
  76205. this._refTexture = null;
  76206. }
  76207. _super.prototype.dispose.call(this, camera);
  76208. };
  76209. return RefractionPostProcess;
  76210. }(BABYLON.PostProcess));
  76211. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76212. })(BABYLON || (BABYLON = {}));
  76213. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76214. var BABYLON;
  76215. (function (BABYLON) {
  76216. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76217. __extends(BlackAndWhitePostProcess, _super);
  76218. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76219. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76220. _this.degree = 1;
  76221. _this.onApplyObservable.add(function (effect) {
  76222. effect.setFloat("degree", _this.degree);
  76223. });
  76224. return _this;
  76225. }
  76226. return BlackAndWhitePostProcess;
  76227. }(BABYLON.PostProcess));
  76228. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76229. })(BABYLON || (BABYLON = {}));
  76230. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76231. var BABYLON;
  76232. (function (BABYLON) {
  76233. /**
  76234. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76235. * input texture to perform effects such as edge detection or sharpening
  76236. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76237. */
  76238. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76239. __extends(ConvolutionPostProcess, _super);
  76240. /**
  76241. * Creates a new instance ConvolutionPostProcess
  76242. * @param name The name of the effect.
  76243. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76244. * @param options The required width/height ratio to downsize to before computing the render pass.
  76245. * @param camera The camera to apply the render pass to.
  76246. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76247. * @param engine The engine which the post process will be applied. (default: current engine)
  76248. * @param reusable If the post process can be reused on the same frame. (default: false)
  76249. * @param textureType Type of textures used when performing the post process. (default: 0)
  76250. */
  76251. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76252. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76253. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76254. _this.kernel = kernel;
  76255. _this.onApply = function (effect) {
  76256. effect.setFloat2("screenSize", _this.width, _this.height);
  76257. effect.setArray("kernel", _this.kernel);
  76258. };
  76259. return _this;
  76260. }
  76261. // Statics
  76262. /**
  76263. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76264. */
  76265. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76266. /**
  76267. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76268. */
  76269. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76270. /**
  76271. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76272. */
  76273. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76274. /**
  76275. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76276. */
  76277. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76278. /**
  76279. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76280. */
  76281. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76282. /**
  76283. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76284. */
  76285. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76286. return ConvolutionPostProcess;
  76287. }(BABYLON.PostProcess));
  76288. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76289. })(BABYLON || (BABYLON = {}));
  76290. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76291. var BABYLON;
  76292. (function (BABYLON) {
  76293. var FilterPostProcess = /** @class */ (function (_super) {
  76294. __extends(FilterPostProcess, _super);
  76295. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76296. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76297. _this.kernelMatrix = kernelMatrix;
  76298. _this.onApply = function (effect) {
  76299. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76300. };
  76301. return _this;
  76302. }
  76303. return FilterPostProcess;
  76304. }(BABYLON.PostProcess));
  76305. BABYLON.FilterPostProcess = FilterPostProcess;
  76306. })(BABYLON || (BABYLON = {}));
  76307. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76308. var BABYLON;
  76309. (function (BABYLON) {
  76310. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76311. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76312. __extends(VolumetricLightScatteringPostProcess, _super);
  76313. /**
  76314. * @constructor
  76315. * @param {string} name - The post-process name
  76316. * @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)
  76317. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76318. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76319. * @param {number} samples - The post-process quality, default 100
  76320. * @param {number} samplingMode - The post-process filtering mode
  76321. * @param {BABYLON.Engine} engine - The babylon engine
  76322. * @param {boolean} reusable - If the post-process is reusable
  76323. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76324. */
  76325. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76326. if (samples === void 0) { samples = 100; }
  76327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76328. 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;
  76329. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76330. /**
  76331. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76332. */
  76333. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76334. /**
  76335. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76336. */
  76337. _this.useCustomMeshPosition = false;
  76338. /**
  76339. * If the post-process should inverse the light scattering direction
  76340. */
  76341. _this.invert = true;
  76342. /**
  76343. * Array containing the excluded meshes not rendered in the internal pass
  76344. */
  76345. _this.excludedMeshes = new Array();
  76346. /**
  76347. * Controls the overall intensity of the post-process
  76348. */
  76349. _this.exposure = 0.3;
  76350. /**
  76351. * Dissipates each sample's contribution in range [0, 1]
  76352. */
  76353. _this.decay = 0.96815;
  76354. /**
  76355. * Controls the overall intensity of each sample
  76356. */
  76357. _this.weight = 0.58767;
  76358. /**
  76359. * Controls the density of each sample
  76360. */
  76361. _this.density = 0.926;
  76362. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76363. engine = scene.getEngine();
  76364. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76365. // Configure mesh
  76366. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76367. // Configure
  76368. _this._createPass(scene, ratio.passRatio || ratio);
  76369. _this.onActivate = function (camera) {
  76370. if (!_this.isSupported) {
  76371. _this.dispose(camera);
  76372. }
  76373. _this.onActivate = null;
  76374. };
  76375. _this.onApplyObservable.add(function (effect) {
  76376. _this._updateMeshScreenCoordinates(scene);
  76377. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76378. effect.setFloat("exposure", _this.exposure);
  76379. effect.setFloat("decay", _this.decay);
  76380. effect.setFloat("weight", _this.weight);
  76381. effect.setFloat("density", _this.density);
  76382. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76383. });
  76384. return _this;
  76385. }
  76386. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76387. get: function () {
  76388. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76389. return false;
  76390. },
  76391. set: function (useDiffuseColor) {
  76392. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76393. },
  76394. enumerable: true,
  76395. configurable: true
  76396. });
  76397. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76398. return "VolumetricLightScatteringPostProcess";
  76399. };
  76400. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76401. var mesh = subMesh.getMesh();
  76402. // Render this.mesh as default
  76403. if (mesh === this.mesh && mesh.material) {
  76404. return mesh.material.isReady(mesh);
  76405. }
  76406. var defines = [];
  76407. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76408. var material = subMesh.getMaterial();
  76409. // Alpha test
  76410. if (material) {
  76411. if (material.needAlphaTesting()) {
  76412. defines.push("#define ALPHATEST");
  76413. }
  76414. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76415. attribs.push(BABYLON.VertexBuffer.UVKind);
  76416. defines.push("#define UV1");
  76417. }
  76418. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76419. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76420. defines.push("#define UV2");
  76421. }
  76422. }
  76423. // Bones
  76424. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76425. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76426. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76427. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76428. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76429. }
  76430. else {
  76431. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76432. }
  76433. // Instances
  76434. if (useInstances) {
  76435. defines.push("#define INSTANCES");
  76436. attribs.push("world0");
  76437. attribs.push("world1");
  76438. attribs.push("world2");
  76439. attribs.push("world3");
  76440. }
  76441. // Get correct effect
  76442. var join = defines.join("\n");
  76443. if (this._cachedDefines !== join) {
  76444. this._cachedDefines = join;
  76445. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76446. }
  76447. return this._volumetricLightScatteringPass.isReady();
  76448. };
  76449. /**
  76450. * Sets the new light position for light scattering effect
  76451. * @param {BABYLON.Vector3} The new custom light position
  76452. */
  76453. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76454. this.customMeshPosition = position;
  76455. };
  76456. /**
  76457. * Returns the light position for light scattering effect
  76458. * @return {BABYLON.Vector3} The custom light position
  76459. */
  76460. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76461. return this.customMeshPosition;
  76462. };
  76463. /**
  76464. * Disposes the internal assets and detaches the post-process from the camera
  76465. */
  76466. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76467. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76468. if (rttIndex !== -1) {
  76469. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76470. }
  76471. this._volumetricLightScatteringRTT.dispose();
  76472. _super.prototype.dispose.call(this, camera);
  76473. };
  76474. /**
  76475. * Returns the render target texture used by the post-process
  76476. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76477. */
  76478. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76479. return this._volumetricLightScatteringRTT;
  76480. };
  76481. // Private methods
  76482. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76483. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76484. return true;
  76485. }
  76486. return false;
  76487. };
  76488. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76489. var _this = this;
  76490. var engine = scene.getEngine();
  76491. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76492. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76493. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76494. this._volumetricLightScatteringRTT.renderList = null;
  76495. this._volumetricLightScatteringRTT.renderParticles = false;
  76496. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76497. var camera = this.getCamera();
  76498. if (camera) {
  76499. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76500. }
  76501. else {
  76502. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76503. }
  76504. // Custom render function for submeshes
  76505. var renderSubMesh = function (subMesh) {
  76506. var mesh = subMesh.getRenderingMesh();
  76507. if (_this._meshExcluded(mesh)) {
  76508. return;
  76509. }
  76510. var material = subMesh.getMaterial();
  76511. if (!material) {
  76512. return;
  76513. }
  76514. var scene = mesh.getScene();
  76515. var engine = scene.getEngine();
  76516. // Culling
  76517. engine.setState(material.backFaceCulling);
  76518. // Managing instances
  76519. var batch = mesh._getInstancesRenderList(subMesh._id);
  76520. if (batch.mustReturn) {
  76521. return;
  76522. }
  76523. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76524. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76525. var effect = _this._volumetricLightScatteringPass;
  76526. if (mesh === _this.mesh) {
  76527. if (subMesh.effect) {
  76528. effect = subMesh.effect;
  76529. }
  76530. else {
  76531. effect = material.getEffect();
  76532. }
  76533. }
  76534. engine.enableEffect(effect);
  76535. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76536. if (mesh === _this.mesh) {
  76537. material.bind(mesh.getWorldMatrix(), mesh);
  76538. }
  76539. else {
  76540. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76541. // Alpha test
  76542. if (material && material.needAlphaTesting()) {
  76543. var alphaTexture = material.getAlphaTestTexture();
  76544. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76545. if (alphaTexture) {
  76546. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76547. }
  76548. }
  76549. // Bones
  76550. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76551. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76552. }
  76553. }
  76554. // Draw
  76555. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76556. }
  76557. };
  76558. // Render target texture callbacks
  76559. var savedSceneClearColor;
  76560. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76561. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76562. savedSceneClearColor = scene.clearColor;
  76563. scene.clearColor = sceneClearColor;
  76564. });
  76565. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76566. scene.clearColor = savedSceneClearColor;
  76567. });
  76568. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76569. var engine = scene.getEngine();
  76570. var index;
  76571. if (depthOnlySubMeshes.length) {
  76572. engine.setColorWrite(false);
  76573. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76574. renderSubMesh(depthOnlySubMeshes.data[index]);
  76575. }
  76576. engine.setColorWrite(true);
  76577. }
  76578. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76579. renderSubMesh(opaqueSubMeshes.data[index]);
  76580. }
  76581. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76582. renderSubMesh(alphaTestSubMeshes.data[index]);
  76583. }
  76584. if (transparentSubMeshes.length) {
  76585. // Sort sub meshes
  76586. for (index = 0; index < transparentSubMeshes.length; index++) {
  76587. var submesh = transparentSubMeshes.data[index];
  76588. var boundingInfo = submesh.getBoundingInfo();
  76589. if (boundingInfo && scene.activeCamera) {
  76590. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76591. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76592. }
  76593. }
  76594. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76595. sortedArray.sort(function (a, b) {
  76596. // Alpha index first
  76597. if (a._alphaIndex > b._alphaIndex) {
  76598. return 1;
  76599. }
  76600. if (a._alphaIndex < b._alphaIndex) {
  76601. return -1;
  76602. }
  76603. // Then distance to camera
  76604. if (a._distanceToCamera < b._distanceToCamera) {
  76605. return 1;
  76606. }
  76607. if (a._distanceToCamera > b._distanceToCamera) {
  76608. return -1;
  76609. }
  76610. return 0;
  76611. });
  76612. // Render sub meshes
  76613. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76614. for (index = 0; index < sortedArray.length; index++) {
  76615. renderSubMesh(sortedArray[index]);
  76616. }
  76617. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76618. }
  76619. };
  76620. };
  76621. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76622. var transform = scene.getTransformMatrix();
  76623. var meshPosition;
  76624. if (this.useCustomMeshPosition) {
  76625. meshPosition = this.customMeshPosition;
  76626. }
  76627. else if (this.attachedNode) {
  76628. meshPosition = this.attachedNode.position;
  76629. }
  76630. else {
  76631. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76632. }
  76633. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76634. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76635. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76636. if (this.invert)
  76637. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76638. };
  76639. // Static methods
  76640. /**
  76641. * Creates a default mesh for the Volumeric Light Scattering post-process
  76642. * @param {string} The mesh name
  76643. * @param {BABYLON.Scene} The scene where to create the mesh
  76644. * @return {BABYLON.Mesh} the default mesh
  76645. */
  76646. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76647. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76648. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76649. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76650. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76651. mesh.material = material;
  76652. return mesh;
  76653. };
  76654. __decorate([
  76655. BABYLON.serializeAsVector3()
  76656. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76657. __decorate([
  76658. BABYLON.serialize()
  76659. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76660. __decorate([
  76661. BABYLON.serialize()
  76662. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76663. __decorate([
  76664. BABYLON.serializeAsMeshReference()
  76665. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76666. __decorate([
  76667. BABYLON.serialize()
  76668. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76669. __decorate([
  76670. BABYLON.serialize()
  76671. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76672. __decorate([
  76673. BABYLON.serialize()
  76674. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76675. __decorate([
  76676. BABYLON.serialize()
  76677. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76678. __decorate([
  76679. BABYLON.serialize()
  76680. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76681. return VolumetricLightScatteringPostProcess;
  76682. }(BABYLON.PostProcess));
  76683. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76684. })(BABYLON || (BABYLON = {}));
  76685. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76686. //
  76687. // This post-process allows the modification of rendered colors by using
  76688. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76689. //
  76690. // The object needs to be provided an url to a texture containing the color
  76691. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76692. // Use an image editing software to tweak the LUT to match your needs.
  76693. //
  76694. // For an example of a color LUT, see here:
  76695. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76696. // For explanations on color grading, see here:
  76697. // http://udn.epicgames.com/Three/ColorGrading.html
  76698. //
  76699. var BABYLON;
  76700. (function (BABYLON) {
  76701. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76702. __extends(ColorCorrectionPostProcess, _super);
  76703. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76704. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76705. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76706. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76707. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76708. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76709. _this.onApply = function (effect) {
  76710. effect.setTexture("colorTable", _this._colorTableTexture);
  76711. };
  76712. return _this;
  76713. }
  76714. return ColorCorrectionPostProcess;
  76715. }(BABYLON.PostProcess));
  76716. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76717. })(BABYLON || (BABYLON = {}));
  76718. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76719. var BABYLON;
  76720. (function (BABYLON) {
  76721. /** Defines operator used for tonemapping */
  76722. var TonemappingOperator;
  76723. (function (TonemappingOperator) {
  76724. /** Hable */
  76725. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76726. /** Reinhard */
  76727. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76728. /** HejiDawson */
  76729. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76730. /** Photographic */
  76731. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76732. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76733. ;
  76734. /**
  76735. * Defines a post process to apply tone mapping
  76736. */
  76737. var TonemapPostProcess = /** @class */ (function (_super) {
  76738. __extends(TonemapPostProcess, _super);
  76739. /**
  76740. * Creates a new TonemapPostProcess
  76741. * @param name defines the name of the postprocess
  76742. * @param _operator defines the operator to use
  76743. * @param exposureAdjustment defines the required exposure adjustement
  76744. * @param camera defines the camera to use (can be null)
  76745. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76746. * @param engine defines the hosting engine (can be ignore if camera is set)
  76747. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76748. */
  76749. function TonemapPostProcess(name, _operator,
  76750. /** Defines the required exposure adjustement */
  76751. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76753. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76754. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76755. _this._operator = _operator;
  76756. _this.exposureAdjustment = exposureAdjustment;
  76757. var defines = "#define ";
  76758. if (_this._operator === TonemappingOperator.Hable)
  76759. defines += "HABLE_TONEMAPPING";
  76760. else if (_this._operator === TonemappingOperator.Reinhard)
  76761. defines += "REINHARD_TONEMAPPING";
  76762. else if (_this._operator === TonemappingOperator.HejiDawson)
  76763. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76764. else if (_this._operator === TonemappingOperator.Photographic)
  76765. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76766. //sadly a second call to create the effect.
  76767. _this.updateEffect(defines);
  76768. _this.onApply = function (effect) {
  76769. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76770. };
  76771. return _this;
  76772. }
  76773. return TonemapPostProcess;
  76774. }(BABYLON.PostProcess));
  76775. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76776. })(BABYLON || (BABYLON = {}));
  76777. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76778. var BABYLON;
  76779. (function (BABYLON) {
  76780. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76781. __extends(DisplayPassPostProcess, _super);
  76782. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76783. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76784. }
  76785. return DisplayPassPostProcess;
  76786. }(BABYLON.PostProcess));
  76787. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76788. })(BABYLON || (BABYLON = {}));
  76789. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76790. var BABYLON;
  76791. (function (BABYLON) {
  76792. var HighlightsPostProcess = /** @class */ (function (_super) {
  76793. __extends(HighlightsPostProcess, _super);
  76794. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76795. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76796. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76797. }
  76798. return HighlightsPostProcess;
  76799. }(BABYLON.PostProcess));
  76800. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76801. })(BABYLON || (BABYLON = {}));
  76802. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76803. var BABYLON;
  76804. (function (BABYLON) {
  76805. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76806. __extends(ImageProcessingPostProcess, _super);
  76807. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76808. if (camera === void 0) { camera = null; }
  76809. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76810. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76811. _this._fromLinearSpace = true;
  76812. /**
  76813. * Defines cache preventing GC.
  76814. */
  76815. _this._defines = {
  76816. IMAGEPROCESSING: false,
  76817. VIGNETTE: false,
  76818. VIGNETTEBLENDMODEMULTIPLY: false,
  76819. VIGNETTEBLENDMODEOPAQUE: false,
  76820. TONEMAPPING: false,
  76821. CONTRAST: false,
  76822. COLORCURVES: false,
  76823. COLORGRADING: false,
  76824. COLORGRADING3D: false,
  76825. FROMLINEARSPACE: false,
  76826. SAMPLER3DGREENDEPTH: false,
  76827. SAMPLER3DBGRMAP: false,
  76828. IMAGEPROCESSINGPOSTPROCESS: false,
  76829. EXPOSURE: false,
  76830. };
  76831. // Setup the configuration as forced by the constructor. This would then not force the
  76832. // scene materials output in linear space and let untouched the default forward pass.
  76833. if (imageProcessingConfiguration) {
  76834. imageProcessingConfiguration.applyByPostProcess = true;
  76835. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76836. // This will cause the shader to be compiled
  76837. _this.fromLinearSpace = false;
  76838. }
  76839. // Setup the default processing configuration to the scene.
  76840. else {
  76841. _this._attachImageProcessingConfiguration(null, true);
  76842. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76843. }
  76844. _this.onApply = function (effect) {
  76845. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76846. };
  76847. return _this;
  76848. }
  76849. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76850. /**
  76851. * Gets the image processing configuration used either in this material.
  76852. */
  76853. get: function () {
  76854. return this._imageProcessingConfiguration;
  76855. },
  76856. /**
  76857. * Sets the Default image processing configuration used either in the this material.
  76858. *
  76859. * If sets to null, the scene one is in use.
  76860. */
  76861. set: function (value) {
  76862. this._attachImageProcessingConfiguration(value);
  76863. },
  76864. enumerable: true,
  76865. configurable: true
  76866. });
  76867. /**
  76868. * Attaches a new image processing configuration to the PBR Material.
  76869. * @param configuration
  76870. */
  76871. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76872. var _this = this;
  76873. if (doNotBuild === void 0) { doNotBuild = false; }
  76874. if (configuration === this._imageProcessingConfiguration) {
  76875. return;
  76876. }
  76877. // Detaches observer.
  76878. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76879. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76880. }
  76881. // Pick the scene configuration if needed.
  76882. if (!configuration) {
  76883. var scene = null;
  76884. var engine = this.getEngine();
  76885. var camera = this.getCamera();
  76886. if (camera) {
  76887. scene = camera.getScene();
  76888. }
  76889. else if (engine && engine.scenes) {
  76890. var scenes = engine.scenes;
  76891. scene = scenes[scenes.length - 1];
  76892. }
  76893. else {
  76894. scene = BABYLON.Engine.LastCreatedScene;
  76895. }
  76896. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76897. }
  76898. else {
  76899. this._imageProcessingConfiguration = configuration;
  76900. }
  76901. // Attaches observer.
  76902. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76903. _this._updateParameters();
  76904. });
  76905. // Ensure the effect will be rebuilt.
  76906. if (!doNotBuild) {
  76907. this._updateParameters();
  76908. }
  76909. };
  76910. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76911. /**
  76912. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76913. */
  76914. get: function () {
  76915. return this.imageProcessingConfiguration.colorCurves;
  76916. },
  76917. /**
  76918. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76919. */
  76920. set: function (value) {
  76921. this.imageProcessingConfiguration.colorCurves = value;
  76922. },
  76923. enumerable: true,
  76924. configurable: true
  76925. });
  76926. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76927. /**
  76928. * Gets wether the color curves effect is enabled.
  76929. */
  76930. get: function () {
  76931. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76932. },
  76933. /**
  76934. * Sets wether the color curves effect is enabled.
  76935. */
  76936. set: function (value) {
  76937. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76938. },
  76939. enumerable: true,
  76940. configurable: true
  76941. });
  76942. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76943. /**
  76944. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76945. */
  76946. get: function () {
  76947. return this.imageProcessingConfiguration.colorGradingTexture;
  76948. },
  76949. /**
  76950. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76951. */
  76952. set: function (value) {
  76953. this.imageProcessingConfiguration.colorGradingTexture = value;
  76954. },
  76955. enumerable: true,
  76956. configurable: true
  76957. });
  76958. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  76959. /**
  76960. * Gets wether the color grading effect is enabled.
  76961. */
  76962. get: function () {
  76963. return this.imageProcessingConfiguration.colorGradingEnabled;
  76964. },
  76965. /**
  76966. * Gets wether the color grading effect is enabled.
  76967. */
  76968. set: function (value) {
  76969. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76970. },
  76971. enumerable: true,
  76972. configurable: true
  76973. });
  76974. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  76975. /**
  76976. * Gets exposure used in the effect.
  76977. */
  76978. get: function () {
  76979. return this.imageProcessingConfiguration.exposure;
  76980. },
  76981. /**
  76982. * Sets exposure used in the effect.
  76983. */
  76984. set: function (value) {
  76985. this.imageProcessingConfiguration.exposure = value;
  76986. },
  76987. enumerable: true,
  76988. configurable: true
  76989. });
  76990. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  76991. /**
  76992. * Gets wether tonemapping is enabled or not.
  76993. */
  76994. get: function () {
  76995. return this._imageProcessingConfiguration.toneMappingEnabled;
  76996. },
  76997. /**
  76998. * Sets wether tonemapping is enabled or not
  76999. */
  77000. set: function (value) {
  77001. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77002. },
  77003. enumerable: true,
  77004. configurable: true
  77005. });
  77006. ;
  77007. ;
  77008. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77009. /**
  77010. * Gets contrast used in the effect.
  77011. */
  77012. get: function () {
  77013. return this.imageProcessingConfiguration.contrast;
  77014. },
  77015. /**
  77016. * Sets contrast used in the effect.
  77017. */
  77018. set: function (value) {
  77019. this.imageProcessingConfiguration.contrast = value;
  77020. },
  77021. enumerable: true,
  77022. configurable: true
  77023. });
  77024. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77025. /**
  77026. * Gets Vignette stretch size.
  77027. */
  77028. get: function () {
  77029. return this.imageProcessingConfiguration.vignetteStretch;
  77030. },
  77031. /**
  77032. * Sets Vignette stretch size.
  77033. */
  77034. set: function (value) {
  77035. this.imageProcessingConfiguration.vignetteStretch = value;
  77036. },
  77037. enumerable: true,
  77038. configurable: true
  77039. });
  77040. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77041. /**
  77042. * Gets Vignette centre X Offset.
  77043. */
  77044. get: function () {
  77045. return this.imageProcessingConfiguration.vignetteCentreX;
  77046. },
  77047. /**
  77048. * Sets Vignette centre X Offset.
  77049. */
  77050. set: function (value) {
  77051. this.imageProcessingConfiguration.vignetteCentreX = value;
  77052. },
  77053. enumerable: true,
  77054. configurable: true
  77055. });
  77056. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77057. /**
  77058. * Gets Vignette centre Y Offset.
  77059. */
  77060. get: function () {
  77061. return this.imageProcessingConfiguration.vignetteCentreY;
  77062. },
  77063. /**
  77064. * Sets Vignette centre Y Offset.
  77065. */
  77066. set: function (value) {
  77067. this.imageProcessingConfiguration.vignetteCentreY = value;
  77068. },
  77069. enumerable: true,
  77070. configurable: true
  77071. });
  77072. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77073. /**
  77074. * Gets Vignette weight or intensity of the vignette effect.
  77075. */
  77076. get: function () {
  77077. return this.imageProcessingConfiguration.vignetteWeight;
  77078. },
  77079. /**
  77080. * Sets Vignette weight or intensity of the vignette effect.
  77081. */
  77082. set: function (value) {
  77083. this.imageProcessingConfiguration.vignetteWeight = value;
  77084. },
  77085. enumerable: true,
  77086. configurable: true
  77087. });
  77088. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77089. /**
  77090. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77091. * if vignetteEnabled is set to true.
  77092. */
  77093. get: function () {
  77094. return this.imageProcessingConfiguration.vignetteColor;
  77095. },
  77096. /**
  77097. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77098. * if vignetteEnabled is set to true.
  77099. */
  77100. set: function (value) {
  77101. this.imageProcessingConfiguration.vignetteColor = value;
  77102. },
  77103. enumerable: true,
  77104. configurable: true
  77105. });
  77106. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77107. /**
  77108. * Gets Camera field of view used by the Vignette effect.
  77109. */
  77110. get: function () {
  77111. return this.imageProcessingConfiguration.vignetteCameraFov;
  77112. },
  77113. /**
  77114. * Sets Camera field of view used by the Vignette effect.
  77115. */
  77116. set: function (value) {
  77117. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77118. },
  77119. enumerable: true,
  77120. configurable: true
  77121. });
  77122. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77123. /**
  77124. * Gets the vignette blend mode allowing different kind of effect.
  77125. */
  77126. get: function () {
  77127. return this.imageProcessingConfiguration.vignetteBlendMode;
  77128. },
  77129. /**
  77130. * Sets the vignette blend mode allowing different kind of effect.
  77131. */
  77132. set: function (value) {
  77133. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77134. },
  77135. enumerable: true,
  77136. configurable: true
  77137. });
  77138. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77139. /**
  77140. * Gets wether the vignette effect is enabled.
  77141. */
  77142. get: function () {
  77143. return this.imageProcessingConfiguration.vignetteEnabled;
  77144. },
  77145. /**
  77146. * Sets wether the vignette effect is enabled.
  77147. */
  77148. set: function (value) {
  77149. this.imageProcessingConfiguration.vignetteEnabled = value;
  77150. },
  77151. enumerable: true,
  77152. configurable: true
  77153. });
  77154. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77155. /**
  77156. * Gets wether the input of the processing is in Gamma or Linear Space.
  77157. */
  77158. get: function () {
  77159. return this._fromLinearSpace;
  77160. },
  77161. /**
  77162. * Sets wether the input of the processing is in Gamma or Linear Space.
  77163. */
  77164. set: function (value) {
  77165. if (this._fromLinearSpace === value) {
  77166. return;
  77167. }
  77168. this._fromLinearSpace = value;
  77169. this._updateParameters();
  77170. },
  77171. enumerable: true,
  77172. configurable: true
  77173. });
  77174. ImageProcessingPostProcess.prototype.getClassName = function () {
  77175. return "ImageProcessingPostProcess";
  77176. };
  77177. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77178. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77179. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77180. var defines = "";
  77181. for (var define in this._defines) {
  77182. if (this._defines[define]) {
  77183. defines += "#define " + define + ";\r\n";
  77184. }
  77185. }
  77186. var samplers = ["textureSampler"];
  77187. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77188. var uniforms = ["scale"];
  77189. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77190. this.updateEffect(defines, uniforms, samplers);
  77191. };
  77192. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77193. _super.prototype.dispose.call(this, camera);
  77194. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77195. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77196. }
  77197. this.imageProcessingConfiguration.applyByPostProcess = false;
  77198. };
  77199. __decorate([
  77200. BABYLON.serialize()
  77201. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77202. return ImageProcessingPostProcess;
  77203. }(BABYLON.PostProcess));
  77204. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77205. })(BABYLON || (BABYLON = {}));
  77206. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77207. var BABYLON;
  77208. (function (BABYLON) {
  77209. /**
  77210. * Class used to store bone information
  77211. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77212. */
  77213. var Bone = /** @class */ (function (_super) {
  77214. __extends(Bone, _super);
  77215. /**
  77216. * Create a new bone
  77217. * @param name defines the bone name
  77218. * @param skeleton defines the parent skeleton
  77219. * @param parentBone defines the parent (can be null if the bone is the root)
  77220. * @param localMatrix defines the local matrix
  77221. * @param restPose defines the rest pose matrix
  77222. * @param baseMatrix defines the base matrix
  77223. * @param index defines index of the bone in the hiearchy
  77224. */
  77225. function Bone(
  77226. /**
  77227. * defines the bone name
  77228. */
  77229. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77230. if (parentBone === void 0) { parentBone = null; }
  77231. if (localMatrix === void 0) { localMatrix = null; }
  77232. if (restPose === void 0) { restPose = null; }
  77233. if (baseMatrix === void 0) { baseMatrix = null; }
  77234. if (index === void 0) { index = null; }
  77235. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77236. _this.name = name;
  77237. /**
  77238. * Gets the list of child bones
  77239. */
  77240. _this.children = new Array();
  77241. /** Gets the animations associated with this bone */
  77242. _this.animations = new Array();
  77243. /**
  77244. * @hidden Internal only
  77245. * Set this value to map this bone to a different index in the transform matrices
  77246. * Set this value to -1 to exclude the bone from the transform matrices
  77247. */
  77248. _this._index = null;
  77249. _this._absoluteTransform = new BABYLON.Matrix();
  77250. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77251. _this._scalingDeterminant = 1;
  77252. _this._worldTransform = new BABYLON.Matrix();
  77253. _this._needToDecompose = true;
  77254. _this._needToCompose = false;
  77255. _this._skeleton = skeleton;
  77256. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77257. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77258. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77259. _this._index = index;
  77260. skeleton.bones.push(_this);
  77261. _this.setParent(parentBone, false);
  77262. if (baseMatrix || localMatrix) {
  77263. _this._updateDifferenceMatrix();
  77264. }
  77265. return _this;
  77266. }
  77267. Object.defineProperty(Bone.prototype, "_matrix", {
  77268. /** @hidden */
  77269. get: function () {
  77270. this._compose();
  77271. return this._localMatrix;
  77272. },
  77273. /** @hidden */
  77274. set: function (value) {
  77275. this._localMatrix.copyFrom(value);
  77276. this._needToDecompose = true;
  77277. },
  77278. enumerable: true,
  77279. configurable: true
  77280. });
  77281. // Members
  77282. /**
  77283. * Gets the parent skeleton
  77284. * @returns a skeleton
  77285. */
  77286. Bone.prototype.getSkeleton = function () {
  77287. return this._skeleton;
  77288. };
  77289. /**
  77290. * Gets parent bone
  77291. * @returns a bone or null if the bone is the root of the bone hierarchy
  77292. */
  77293. Bone.prototype.getParent = function () {
  77294. return this._parent;
  77295. };
  77296. /**
  77297. * Sets the parent bone
  77298. * @param parent defines the parent (can be null if the bone is the root)
  77299. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77300. */
  77301. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77302. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77303. if (this._parent === parent) {
  77304. return;
  77305. }
  77306. if (this._parent) {
  77307. var index = this._parent.children.indexOf(this);
  77308. if (index !== -1) {
  77309. this._parent.children.splice(index, 1);
  77310. }
  77311. }
  77312. this._parent = parent;
  77313. if (this._parent) {
  77314. this._parent.children.push(this);
  77315. }
  77316. if (updateDifferenceMatrix) {
  77317. this._updateDifferenceMatrix();
  77318. }
  77319. this.markAsDirty();
  77320. };
  77321. /**
  77322. * Gets the local matrix
  77323. * @returns a matrix
  77324. */
  77325. Bone.prototype.getLocalMatrix = function () {
  77326. this._compose();
  77327. return this._localMatrix;
  77328. };
  77329. /**
  77330. * Gets the base matrix (initial matrix which remains unchanged)
  77331. * @returns a matrix
  77332. */
  77333. Bone.prototype.getBaseMatrix = function () {
  77334. return this._baseMatrix;
  77335. };
  77336. /**
  77337. * Gets the rest pose matrix
  77338. * @returns a matrix
  77339. */
  77340. Bone.prototype.getRestPose = function () {
  77341. return this._restPose;
  77342. };
  77343. /**
  77344. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77345. */
  77346. Bone.prototype.getWorldMatrix = function () {
  77347. return this._worldTransform;
  77348. };
  77349. /**
  77350. * Sets the local matrix to rest pose matrix
  77351. */
  77352. Bone.prototype.returnToRest = function () {
  77353. this.updateMatrix(this._restPose.clone());
  77354. };
  77355. /**
  77356. * Gets the inverse of the absolute transform matrix.
  77357. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77358. * @returns a matrix
  77359. */
  77360. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77361. return this._invertedAbsoluteTransform;
  77362. };
  77363. /**
  77364. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77365. * @returns a matrix
  77366. */
  77367. Bone.prototype.getAbsoluteTransform = function () {
  77368. return this._absoluteTransform;
  77369. };
  77370. Object.defineProperty(Bone.prototype, "position", {
  77371. // Properties (matches AbstractMesh properties)
  77372. /** Gets or sets current position (in local space) */
  77373. get: function () {
  77374. this._decompose();
  77375. return this._localPosition;
  77376. },
  77377. set: function (newPosition) {
  77378. this._decompose();
  77379. this._localPosition.copyFrom(newPosition);
  77380. this._markAsDirtyAndCompose();
  77381. },
  77382. enumerable: true,
  77383. configurable: true
  77384. });
  77385. Object.defineProperty(Bone.prototype, "rotation", {
  77386. /** Gets or sets current rotation (in local space) */
  77387. get: function () {
  77388. return this.getRotation();
  77389. },
  77390. set: function (newRotation) {
  77391. this.setRotation(newRotation);
  77392. },
  77393. enumerable: true,
  77394. configurable: true
  77395. });
  77396. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77397. /** Gets or sets current rotation quaternion (in local space) */
  77398. get: function () {
  77399. this._decompose();
  77400. return this._localRotation;
  77401. },
  77402. set: function (newRotation) {
  77403. this.setRotationQuaternion(newRotation);
  77404. },
  77405. enumerable: true,
  77406. configurable: true
  77407. });
  77408. Object.defineProperty(Bone.prototype, "scaling", {
  77409. /** Gets or sets current scaling (in local space) */
  77410. get: function () {
  77411. return this.getScale();
  77412. },
  77413. set: function (newScaling) {
  77414. this.setScale(newScaling);
  77415. },
  77416. enumerable: true,
  77417. configurable: true
  77418. });
  77419. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77420. /**
  77421. * Gets the animation properties override
  77422. */
  77423. get: function () {
  77424. return this._skeleton.animationPropertiesOverride;
  77425. },
  77426. enumerable: true,
  77427. configurable: true
  77428. });
  77429. // Methods
  77430. Bone.prototype._decompose = function () {
  77431. if (!this._needToDecompose) {
  77432. return;
  77433. }
  77434. this._needToDecompose = false;
  77435. if (!this._localScaling) {
  77436. this._localScaling = BABYLON.Vector3.Zero();
  77437. this._localRotation = BABYLON.Quaternion.Zero();
  77438. this._localPosition = BABYLON.Vector3.Zero();
  77439. }
  77440. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77441. };
  77442. Bone.prototype._compose = function () {
  77443. if (!this._needToCompose) {
  77444. return;
  77445. }
  77446. this._needToCompose = false;
  77447. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77448. };
  77449. /**
  77450. * Update the base and local matrices
  77451. * @param matrix defines the new base or local matrix
  77452. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77453. * @param updateLocalMatrix defines if the local matrix should be updated
  77454. */
  77455. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77456. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77457. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77458. this._baseMatrix.copyFrom(matrix);
  77459. if (updateDifferenceMatrix) {
  77460. this._updateDifferenceMatrix();
  77461. }
  77462. if (updateLocalMatrix) {
  77463. this._localMatrix.copyFrom(matrix);
  77464. this._markAsDirtyAndDecompose();
  77465. }
  77466. else {
  77467. this.markAsDirty();
  77468. }
  77469. };
  77470. /** @hidden */
  77471. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77472. if (updateChildren === void 0) { updateChildren = true; }
  77473. if (!rootMatrix) {
  77474. rootMatrix = this._baseMatrix;
  77475. }
  77476. if (this._parent) {
  77477. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77478. }
  77479. else {
  77480. this._absoluteTransform.copyFrom(rootMatrix);
  77481. }
  77482. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77483. if (updateChildren) {
  77484. for (var index = 0; index < this.children.length; index++) {
  77485. this.children[index]._updateDifferenceMatrix();
  77486. }
  77487. }
  77488. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77489. };
  77490. /**
  77491. * Flag the bone as dirty (Forcing it to update everything)
  77492. */
  77493. Bone.prototype.markAsDirty = function () {
  77494. this._currentRenderId++;
  77495. this._childRenderId++;
  77496. this._skeleton._markAsDirty();
  77497. };
  77498. Bone.prototype._markAsDirtyAndCompose = function () {
  77499. this.markAsDirty();
  77500. this._needToCompose = true;
  77501. };
  77502. Bone.prototype._markAsDirtyAndDecompose = function () {
  77503. this.markAsDirty();
  77504. this._needToDecompose = true;
  77505. };
  77506. /**
  77507. * Copy an animation range from another bone
  77508. * @param source defines the source bone
  77509. * @param rangeName defines the range name to copy
  77510. * @param frameOffset defines the frame offset
  77511. * @param rescaleAsRequired defines if rescaling must be applied if required
  77512. * @param skelDimensionsRatio defines the scaling ratio
  77513. * @returns true if operation was successful
  77514. */
  77515. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77516. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77517. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77518. // all animation may be coming from a library skeleton, so may need to create animation
  77519. if (this.animations.length === 0) {
  77520. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77521. this.animations[0].setKeys([]);
  77522. }
  77523. // get animation info / verify there is such a range from the source bone
  77524. var sourceRange = source.animations[0].getRange(rangeName);
  77525. if (!sourceRange) {
  77526. return false;
  77527. }
  77528. var from = sourceRange.from;
  77529. var to = sourceRange.to;
  77530. var sourceKeys = source.animations[0].getKeys();
  77531. // rescaling prep
  77532. var sourceBoneLength = source.length;
  77533. var sourceParent = source.getParent();
  77534. var parent = this.getParent();
  77535. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77536. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77537. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77538. var destKeys = this.animations[0].getKeys();
  77539. // loop vars declaration
  77540. var orig;
  77541. var origTranslation;
  77542. var mat;
  77543. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77544. orig = sourceKeys[key];
  77545. if (orig.frame >= from && orig.frame <= to) {
  77546. if (rescaleAsRequired) {
  77547. mat = orig.value.clone();
  77548. // scale based on parent ratio, when bone has parent
  77549. if (parentScalingReqd) {
  77550. origTranslation = mat.getTranslation();
  77551. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77552. // scale based on skeleton dimension ratio when root bone, and value is passed
  77553. }
  77554. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77555. origTranslation = mat.getTranslation();
  77556. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77557. // use original when root bone, and no data for skelDimensionsRatio
  77558. }
  77559. else {
  77560. mat = orig.value;
  77561. }
  77562. }
  77563. else {
  77564. mat = orig.value;
  77565. }
  77566. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77567. }
  77568. }
  77569. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77570. return true;
  77571. };
  77572. /**
  77573. * Translate the bone in local or world space
  77574. * @param vec The amount to translate the bone
  77575. * @param space The space that the translation is in
  77576. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77577. */
  77578. Bone.prototype.translate = function (vec, space, mesh) {
  77579. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77580. var lm = this.getLocalMatrix();
  77581. if (space == BABYLON.Space.LOCAL) {
  77582. lm.m[12] += vec.x;
  77583. lm.m[13] += vec.y;
  77584. lm.m[14] += vec.z;
  77585. }
  77586. else {
  77587. var wm = null;
  77588. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77589. if (mesh) {
  77590. wm = mesh.getWorldMatrix();
  77591. }
  77592. this._skeleton.computeAbsoluteTransforms();
  77593. var tmat = Bone._tmpMats[0];
  77594. var tvec = Bone._tmpVecs[0];
  77595. if (this._parent) {
  77596. if (mesh && wm) {
  77597. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77598. tmat.multiplyToRef(wm, tmat);
  77599. }
  77600. else {
  77601. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77602. }
  77603. }
  77604. tmat.m[12] = 0;
  77605. tmat.m[13] = 0;
  77606. tmat.m[14] = 0;
  77607. tmat.invert();
  77608. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77609. lm.m[12] += tvec.x;
  77610. lm.m[13] += tvec.y;
  77611. lm.m[14] += tvec.z;
  77612. }
  77613. this._markAsDirtyAndDecompose();
  77614. };
  77615. /**
  77616. * Set the postion of the bone in local or world space
  77617. * @param position The position to set the bone
  77618. * @param space The space that the position is in
  77619. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77620. */
  77621. Bone.prototype.setPosition = function (position, space, mesh) {
  77622. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77623. var lm = this.getLocalMatrix();
  77624. if (space == BABYLON.Space.LOCAL) {
  77625. lm.m[12] = position.x;
  77626. lm.m[13] = position.y;
  77627. lm.m[14] = position.z;
  77628. }
  77629. else {
  77630. var wm = null;
  77631. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77632. if (mesh) {
  77633. wm = mesh.getWorldMatrix();
  77634. }
  77635. this._skeleton.computeAbsoluteTransforms();
  77636. var tmat = Bone._tmpMats[0];
  77637. var vec = Bone._tmpVecs[0];
  77638. if (this._parent) {
  77639. if (mesh && wm) {
  77640. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77641. tmat.multiplyToRef(wm, tmat);
  77642. }
  77643. else {
  77644. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77645. }
  77646. }
  77647. tmat.invert();
  77648. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77649. lm.m[12] = vec.x;
  77650. lm.m[13] = vec.y;
  77651. lm.m[14] = vec.z;
  77652. }
  77653. this._markAsDirtyAndDecompose();
  77654. };
  77655. /**
  77656. * Set the absolute position of the bone (world space)
  77657. * @param position The position to set the bone
  77658. * @param mesh The mesh that this bone is attached to
  77659. */
  77660. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77661. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77662. };
  77663. /**
  77664. * Scale the bone on the x, y and z axes (in local space)
  77665. * @param x The amount to scale the bone on the x axis
  77666. * @param y The amount to scale the bone on the y axis
  77667. * @param z The amount to scale the bone on the z axis
  77668. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77669. */
  77670. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77671. if (scaleChildren === void 0) { scaleChildren = false; }
  77672. var locMat = this.getLocalMatrix();
  77673. // Apply new scaling on top of current local matrix
  77674. var scaleMat = Bone._tmpMats[0];
  77675. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77676. scaleMat.multiplyToRef(locMat, locMat);
  77677. // Invert scaling matrix and apply the inverse to all children
  77678. scaleMat.invert();
  77679. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77680. var child = _a[_i];
  77681. var cm = child.getLocalMatrix();
  77682. cm.multiplyToRef(scaleMat, cm);
  77683. cm.m[12] *= x;
  77684. cm.m[13] *= y;
  77685. cm.m[14] *= z;
  77686. child._markAsDirtyAndDecompose();
  77687. }
  77688. this._markAsDirtyAndDecompose();
  77689. if (scaleChildren) {
  77690. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77691. var child = _c[_b];
  77692. child.scale(x, y, z, scaleChildren);
  77693. }
  77694. }
  77695. };
  77696. /**
  77697. * Set the bone scaling in local space
  77698. * @param scale defines the scaling vector
  77699. */
  77700. Bone.prototype.setScale = function (scale) {
  77701. this._decompose();
  77702. this._localScaling.copyFrom(scale);
  77703. this._markAsDirtyAndCompose();
  77704. };
  77705. /**
  77706. * Gets the current scaling in local space
  77707. * @returns the current scaling vector
  77708. */
  77709. Bone.prototype.getScale = function () {
  77710. this._decompose();
  77711. return this._localScaling;
  77712. };
  77713. /**
  77714. * Gets the current scaling in local space and stores it in a target vector
  77715. * @param result defines the target vector
  77716. */
  77717. Bone.prototype.getScaleToRef = function (result) {
  77718. this._decompose();
  77719. result.copyFrom(this._localScaling);
  77720. };
  77721. /**
  77722. * Set the yaw, pitch, and roll of the bone in local or world space
  77723. * @param yaw The rotation of the bone on the y axis
  77724. * @param pitch The rotation of the bone on the x axis
  77725. * @param roll The rotation of the bone on the z axis
  77726. * @param space The space that the axes of rotation are in
  77727. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77728. */
  77729. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77730. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77731. if (space === BABYLON.Space.LOCAL) {
  77732. var quat = Bone._tmpQuat;
  77733. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77734. this.setRotationQuaternion(quat, space, mesh);
  77735. return;
  77736. }
  77737. var rotMatInv = Bone._tmpMats[0];
  77738. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77739. return;
  77740. }
  77741. var rotMat = Bone._tmpMats[1];
  77742. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77743. rotMatInv.multiplyToRef(rotMat, rotMat);
  77744. this._rotateWithMatrix(rotMat, space, mesh);
  77745. };
  77746. /**
  77747. * Add a rotation to the bone on an axis in local or world space
  77748. * @param axis The axis to rotate the bone on
  77749. * @param amount The amount to rotate the bone
  77750. * @param space The space that the axis is in
  77751. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77752. */
  77753. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77754. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77755. var rmat = Bone._tmpMats[0];
  77756. rmat.m[12] = 0;
  77757. rmat.m[13] = 0;
  77758. rmat.m[14] = 0;
  77759. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77760. this._rotateWithMatrix(rmat, space, mesh);
  77761. };
  77762. /**
  77763. * Set the rotation of the bone to a particular axis angle in local or world space
  77764. * @param axis The axis to rotate the bone on
  77765. * @param angle The angle that the bone should be rotated to
  77766. * @param space The space that the axis is in
  77767. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77768. */
  77769. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77770. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77771. if (space === BABYLON.Space.LOCAL) {
  77772. var quat = Bone._tmpQuat;
  77773. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77774. this.setRotationQuaternion(quat, space, mesh);
  77775. return;
  77776. }
  77777. var rotMatInv = Bone._tmpMats[0];
  77778. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77779. return;
  77780. }
  77781. var rotMat = Bone._tmpMats[1];
  77782. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77783. rotMatInv.multiplyToRef(rotMat, rotMat);
  77784. this._rotateWithMatrix(rotMat, space, mesh);
  77785. };
  77786. /**
  77787. * Set the euler rotation of the bone in local of world space
  77788. * @param rotation The euler rotation that the bone should be set to
  77789. * @param space The space that the rotation is in
  77790. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77791. */
  77792. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77793. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77794. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77795. };
  77796. /**
  77797. * Set the quaternion rotation of the bone in local of world space
  77798. * @param quat The quaternion rotation that the bone should be set to
  77799. * @param space The space that the rotation is in
  77800. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77801. */
  77802. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77803. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77804. if (space === BABYLON.Space.LOCAL) {
  77805. this._decompose();
  77806. this._localRotation.copyFrom(quat);
  77807. this._markAsDirtyAndCompose();
  77808. return;
  77809. }
  77810. var rotMatInv = Bone._tmpMats[0];
  77811. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77812. return;
  77813. }
  77814. var rotMat = Bone._tmpMats[1];
  77815. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77816. rotMatInv.multiplyToRef(rotMat, rotMat);
  77817. this._rotateWithMatrix(rotMat, space, mesh);
  77818. };
  77819. /**
  77820. * Set the rotation matrix of the bone in local of world space
  77821. * @param rotMat The rotation matrix that the bone should be set to
  77822. * @param space The space that the rotation is in
  77823. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77824. */
  77825. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77826. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77827. if (space === BABYLON.Space.LOCAL) {
  77828. var quat = Bone._tmpQuat;
  77829. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77830. this.setRotationQuaternion(quat, space, mesh);
  77831. return;
  77832. }
  77833. var rotMatInv = Bone._tmpMats[0];
  77834. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77835. return;
  77836. }
  77837. var rotMat2 = Bone._tmpMats[1];
  77838. rotMat2.copyFrom(rotMat);
  77839. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77840. this._rotateWithMatrix(rotMat2, space, mesh);
  77841. };
  77842. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77843. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77844. var lmat = this.getLocalMatrix();
  77845. var lx = lmat.m[12];
  77846. var ly = lmat.m[13];
  77847. var lz = lmat.m[14];
  77848. var parent = this.getParent();
  77849. var parentScale = Bone._tmpMats[3];
  77850. var parentScaleInv = Bone._tmpMats[4];
  77851. if (parent && space == BABYLON.Space.WORLD) {
  77852. if (mesh) {
  77853. parentScale.copyFrom(mesh.getWorldMatrix());
  77854. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77855. }
  77856. else {
  77857. parentScale.copyFrom(parent.getAbsoluteTransform());
  77858. }
  77859. parentScaleInv.copyFrom(parentScale);
  77860. parentScaleInv.invert();
  77861. lmat.multiplyToRef(parentScale, lmat);
  77862. lmat.multiplyToRef(rmat, lmat);
  77863. lmat.multiplyToRef(parentScaleInv, lmat);
  77864. }
  77865. else {
  77866. if (space == BABYLON.Space.WORLD && mesh) {
  77867. parentScale.copyFrom(mesh.getWorldMatrix());
  77868. parentScaleInv.copyFrom(parentScale);
  77869. parentScaleInv.invert();
  77870. lmat.multiplyToRef(parentScale, lmat);
  77871. lmat.multiplyToRef(rmat, lmat);
  77872. lmat.multiplyToRef(parentScaleInv, lmat);
  77873. }
  77874. else {
  77875. lmat.multiplyToRef(rmat, lmat);
  77876. }
  77877. }
  77878. lmat.m[12] = lx;
  77879. lmat.m[13] = ly;
  77880. lmat.m[14] = lz;
  77881. this.computeAbsoluteTransforms();
  77882. this._markAsDirtyAndDecompose();
  77883. };
  77884. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77885. var scaleMatrix = Bone._tmpMats[2];
  77886. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77887. if (mesh) {
  77888. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77889. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77890. }
  77891. rotMatInv.invert();
  77892. if (isNaN(rotMatInv.m[0])) {
  77893. // Matrix failed to invert.
  77894. // This can happen if scale is zero for example.
  77895. return false;
  77896. }
  77897. scaleMatrix.m[0] *= this._scalingDeterminant;
  77898. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77899. return true;
  77900. };
  77901. /**
  77902. * Get the position of the bone in local or world space
  77903. * @param space The space that the returned position is in
  77904. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77905. * @returns The position of the bone
  77906. */
  77907. Bone.prototype.getPosition = function (space, mesh) {
  77908. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77909. if (mesh === void 0) { mesh = null; }
  77910. var pos = BABYLON.Vector3.Zero();
  77911. this.getPositionToRef(space, mesh, pos);
  77912. return pos;
  77913. };
  77914. /**
  77915. * Copy the position of the bone to a vector3 in local or world space
  77916. * @param space The space that the returned position is in
  77917. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77918. * @param result The vector3 to copy the position to
  77919. */
  77920. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77921. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77922. if (space == BABYLON.Space.LOCAL) {
  77923. var lm = this.getLocalMatrix();
  77924. result.x = lm.m[12];
  77925. result.y = lm.m[13];
  77926. result.z = lm.m[14];
  77927. }
  77928. else {
  77929. var wm = null;
  77930. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77931. if (mesh) {
  77932. wm = mesh.getWorldMatrix();
  77933. }
  77934. this._skeleton.computeAbsoluteTransforms();
  77935. var tmat = Bone._tmpMats[0];
  77936. if (mesh && wm) {
  77937. tmat.copyFrom(this.getAbsoluteTransform());
  77938. tmat.multiplyToRef(wm, tmat);
  77939. }
  77940. else {
  77941. tmat = this.getAbsoluteTransform();
  77942. }
  77943. result.x = tmat.m[12];
  77944. result.y = tmat.m[13];
  77945. result.z = tmat.m[14];
  77946. }
  77947. };
  77948. /**
  77949. * Get the absolute position of the bone (world space)
  77950. * @param mesh The mesh that this bone is attached to
  77951. * @returns The absolute position of the bone
  77952. */
  77953. Bone.prototype.getAbsolutePosition = function (mesh) {
  77954. if (mesh === void 0) { mesh = null; }
  77955. var pos = BABYLON.Vector3.Zero();
  77956. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  77957. return pos;
  77958. };
  77959. /**
  77960. * Copy the absolute position of the bone (world space) to the result param
  77961. * @param mesh The mesh that this bone is attached to
  77962. * @param result The vector3 to copy the absolute position to
  77963. */
  77964. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  77965. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  77966. };
  77967. /**
  77968. * Compute the absolute transforms of this bone and its children
  77969. */
  77970. Bone.prototype.computeAbsoluteTransforms = function () {
  77971. this._compose();
  77972. if (this._parent) {
  77973. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77974. }
  77975. else {
  77976. this._absoluteTransform.copyFrom(this._localMatrix);
  77977. var poseMatrix = this._skeleton.getPoseMatrix();
  77978. if (poseMatrix) {
  77979. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  77980. }
  77981. }
  77982. var children = this.children;
  77983. var len = children.length;
  77984. for (var i = 0; i < len; i++) {
  77985. children[i].computeAbsoluteTransforms();
  77986. }
  77987. };
  77988. /**
  77989. * Get the world direction from an axis that is in the local space of the bone
  77990. * @param localAxis The local direction that is used to compute the world direction
  77991. * @param mesh The mesh that this bone is attached to
  77992. * @returns The world direction
  77993. */
  77994. Bone.prototype.getDirection = function (localAxis, mesh) {
  77995. if (mesh === void 0) { mesh = null; }
  77996. var result = BABYLON.Vector3.Zero();
  77997. this.getDirectionToRef(localAxis, mesh, result);
  77998. return result;
  77999. };
  78000. /**
  78001. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78002. * @param localAxis The local direction that is used to compute the world direction
  78003. * @param mesh The mesh that this bone is attached to
  78004. * @param result The vector3 that the world direction will be copied to
  78005. */
  78006. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78007. if (mesh === void 0) { mesh = null; }
  78008. var wm = null;
  78009. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78010. if (mesh) {
  78011. wm = mesh.getWorldMatrix();
  78012. }
  78013. this._skeleton.computeAbsoluteTransforms();
  78014. var mat = Bone._tmpMats[0];
  78015. mat.copyFrom(this.getAbsoluteTransform());
  78016. if (mesh && wm) {
  78017. mat.multiplyToRef(wm, mat);
  78018. }
  78019. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78020. result.normalize();
  78021. };
  78022. /**
  78023. * Get the euler rotation of the bone in local or world space
  78024. * @param space The space that the rotation should be in
  78025. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78026. * @returns The euler rotation
  78027. */
  78028. Bone.prototype.getRotation = function (space, mesh) {
  78029. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78030. if (mesh === void 0) { mesh = null; }
  78031. var result = BABYLON.Vector3.Zero();
  78032. this.getRotationToRef(space, mesh, result);
  78033. return result;
  78034. };
  78035. /**
  78036. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78037. * @param space The space that the rotation should be in
  78038. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78039. * @param result The vector3 that the rotation should be copied to
  78040. */
  78041. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78042. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78043. if (mesh === void 0) { mesh = null; }
  78044. var quat = Bone._tmpQuat;
  78045. this.getRotationQuaternionToRef(space, mesh, quat);
  78046. quat.toEulerAnglesToRef(result);
  78047. };
  78048. /**
  78049. * Get the quaternion rotation of the bone in either local or world space
  78050. * @param space The space that the rotation should be in
  78051. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78052. * @returns The quaternion rotation
  78053. */
  78054. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78055. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78056. if (mesh === void 0) { mesh = null; }
  78057. var result = BABYLON.Quaternion.Identity();
  78058. this.getRotationQuaternionToRef(space, mesh, result);
  78059. return result;
  78060. };
  78061. /**
  78062. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78063. * @param space The space that the rotation should be in
  78064. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78065. * @param result The quaternion that the rotation should be copied to
  78066. */
  78067. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78068. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78069. if (mesh === void 0) { mesh = null; }
  78070. if (space == BABYLON.Space.LOCAL) {
  78071. this._decompose();
  78072. result.copyFrom(this._localRotation);
  78073. }
  78074. else {
  78075. var mat = Bone._tmpMats[0];
  78076. var amat = this.getAbsoluteTransform();
  78077. if (mesh) {
  78078. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78079. }
  78080. else {
  78081. mat.copyFrom(amat);
  78082. }
  78083. mat.m[0] *= this._scalingDeterminant;
  78084. mat.m[1] *= this._scalingDeterminant;
  78085. mat.m[2] *= this._scalingDeterminant;
  78086. mat.decompose(undefined, result, undefined);
  78087. }
  78088. };
  78089. /**
  78090. * Get the rotation matrix of the bone in local or world space
  78091. * @param space The space that the rotation should be in
  78092. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78093. * @returns The rotation matrix
  78094. */
  78095. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78096. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78097. var result = BABYLON.Matrix.Identity();
  78098. this.getRotationMatrixToRef(space, mesh, result);
  78099. return result;
  78100. };
  78101. /**
  78102. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78103. * @param space The space that the rotation should be in
  78104. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78105. * @param result The quaternion that the rotation should be copied to
  78106. */
  78107. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78108. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78109. if (space == BABYLON.Space.LOCAL) {
  78110. this.getLocalMatrix().getRotationMatrixToRef(result);
  78111. }
  78112. else {
  78113. var mat = Bone._tmpMats[0];
  78114. var amat = this.getAbsoluteTransform();
  78115. if (mesh) {
  78116. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78117. }
  78118. else {
  78119. mat.copyFrom(amat);
  78120. }
  78121. mat.m[0] *= this._scalingDeterminant;
  78122. mat.m[1] *= this._scalingDeterminant;
  78123. mat.m[2] *= this._scalingDeterminant;
  78124. mat.getRotationMatrixToRef(result);
  78125. }
  78126. };
  78127. /**
  78128. * Get the world position of a point that is in the local space of the bone
  78129. * @param position The local position
  78130. * @param mesh The mesh that this bone is attached to
  78131. * @returns The world position
  78132. */
  78133. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78134. if (mesh === void 0) { mesh = null; }
  78135. var result = BABYLON.Vector3.Zero();
  78136. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78137. return result;
  78138. };
  78139. /**
  78140. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78141. * @param position The local position
  78142. * @param mesh The mesh that this bone is attached to
  78143. * @param result The vector3 that the world position should be copied to
  78144. */
  78145. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78146. if (mesh === void 0) { mesh = null; }
  78147. var wm = null;
  78148. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78149. if (mesh) {
  78150. wm = mesh.getWorldMatrix();
  78151. }
  78152. this._skeleton.computeAbsoluteTransforms();
  78153. var tmat = Bone._tmpMats[0];
  78154. if (mesh && wm) {
  78155. tmat.copyFrom(this.getAbsoluteTransform());
  78156. tmat.multiplyToRef(wm, tmat);
  78157. }
  78158. else {
  78159. tmat = this.getAbsoluteTransform();
  78160. }
  78161. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78162. };
  78163. /**
  78164. * Get the local position of a point that is in world space
  78165. * @param position The world position
  78166. * @param mesh The mesh that this bone is attached to
  78167. * @returns The local position
  78168. */
  78169. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78170. if (mesh === void 0) { mesh = null; }
  78171. var result = BABYLON.Vector3.Zero();
  78172. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78173. return result;
  78174. };
  78175. /**
  78176. * Get the local position of a point that is in world space and copy it to the result param
  78177. * @param position The world position
  78178. * @param mesh The mesh that this bone is attached to
  78179. * @param result The vector3 that the local position should be copied to
  78180. */
  78181. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78182. if (mesh === void 0) { mesh = null; }
  78183. var wm = null;
  78184. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78185. if (mesh) {
  78186. wm = mesh.getWorldMatrix();
  78187. }
  78188. this._skeleton.computeAbsoluteTransforms();
  78189. var tmat = Bone._tmpMats[0];
  78190. tmat.copyFrom(this.getAbsoluteTransform());
  78191. if (mesh && wm) {
  78192. tmat.multiplyToRef(wm, tmat);
  78193. }
  78194. tmat.invert();
  78195. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78196. };
  78197. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78198. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78199. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78200. return Bone;
  78201. }(BABYLON.Node));
  78202. BABYLON.Bone = Bone;
  78203. })(BABYLON || (BABYLON = {}));
  78204. //# sourceMappingURL=babylon.bone.js.map
  78205. var BABYLON;
  78206. (function (BABYLON) {
  78207. /**
  78208. * Class used to apply inverse kinematics to bones
  78209. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78210. */
  78211. var BoneIKController = /** @class */ (function () {
  78212. /**
  78213. * Creates a new BoneIKController
  78214. * @param mesh defines the mesh to control
  78215. * @param bone defines the bone to control
  78216. * @param options defines options to set up the controller
  78217. */
  78218. function BoneIKController(mesh, bone, options) {
  78219. /**
  78220. * Gets or sets the target position
  78221. */
  78222. this.targetPosition = BABYLON.Vector3.Zero();
  78223. /**
  78224. * Gets or sets the pole target position
  78225. */
  78226. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78227. /**
  78228. * Gets or sets the pole target local offset
  78229. */
  78230. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78231. /**
  78232. * Gets or sets the pole angle
  78233. */
  78234. this.poleAngle = 0;
  78235. /**
  78236. * 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)
  78237. */
  78238. this.slerpAmount = 1;
  78239. this._bone1Quat = BABYLON.Quaternion.Identity();
  78240. this._bone1Mat = BABYLON.Matrix.Identity();
  78241. this._bone2Ang = Math.PI;
  78242. this._maxAngle = Math.PI;
  78243. this._rightHandedSystem = false;
  78244. this._bendAxis = BABYLON.Vector3.Right();
  78245. this._slerping = false;
  78246. this._adjustRoll = 0;
  78247. this._bone2 = bone;
  78248. this._bone1 = bone.getParent();
  78249. if (!this._bone1) {
  78250. return;
  78251. }
  78252. this.mesh = mesh;
  78253. var bonePos = bone.getPosition();
  78254. if (bone.getAbsoluteTransform().determinant() > 0) {
  78255. this._rightHandedSystem = true;
  78256. this._bendAxis.x = 0;
  78257. this._bendAxis.y = 0;
  78258. this._bendAxis.z = -1;
  78259. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78260. this._adjustRoll = Math.PI * .5;
  78261. this._bendAxis.z = 1;
  78262. }
  78263. }
  78264. if (this._bone1.length) {
  78265. var boneScale1 = this._bone1.getScale();
  78266. var boneScale2 = this._bone2.getScale();
  78267. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78268. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78269. }
  78270. else if (this._bone1.children[0]) {
  78271. mesh.computeWorldMatrix(true);
  78272. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78273. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78274. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78275. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78276. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78277. }
  78278. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78279. this.maxAngle = Math.PI;
  78280. if (options) {
  78281. if (options.targetMesh) {
  78282. this.targetMesh = options.targetMesh;
  78283. this.targetMesh.computeWorldMatrix(true);
  78284. }
  78285. if (options.poleTargetMesh) {
  78286. this.poleTargetMesh = options.poleTargetMesh;
  78287. this.poleTargetMesh.computeWorldMatrix(true);
  78288. }
  78289. else if (options.poleTargetBone) {
  78290. this.poleTargetBone = options.poleTargetBone;
  78291. }
  78292. else if (this._bone1.getParent()) {
  78293. this.poleTargetBone = this._bone1.getParent();
  78294. }
  78295. if (options.poleTargetLocalOffset) {
  78296. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78297. }
  78298. if (options.poleAngle) {
  78299. this.poleAngle = options.poleAngle;
  78300. }
  78301. if (options.bendAxis) {
  78302. this._bendAxis.copyFrom(options.bendAxis);
  78303. }
  78304. if (options.maxAngle) {
  78305. this.maxAngle = options.maxAngle;
  78306. }
  78307. if (options.slerpAmount) {
  78308. this.slerpAmount = options.slerpAmount;
  78309. }
  78310. }
  78311. }
  78312. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78313. /**
  78314. * Gets or sets maximum allowed angle
  78315. */
  78316. get: function () {
  78317. return this._maxAngle;
  78318. },
  78319. set: function (value) {
  78320. this._setMaxAngle(value);
  78321. },
  78322. enumerable: true,
  78323. configurable: true
  78324. });
  78325. BoneIKController.prototype._setMaxAngle = function (ang) {
  78326. if (ang < 0) {
  78327. ang = 0;
  78328. }
  78329. if (ang > Math.PI || ang == undefined) {
  78330. ang = Math.PI;
  78331. }
  78332. this._maxAngle = ang;
  78333. var a = this._bone1Length;
  78334. var b = this._bone2Length;
  78335. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78336. };
  78337. /**
  78338. * Force the controller to update the bones
  78339. */
  78340. BoneIKController.prototype.update = function () {
  78341. var bone1 = this._bone1;
  78342. if (!bone1) {
  78343. return;
  78344. }
  78345. var target = this.targetPosition;
  78346. var poleTarget = this.poleTargetPosition;
  78347. var mat1 = BoneIKController._tmpMats[0];
  78348. var mat2 = BoneIKController._tmpMats[1];
  78349. if (this.targetMesh) {
  78350. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78351. }
  78352. if (this.poleTargetBone) {
  78353. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78354. }
  78355. else if (this.poleTargetMesh) {
  78356. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78357. }
  78358. var bonePos = BoneIKController._tmpVecs[0];
  78359. var zaxis = BoneIKController._tmpVecs[1];
  78360. var xaxis = BoneIKController._tmpVecs[2];
  78361. var yaxis = BoneIKController._tmpVecs[3];
  78362. var upAxis = BoneIKController._tmpVecs[4];
  78363. var _tmpQuat = BoneIKController._tmpQuat;
  78364. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78365. poleTarget.subtractToRef(bonePos, upAxis);
  78366. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78367. upAxis.y = 1;
  78368. }
  78369. else {
  78370. upAxis.normalize();
  78371. }
  78372. target.subtractToRef(bonePos, yaxis);
  78373. yaxis.normalize();
  78374. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78375. zaxis.normalize();
  78376. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78377. xaxis.normalize();
  78378. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78379. var a = this._bone1Length;
  78380. var b = this._bone2Length;
  78381. var c = BABYLON.Vector3.Distance(bonePos, target);
  78382. if (this._maxReach > 0) {
  78383. c = Math.min(this._maxReach, c);
  78384. }
  78385. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78386. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78387. if (acosa > 1) {
  78388. acosa = 1;
  78389. }
  78390. if (acosb > 1) {
  78391. acosb = 1;
  78392. }
  78393. if (acosa < -1) {
  78394. acosa = -1;
  78395. }
  78396. if (acosb < -1) {
  78397. acosb = -1;
  78398. }
  78399. var angA = Math.acos(acosa);
  78400. var angB = Math.acos(acosb);
  78401. var angC = -angA - angB;
  78402. if (this._rightHandedSystem) {
  78403. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78404. mat2.multiplyToRef(mat1, mat1);
  78405. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78406. mat2.multiplyToRef(mat1, mat1);
  78407. }
  78408. else {
  78409. var _tmpVec = BoneIKController._tmpVecs[5];
  78410. _tmpVec.copyFrom(this._bendAxis);
  78411. _tmpVec.x *= -1;
  78412. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78413. mat2.multiplyToRef(mat1, mat1);
  78414. }
  78415. if (this.poleAngle) {
  78416. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78417. mat1.multiplyToRef(mat2, mat1);
  78418. }
  78419. if (this._bone1) {
  78420. if (this.slerpAmount < 1) {
  78421. if (!this._slerping) {
  78422. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78423. }
  78424. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78425. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78426. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78427. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78428. this._slerping = true;
  78429. }
  78430. else {
  78431. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78432. this._bone1Mat.copyFrom(mat1);
  78433. this._slerping = false;
  78434. }
  78435. }
  78436. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78437. this._bone2Ang = angC;
  78438. };
  78439. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78440. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78441. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78442. return BoneIKController;
  78443. }());
  78444. BABYLON.BoneIKController = BoneIKController;
  78445. })(BABYLON || (BABYLON = {}));
  78446. //# sourceMappingURL=babylon.boneIKController.js.map
  78447. var BABYLON;
  78448. (function (BABYLON) {
  78449. /**
  78450. * Class used to make a bone look toward a point in space
  78451. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78452. */
  78453. var BoneLookController = /** @class */ (function () {
  78454. /**
  78455. * Create a BoneLookController
  78456. * @param mesh the mesh that the bone belongs to
  78457. * @param bone the bone that will be looking to the target
  78458. * @param target the target Vector3 to look at
  78459. * @param settings optional settings:
  78460. * * maxYaw: the maximum angle the bone will yaw to
  78461. * * minYaw: the minimum angle the bone will yaw to
  78462. * * maxPitch: the maximum angle the bone will pitch to
  78463. * * minPitch: the minimum angle the bone will yaw to
  78464. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78465. * * upAxis: the up axis of the coordinate system
  78466. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78467. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78468. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78469. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78470. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78471. * * adjustRoll: used to make an adjustment to the roll of the bone
  78472. **/
  78473. function BoneLookController(mesh, bone, target, options) {
  78474. /**
  78475. * The up axis of the coordinate system that is used when the bone is rotated
  78476. */
  78477. this.upAxis = BABYLON.Vector3.Up();
  78478. /**
  78479. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78480. */
  78481. this.upAxisSpace = BABYLON.Space.LOCAL;
  78482. /**
  78483. * Used to make an adjustment to the yaw of the bone
  78484. */
  78485. this.adjustYaw = 0;
  78486. /**
  78487. * Used to make an adjustment to the pitch of the bone
  78488. */
  78489. this.adjustPitch = 0;
  78490. /**
  78491. * Used to make an adjustment to the roll of the bone
  78492. */
  78493. this.adjustRoll = 0;
  78494. /**
  78495. * 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)
  78496. */
  78497. this.slerpAmount = 1;
  78498. this._boneQuat = BABYLON.Quaternion.Identity();
  78499. this._slerping = false;
  78500. this._firstFrameSkipped = false;
  78501. this._fowardAxis = BABYLON.Vector3.Forward();
  78502. this.mesh = mesh;
  78503. this.bone = bone;
  78504. this.target = target;
  78505. if (options) {
  78506. if (options.adjustYaw) {
  78507. this.adjustYaw = options.adjustYaw;
  78508. }
  78509. if (options.adjustPitch) {
  78510. this.adjustPitch = options.adjustPitch;
  78511. }
  78512. if (options.adjustRoll) {
  78513. this.adjustRoll = options.adjustRoll;
  78514. }
  78515. if (options.maxYaw != null) {
  78516. this.maxYaw = options.maxYaw;
  78517. }
  78518. else {
  78519. this.maxYaw = Math.PI;
  78520. }
  78521. if (options.minYaw != null) {
  78522. this.minYaw = options.minYaw;
  78523. }
  78524. else {
  78525. this.minYaw = -Math.PI;
  78526. }
  78527. if (options.maxPitch != null) {
  78528. this.maxPitch = options.maxPitch;
  78529. }
  78530. else {
  78531. this.maxPitch = Math.PI;
  78532. }
  78533. if (options.minPitch != null) {
  78534. this.minPitch = options.minPitch;
  78535. }
  78536. else {
  78537. this.minPitch = -Math.PI;
  78538. }
  78539. if (options.slerpAmount != null) {
  78540. this.slerpAmount = options.slerpAmount;
  78541. }
  78542. if (options.upAxis != null) {
  78543. this.upAxis = options.upAxis;
  78544. }
  78545. if (options.upAxisSpace != null) {
  78546. this.upAxisSpace = options.upAxisSpace;
  78547. }
  78548. if (options.yawAxis != null || options.pitchAxis != null) {
  78549. var newYawAxis = BABYLON.Axis.Y;
  78550. var newPitchAxis = BABYLON.Axis.X;
  78551. if (options.yawAxis != null) {
  78552. newYawAxis = options.yawAxis.clone();
  78553. newYawAxis.normalize();
  78554. }
  78555. if (options.pitchAxis != null) {
  78556. newPitchAxis = options.pitchAxis.clone();
  78557. newPitchAxis.normalize();
  78558. }
  78559. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78560. this._transformYawPitch = BABYLON.Matrix.Identity();
  78561. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78562. this._transformYawPitchInv = this._transformYawPitch.clone();
  78563. this._transformYawPitch.invert();
  78564. }
  78565. }
  78566. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78567. this.upAxisSpace = BABYLON.Space.LOCAL;
  78568. }
  78569. }
  78570. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78571. /**
  78572. * Gets or sets the minimum yaw angle that the bone can look to
  78573. */
  78574. get: function () {
  78575. return this._minYaw;
  78576. },
  78577. set: function (value) {
  78578. this._minYaw = value;
  78579. this._minYawSin = Math.sin(value);
  78580. this._minYawCos = Math.cos(value);
  78581. if (this._maxYaw != null) {
  78582. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78583. this._yawRange = this._maxYaw - this._minYaw;
  78584. }
  78585. },
  78586. enumerable: true,
  78587. configurable: true
  78588. });
  78589. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78590. /**
  78591. * Gets or sets the maximum yaw angle that the bone can look to
  78592. */
  78593. get: function () {
  78594. return this._maxYaw;
  78595. },
  78596. set: function (value) {
  78597. this._maxYaw = value;
  78598. this._maxYawSin = Math.sin(value);
  78599. this._maxYawCos = Math.cos(value);
  78600. if (this._minYaw != null) {
  78601. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78602. this._yawRange = this._maxYaw - this._minYaw;
  78603. }
  78604. },
  78605. enumerable: true,
  78606. configurable: true
  78607. });
  78608. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78609. /**
  78610. * Gets or sets the minimum pitch angle that the bone can look to
  78611. */
  78612. get: function () {
  78613. return this._minPitch;
  78614. },
  78615. set: function (value) {
  78616. this._minPitch = value;
  78617. this._minPitchTan = Math.tan(value);
  78618. },
  78619. enumerable: true,
  78620. configurable: true
  78621. });
  78622. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78623. /**
  78624. * Gets or sets the maximum pitch angle that the bone can look to
  78625. */
  78626. get: function () {
  78627. return this._maxPitch;
  78628. },
  78629. set: function (value) {
  78630. this._maxPitch = value;
  78631. this._maxPitchTan = Math.tan(value);
  78632. },
  78633. enumerable: true,
  78634. configurable: true
  78635. });
  78636. /**
  78637. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78638. */
  78639. BoneLookController.prototype.update = function () {
  78640. //skip the first frame when slerping so that the mesh rotation is correct
  78641. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78642. this._firstFrameSkipped = true;
  78643. return;
  78644. }
  78645. var bone = this.bone;
  78646. var bonePos = BoneLookController._tmpVecs[0];
  78647. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78648. var target = this.target;
  78649. var _tmpMat1 = BoneLookController._tmpMats[0];
  78650. var _tmpMat2 = BoneLookController._tmpMats[1];
  78651. var mesh = this.mesh;
  78652. var parentBone = bone.getParent();
  78653. var upAxis = BoneLookController._tmpVecs[1];
  78654. upAxis.copyFrom(this.upAxis);
  78655. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78656. if (this._transformYawPitch) {
  78657. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78658. }
  78659. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78660. }
  78661. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78662. mesh.getDirectionToRef(upAxis, upAxis);
  78663. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78664. upAxis.normalize();
  78665. }
  78666. }
  78667. var checkYaw = false;
  78668. var checkPitch = false;
  78669. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78670. checkYaw = true;
  78671. }
  78672. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78673. checkPitch = true;
  78674. }
  78675. if (checkYaw || checkPitch) {
  78676. var spaceMat = BoneLookController._tmpMats[2];
  78677. var spaceMatInv = BoneLookController._tmpMats[3];
  78678. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78679. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78680. }
  78681. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78682. spaceMat.copyFrom(mesh.getWorldMatrix());
  78683. }
  78684. else {
  78685. var forwardAxis = BoneLookController._tmpVecs[2];
  78686. forwardAxis.copyFrom(this._fowardAxis);
  78687. if (this._transformYawPitch) {
  78688. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78689. }
  78690. if (parentBone) {
  78691. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78692. }
  78693. else {
  78694. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78695. }
  78696. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78697. rightAxis.normalize();
  78698. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78699. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78700. }
  78701. spaceMat.invertToRef(spaceMatInv);
  78702. var xzlen = null;
  78703. if (checkPitch) {
  78704. var localTarget = BoneLookController._tmpVecs[3];
  78705. target.subtractToRef(bonePos, localTarget);
  78706. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78707. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78708. var pitch = Math.atan2(localTarget.y, xzlen);
  78709. var newPitch = pitch;
  78710. if (pitch > this._maxPitch) {
  78711. localTarget.y = this._maxPitchTan * xzlen;
  78712. newPitch = this._maxPitch;
  78713. }
  78714. else if (pitch < this._minPitch) {
  78715. localTarget.y = this._minPitchTan * xzlen;
  78716. newPitch = this._minPitch;
  78717. }
  78718. if (pitch != newPitch) {
  78719. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78720. localTarget.addInPlace(bonePos);
  78721. target = localTarget;
  78722. }
  78723. }
  78724. if (checkYaw) {
  78725. var localTarget = BoneLookController._tmpVecs[4];
  78726. target.subtractToRef(bonePos, localTarget);
  78727. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78728. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78729. var newYaw = yaw;
  78730. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78731. if (xzlen == null) {
  78732. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78733. }
  78734. if (this._yawRange > Math.PI) {
  78735. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78736. localTarget.z = this._maxYawCos * xzlen;
  78737. localTarget.x = this._maxYawSin * xzlen;
  78738. newYaw = this._maxYaw;
  78739. }
  78740. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78741. localTarget.z = this._minYawCos * xzlen;
  78742. localTarget.x = this._minYawSin * xzlen;
  78743. newYaw = this._minYaw;
  78744. }
  78745. }
  78746. else {
  78747. if (yaw > this._maxYaw) {
  78748. localTarget.z = this._maxYawCos * xzlen;
  78749. localTarget.x = this._maxYawSin * xzlen;
  78750. newYaw = this._maxYaw;
  78751. }
  78752. else if (yaw < this._minYaw) {
  78753. localTarget.z = this._minYawCos * xzlen;
  78754. localTarget.x = this._minYawSin * xzlen;
  78755. newYaw = this._minYaw;
  78756. }
  78757. }
  78758. }
  78759. if (this._slerping && this._yawRange > Math.PI) {
  78760. //are we going to be crossing into the min/max region?
  78761. var boneFwd = BoneLookController._tmpVecs[8];
  78762. boneFwd.copyFrom(BABYLON.Axis.Z);
  78763. if (this._transformYawPitch) {
  78764. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78765. }
  78766. var boneRotMat = BoneLookController._tmpMats[4];
  78767. this._boneQuat.toRotationMatrix(boneRotMat);
  78768. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78769. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78770. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78771. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78772. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78773. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78774. if (angBtwTar > angBtwMidYaw) {
  78775. if (xzlen == null) {
  78776. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78777. }
  78778. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78779. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78780. if (angBtwMin < angBtwMax) {
  78781. newYaw = boneYaw + Math.PI * .75;
  78782. localTarget.z = Math.cos(newYaw) * xzlen;
  78783. localTarget.x = Math.sin(newYaw) * xzlen;
  78784. }
  78785. else {
  78786. newYaw = boneYaw - Math.PI * .75;
  78787. localTarget.z = Math.cos(newYaw) * xzlen;
  78788. localTarget.x = Math.sin(newYaw) * xzlen;
  78789. }
  78790. }
  78791. }
  78792. if (yaw != newYaw) {
  78793. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78794. localTarget.addInPlace(bonePos);
  78795. target = localTarget;
  78796. }
  78797. }
  78798. }
  78799. var zaxis = BoneLookController._tmpVecs[5];
  78800. var xaxis = BoneLookController._tmpVecs[6];
  78801. var yaxis = BoneLookController._tmpVecs[7];
  78802. var _tmpQuat = BoneLookController._tmpQuat;
  78803. target.subtractToRef(bonePos, zaxis);
  78804. zaxis.normalize();
  78805. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78806. xaxis.normalize();
  78807. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78808. yaxis.normalize();
  78809. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78810. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78811. return;
  78812. }
  78813. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78814. return;
  78815. }
  78816. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78817. return;
  78818. }
  78819. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78820. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78821. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78822. }
  78823. if (this.slerpAmount < 1) {
  78824. if (!this._slerping) {
  78825. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78826. }
  78827. if (this._transformYawPitch) {
  78828. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78829. }
  78830. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78831. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78832. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78833. this._slerping = true;
  78834. }
  78835. else {
  78836. if (this._transformYawPitch) {
  78837. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78838. }
  78839. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78840. this._slerping = false;
  78841. }
  78842. };
  78843. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78844. var angDiff = ang2 - ang1;
  78845. angDiff %= Math.PI * 2;
  78846. if (angDiff > Math.PI) {
  78847. angDiff -= Math.PI * 2;
  78848. }
  78849. else if (angDiff < -Math.PI) {
  78850. angDiff += Math.PI * 2;
  78851. }
  78852. return angDiff;
  78853. };
  78854. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78855. ang1 %= (2 * Math.PI);
  78856. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78857. ang2 %= (2 * Math.PI);
  78858. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78859. var ab = 0;
  78860. if (ang1 < ang2) {
  78861. ab = ang2 - ang1;
  78862. }
  78863. else {
  78864. ab = ang1 - ang2;
  78865. }
  78866. if (ab > Math.PI) {
  78867. ab = Math.PI * 2 - ab;
  78868. }
  78869. return ab;
  78870. };
  78871. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78872. ang %= (2 * Math.PI);
  78873. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78874. ang1 %= (2 * Math.PI);
  78875. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78876. ang2 %= (2 * Math.PI);
  78877. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78878. if (ang1 < ang2) {
  78879. if (ang > ang1 && ang < ang2) {
  78880. return true;
  78881. }
  78882. }
  78883. else {
  78884. if (ang > ang2 && ang < ang1) {
  78885. return true;
  78886. }
  78887. }
  78888. return false;
  78889. };
  78890. 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()];
  78891. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78892. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78893. return BoneLookController;
  78894. }());
  78895. BABYLON.BoneLookController = BoneLookController;
  78896. })(BABYLON || (BABYLON = {}));
  78897. //# sourceMappingURL=babylon.boneLookController.js.map
  78898. var BABYLON;
  78899. (function (BABYLON) {
  78900. /**
  78901. * Class used to handle skinning animations
  78902. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78903. */
  78904. var Skeleton = /** @class */ (function () {
  78905. /**
  78906. * Creates a new skeleton
  78907. * @param name defines the skeleton name
  78908. * @param id defines the skeleton Id
  78909. * @param scene defines the hosting scene
  78910. */
  78911. function Skeleton(
  78912. /** defines the skeleton name */
  78913. name,
  78914. /** defines the skeleton Id */
  78915. id, scene) {
  78916. this.name = name;
  78917. this.id = id;
  78918. /**
  78919. * Gets the list of child bones
  78920. */
  78921. this.bones = new Array();
  78922. /**
  78923. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78924. */
  78925. this.needInitialSkinMatrix = false;
  78926. this._isDirty = true;
  78927. this._meshesWithPoseMatrix = new Array();
  78928. this._identity = BABYLON.Matrix.Identity();
  78929. this._ranges = {};
  78930. this._lastAbsoluteTransformsUpdateId = -1;
  78931. /**
  78932. * Specifies if the skeleton should be serialized
  78933. */
  78934. this.doNotSerialize = false;
  78935. this._animationPropertiesOverride = null;
  78936. // Events
  78937. /**
  78938. * An observable triggered before computing the skeleton's matrices
  78939. */
  78940. this.onBeforeComputeObservable = new BABYLON.Observable();
  78941. this.bones = [];
  78942. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78943. scene.skeletons.push(this);
  78944. //make sure it will recalculate the matrix next time prepare is called.
  78945. this._isDirty = true;
  78946. }
  78947. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78948. /**
  78949. * Gets or sets the animation properties override
  78950. */
  78951. get: function () {
  78952. if (!this._animationPropertiesOverride) {
  78953. return this._scene.animationPropertiesOverride;
  78954. }
  78955. return this._animationPropertiesOverride;
  78956. },
  78957. set: function (value) {
  78958. this._animationPropertiesOverride = value;
  78959. },
  78960. enumerable: true,
  78961. configurable: true
  78962. });
  78963. // Members
  78964. /**
  78965. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  78966. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  78967. * @returns a Float32Array containing matrices data
  78968. */
  78969. Skeleton.prototype.getTransformMatrices = function (mesh) {
  78970. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  78971. return mesh._bonesTransformMatrices;
  78972. }
  78973. if (!this._transformMatrices) {
  78974. this.prepare();
  78975. }
  78976. return this._transformMatrices;
  78977. };
  78978. /**
  78979. * Gets the current hosting scene
  78980. * @returns a scene object
  78981. */
  78982. Skeleton.prototype.getScene = function () {
  78983. return this._scene;
  78984. };
  78985. // Methods
  78986. /**
  78987. * Gets a string representing the current skeleton data
  78988. * @param fullDetails defines a boolean indicating if we want a verbose version
  78989. * @returns a string representing the current skeleton data
  78990. */
  78991. Skeleton.prototype.toString = function (fullDetails) {
  78992. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  78993. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  78994. if (fullDetails) {
  78995. ret += ", Ranges: {";
  78996. var first = true;
  78997. for (var name_1 in this._ranges) {
  78998. if (first) {
  78999. ret += ", ";
  79000. first = false;
  79001. }
  79002. ret += name_1;
  79003. }
  79004. ret += "}";
  79005. }
  79006. return ret;
  79007. };
  79008. /**
  79009. * Get bone's index searching by name
  79010. * @param name defines bone's name to search for
  79011. * @return the indice of the bone. Returns -1 if not found
  79012. */
  79013. Skeleton.prototype.getBoneIndexByName = function (name) {
  79014. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79015. if (this.bones[boneIndex].name === name) {
  79016. return boneIndex;
  79017. }
  79018. }
  79019. return -1;
  79020. };
  79021. /**
  79022. * Creater a new animation range
  79023. * @param name defines the name of the range
  79024. * @param from defines the start key
  79025. * @param to defines the end key
  79026. */
  79027. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79028. // check name not already in use
  79029. if (!this._ranges[name]) {
  79030. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79031. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79032. if (this.bones[i].animations[0]) {
  79033. this.bones[i].animations[0].createRange(name, from, to);
  79034. }
  79035. }
  79036. }
  79037. };
  79038. /**
  79039. * Delete a specific animation range
  79040. * @param name defines the name of the range
  79041. * @param deleteFrames defines if frames must be removed as well
  79042. */
  79043. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79044. if (deleteFrames === void 0) { deleteFrames = true; }
  79045. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79046. if (this.bones[i].animations[0]) {
  79047. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79048. }
  79049. }
  79050. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79051. };
  79052. /**
  79053. * Gets a specific animation range
  79054. * @param name defines the name of the range to look for
  79055. * @returns the requested animation range or null if not found
  79056. */
  79057. Skeleton.prototype.getAnimationRange = function (name) {
  79058. return this._ranges[name];
  79059. };
  79060. /**
  79061. * Gets the list of all animation ranges defined on this skeleton
  79062. * @returns an array
  79063. */
  79064. Skeleton.prototype.getAnimationRanges = function () {
  79065. var animationRanges = [];
  79066. var name;
  79067. var i = 0;
  79068. for (name in this._ranges) {
  79069. animationRanges[i] = this._ranges[name];
  79070. i++;
  79071. }
  79072. return animationRanges;
  79073. };
  79074. /**
  79075. * Copy animation range from a source skeleton.
  79076. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79077. * @param source defines the source skeleton
  79078. * @param name defines the name of the range to copy
  79079. * @param rescaleAsRequired defines if rescaling must be applied if required
  79080. * @returns true if operation was successful
  79081. */
  79082. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79083. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79084. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79085. return false;
  79086. }
  79087. var ret = true;
  79088. var frameOffset = this._getHighestAnimationFrame() + 1;
  79089. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79090. var boneDict = {};
  79091. var sourceBones = source.bones;
  79092. var nBones;
  79093. var i;
  79094. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79095. boneDict[sourceBones[i].name] = sourceBones[i];
  79096. }
  79097. if (this.bones.length !== sourceBones.length) {
  79098. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79099. ret = false;
  79100. }
  79101. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79102. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79103. var boneName = this.bones[i].name;
  79104. var sourceBone = boneDict[boneName];
  79105. if (sourceBone) {
  79106. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79107. }
  79108. else {
  79109. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79110. ret = false;
  79111. }
  79112. }
  79113. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79114. var range = source.getAnimationRange(name);
  79115. if (range) {
  79116. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79117. }
  79118. return ret;
  79119. };
  79120. /**
  79121. * Forces the skeleton to go to rest pose
  79122. */
  79123. Skeleton.prototype.returnToRest = function () {
  79124. for (var index = 0; index < this.bones.length; index++) {
  79125. this.bones[index].returnToRest();
  79126. }
  79127. };
  79128. Skeleton.prototype._getHighestAnimationFrame = function () {
  79129. var ret = 0;
  79130. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79131. if (this.bones[i].animations[0]) {
  79132. var highest = this.bones[i].animations[0].getHighestFrame();
  79133. if (ret < highest) {
  79134. ret = highest;
  79135. }
  79136. }
  79137. }
  79138. return ret;
  79139. };
  79140. /**
  79141. * Begin a specific animation range
  79142. * @param name defines the name of the range to start
  79143. * @param loop defines if looping must be turned on (false by default)
  79144. * @param speedRatio defines the speed ratio to apply (1 by default)
  79145. * @param onAnimationEnd defines a callback which will be called when animation will end
  79146. * @returns a new animatable
  79147. */
  79148. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79149. var range = this.getAnimationRange(name);
  79150. if (!range) {
  79151. return null;
  79152. }
  79153. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79154. };
  79155. /** @hidden */
  79156. Skeleton.prototype._markAsDirty = function () {
  79157. this._isDirty = true;
  79158. };
  79159. /** @hidden */
  79160. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79161. this._meshesWithPoseMatrix.push(mesh);
  79162. };
  79163. /** @hidden */
  79164. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79165. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79166. if (index > -1) {
  79167. this._meshesWithPoseMatrix.splice(index, 1);
  79168. }
  79169. };
  79170. /** @hidden */
  79171. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79172. this.onBeforeComputeObservable.notifyObservers(this);
  79173. for (var index = 0; index < this.bones.length; index++) {
  79174. var bone = this.bones[index];
  79175. var parentBone = bone.getParent();
  79176. if (parentBone) {
  79177. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79178. }
  79179. else {
  79180. if (initialSkinMatrix) {
  79181. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79182. }
  79183. else {
  79184. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79185. }
  79186. }
  79187. if (bone._index !== -1) {
  79188. var mappedIndex = bone._index === null ? index : bone._index;
  79189. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79190. }
  79191. }
  79192. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79193. };
  79194. /**
  79195. * Build all resources required to render a skeleton
  79196. */
  79197. Skeleton.prototype.prepare = function () {
  79198. if (!this._isDirty) {
  79199. return;
  79200. }
  79201. if (this.needInitialSkinMatrix) {
  79202. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79203. var mesh = this._meshesWithPoseMatrix[index];
  79204. var poseMatrix = mesh.getPoseMatrix();
  79205. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79206. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79207. }
  79208. if (this._synchronizedWithMesh !== mesh) {
  79209. this._synchronizedWithMesh = mesh;
  79210. // Prepare bones
  79211. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79212. var bone = this.bones[boneIndex];
  79213. if (!bone.getParent()) {
  79214. var matrix = bone.getBaseMatrix();
  79215. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79216. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79217. }
  79218. }
  79219. }
  79220. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79221. }
  79222. }
  79223. else {
  79224. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79225. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79226. }
  79227. this._computeTransformMatrices(this._transformMatrices, null);
  79228. }
  79229. this._isDirty = false;
  79230. this._scene._activeBones.addCount(this.bones.length, false);
  79231. };
  79232. /**
  79233. * Gets the list of animatables currently running for this skeleton
  79234. * @returns an array of animatables
  79235. */
  79236. Skeleton.prototype.getAnimatables = function () {
  79237. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79238. this._animatables = [];
  79239. for (var index = 0; index < this.bones.length; index++) {
  79240. this._animatables.push(this.bones[index]);
  79241. }
  79242. }
  79243. return this._animatables;
  79244. };
  79245. /**
  79246. * Clone the current skeleton
  79247. * @param name defines the name of the new skeleton
  79248. * @param id defines the id of the enw skeleton
  79249. * @returns the new skeleton
  79250. */
  79251. Skeleton.prototype.clone = function (name, id) {
  79252. var result = new Skeleton(name, id || name, this._scene);
  79253. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79254. for (var index = 0; index < this.bones.length; index++) {
  79255. var source = this.bones[index];
  79256. var parentBone = null;
  79257. var parent_1 = source.getParent();
  79258. if (parent_1) {
  79259. var parentIndex = this.bones.indexOf(parent_1);
  79260. parentBone = result.bones[parentIndex];
  79261. }
  79262. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79263. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79264. }
  79265. if (this._ranges) {
  79266. result._ranges = {};
  79267. for (var rangeName in this._ranges) {
  79268. var range = this._ranges[rangeName];
  79269. if (range) {
  79270. result._ranges[rangeName] = range.clone();
  79271. }
  79272. }
  79273. }
  79274. this._isDirty = true;
  79275. return result;
  79276. };
  79277. /**
  79278. * Enable animation blending for this skeleton
  79279. * @param blendingSpeed defines the blending speed to apply
  79280. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79281. */
  79282. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79283. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79284. this.bones.forEach(function (bone) {
  79285. bone.animations.forEach(function (animation) {
  79286. animation.enableBlending = true;
  79287. animation.blendingSpeed = blendingSpeed;
  79288. });
  79289. });
  79290. };
  79291. /**
  79292. * Releases all resources associated with the current skeleton
  79293. */
  79294. Skeleton.prototype.dispose = function () {
  79295. this._meshesWithPoseMatrix = [];
  79296. // Animations
  79297. this.getScene().stopAnimation(this);
  79298. // Remove from scene
  79299. this.getScene().removeSkeleton(this);
  79300. };
  79301. /**
  79302. * Serialize the skeleton in a JSON object
  79303. * @returns a JSON object
  79304. */
  79305. Skeleton.prototype.serialize = function () {
  79306. var serializationObject = {};
  79307. serializationObject.name = this.name;
  79308. serializationObject.id = this.id;
  79309. if (this.dimensionsAtRest) {
  79310. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79311. }
  79312. serializationObject.bones = [];
  79313. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79314. for (var index = 0; index < this.bones.length; index++) {
  79315. var bone = this.bones[index];
  79316. var parent_2 = bone.getParent();
  79317. var serializedBone = {
  79318. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79319. name: bone.name,
  79320. matrix: bone.getBaseMatrix().toArray(),
  79321. rest: bone.getRestPose().toArray()
  79322. };
  79323. serializationObject.bones.push(serializedBone);
  79324. if (bone.length) {
  79325. serializedBone.length = bone.length;
  79326. }
  79327. if (bone.animations && bone.animations.length > 0) {
  79328. serializedBone.animation = bone.animations[0].serialize();
  79329. }
  79330. serializationObject.ranges = [];
  79331. for (var name in this._ranges) {
  79332. var source = this._ranges[name];
  79333. if (!source) {
  79334. continue;
  79335. }
  79336. var range = {};
  79337. range.name = name;
  79338. range.from = source.from;
  79339. range.to = source.to;
  79340. serializationObject.ranges.push(range);
  79341. }
  79342. }
  79343. return serializationObject;
  79344. };
  79345. /**
  79346. * Creates a new skeleton from serialized data
  79347. * @param parsedSkeleton defines the serialized data
  79348. * @param scene defines the hosting scene
  79349. * @returns a new skeleton
  79350. */
  79351. Skeleton.Parse = function (parsedSkeleton, scene) {
  79352. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79353. if (parsedSkeleton.dimensionsAtRest) {
  79354. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79355. }
  79356. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79357. var index;
  79358. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79359. var parsedBone = parsedSkeleton.bones[index];
  79360. var parentBone = null;
  79361. if (parsedBone.parentBoneIndex > -1) {
  79362. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79363. }
  79364. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79365. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79366. if (parsedBone.length) {
  79367. bone.length = parsedBone.length;
  79368. }
  79369. if (parsedBone.animation) {
  79370. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79371. }
  79372. }
  79373. // placed after bones, so createAnimationRange can cascade down
  79374. if (parsedSkeleton.ranges) {
  79375. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79376. var data = parsedSkeleton.ranges[index];
  79377. skeleton.createAnimationRange(data.name, data.from, data.to);
  79378. }
  79379. }
  79380. return skeleton;
  79381. };
  79382. /**
  79383. * Compute all node absolute transforms
  79384. * @param forceUpdate defines if computation must be done even if cache is up to date
  79385. */
  79386. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79387. if (forceUpdate === void 0) { forceUpdate = false; }
  79388. var renderId = this._scene.getRenderId();
  79389. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79390. this.bones[0].computeAbsoluteTransforms();
  79391. this._lastAbsoluteTransformsUpdateId = renderId;
  79392. }
  79393. };
  79394. /**
  79395. * Gets the root pose matrix
  79396. * @returns a matrix
  79397. */
  79398. Skeleton.prototype.getPoseMatrix = function () {
  79399. var poseMatrix = null;
  79400. if (this._meshesWithPoseMatrix.length > 0) {
  79401. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79402. }
  79403. return poseMatrix;
  79404. };
  79405. /**
  79406. * Sorts bones per internal index
  79407. */
  79408. Skeleton.prototype.sortBones = function () {
  79409. var bones = new Array();
  79410. var visited = new Array(this.bones.length);
  79411. for (var index = 0; index < this.bones.length; index++) {
  79412. this._sortBones(index, bones, visited);
  79413. }
  79414. this.bones = bones;
  79415. };
  79416. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79417. if (visited[index]) {
  79418. return;
  79419. }
  79420. visited[index] = true;
  79421. var bone = this.bones[index];
  79422. if (bone._index === undefined) {
  79423. bone._index = index;
  79424. }
  79425. var parentBone = bone.getParent();
  79426. if (parentBone) {
  79427. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79428. }
  79429. bones.push(bone);
  79430. };
  79431. return Skeleton;
  79432. }());
  79433. BABYLON.Skeleton = Skeleton;
  79434. })(BABYLON || (BABYLON = {}));
  79435. //# sourceMappingURL=babylon.skeleton.js.map
  79436. var BABYLON;
  79437. (function (BABYLON) {
  79438. var SphericalPolynomial = /** @class */ (function () {
  79439. function SphericalPolynomial() {
  79440. this.x = BABYLON.Vector3.Zero();
  79441. this.y = BABYLON.Vector3.Zero();
  79442. this.z = BABYLON.Vector3.Zero();
  79443. this.xx = BABYLON.Vector3.Zero();
  79444. this.yy = BABYLON.Vector3.Zero();
  79445. this.zz = BABYLON.Vector3.Zero();
  79446. this.xy = BABYLON.Vector3.Zero();
  79447. this.yz = BABYLON.Vector3.Zero();
  79448. this.zx = BABYLON.Vector3.Zero();
  79449. }
  79450. SphericalPolynomial.prototype.addAmbient = function (color) {
  79451. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79452. this.xx = this.xx.add(colorVector);
  79453. this.yy = this.yy.add(colorVector);
  79454. this.zz = this.zz.add(colorVector);
  79455. };
  79456. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79457. var result = new SphericalPolynomial();
  79458. result.x = harmonics.L11.scale(1.02333);
  79459. result.y = harmonics.L1_1.scale(1.02333);
  79460. result.z = harmonics.L10.scale(1.02333);
  79461. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79462. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79463. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79464. result.yz = harmonics.L2_1.scale(0.858086);
  79465. result.zx = harmonics.L21.scale(0.858086);
  79466. result.xy = harmonics.L2_2.scale(0.858086);
  79467. result.scale(1.0 / Math.PI);
  79468. return result;
  79469. };
  79470. SphericalPolynomial.prototype.scale = function (scale) {
  79471. this.x = this.x.scale(scale);
  79472. this.y = this.y.scale(scale);
  79473. this.z = this.z.scale(scale);
  79474. this.xx = this.xx.scale(scale);
  79475. this.yy = this.yy.scale(scale);
  79476. this.zz = this.zz.scale(scale);
  79477. this.yz = this.yz.scale(scale);
  79478. this.zx = this.zx.scale(scale);
  79479. this.xy = this.xy.scale(scale);
  79480. };
  79481. return SphericalPolynomial;
  79482. }());
  79483. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79484. var SphericalHarmonics = /** @class */ (function () {
  79485. function SphericalHarmonics() {
  79486. this.L00 = BABYLON.Vector3.Zero();
  79487. this.L1_1 = BABYLON.Vector3.Zero();
  79488. this.L10 = BABYLON.Vector3.Zero();
  79489. this.L11 = BABYLON.Vector3.Zero();
  79490. this.L2_2 = BABYLON.Vector3.Zero();
  79491. this.L2_1 = BABYLON.Vector3.Zero();
  79492. this.L20 = BABYLON.Vector3.Zero();
  79493. this.L21 = BABYLON.Vector3.Zero();
  79494. this.L22 = BABYLON.Vector3.Zero();
  79495. }
  79496. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79497. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79498. var c = colorVector.scale(deltaSolidAngle);
  79499. this.L00 = this.L00.add(c.scale(0.282095));
  79500. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79501. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79502. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79503. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79504. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79505. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79506. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79507. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79508. };
  79509. SphericalHarmonics.prototype.scale = function (scale) {
  79510. this.L00 = this.L00.scale(scale);
  79511. this.L1_1 = this.L1_1.scale(scale);
  79512. this.L10 = this.L10.scale(scale);
  79513. this.L11 = this.L11.scale(scale);
  79514. this.L2_2 = this.L2_2.scale(scale);
  79515. this.L2_1 = this.L2_1.scale(scale);
  79516. this.L20 = this.L20.scale(scale);
  79517. this.L21 = this.L21.scale(scale);
  79518. this.L22 = this.L22.scale(scale);
  79519. };
  79520. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79521. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79522. //
  79523. // E_lm = A_l * L_lm
  79524. //
  79525. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79526. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79527. // the scaling factors are given in equation 9.
  79528. // Constant (Band 0)
  79529. this.L00 = this.L00.scale(3.141593);
  79530. // Linear (Band 1)
  79531. this.L1_1 = this.L1_1.scale(2.094395);
  79532. this.L10 = this.L10.scale(2.094395);
  79533. this.L11 = this.L11.scale(2.094395);
  79534. // Quadratic (Band 2)
  79535. this.L2_2 = this.L2_2.scale(0.785398);
  79536. this.L2_1 = this.L2_1.scale(0.785398);
  79537. this.L20 = this.L20.scale(0.785398);
  79538. this.L21 = this.L21.scale(0.785398);
  79539. this.L22 = this.L22.scale(0.785398);
  79540. };
  79541. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79542. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79543. // L = (1/pi) * E * rho
  79544. //
  79545. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79546. this.scale(1.0 / Math.PI);
  79547. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79548. // (The pixel shader must apply albedo after texture fetches, etc).
  79549. };
  79550. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79551. var result = new SphericalHarmonics();
  79552. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79553. result.L1_1 = polynomial.y.scale(0.977204);
  79554. result.L10 = polynomial.z.scale(0.977204);
  79555. result.L11 = polynomial.x.scale(0.977204);
  79556. result.L2_2 = polynomial.xy.scale(1.16538);
  79557. result.L2_1 = polynomial.yz.scale(1.16538);
  79558. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79559. result.L21 = polynomial.zx.scale(1.16538);
  79560. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79561. result.scale(Math.PI);
  79562. return result;
  79563. };
  79564. return SphericalHarmonics;
  79565. }());
  79566. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79567. })(BABYLON || (BABYLON = {}));
  79568. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79569. var BABYLON;
  79570. (function (BABYLON) {
  79571. var FileFaceOrientation = /** @class */ (function () {
  79572. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79573. this.name = name;
  79574. this.worldAxisForNormal = worldAxisForNormal;
  79575. this.worldAxisForFileX = worldAxisForFileX;
  79576. this.worldAxisForFileY = worldAxisForFileY;
  79577. }
  79578. return FileFaceOrientation;
  79579. }());
  79580. ;
  79581. /**
  79582. * Helper class dealing with the extraction of spherical polynomial dataArray
  79583. * from a cube map.
  79584. */
  79585. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79586. function CubeMapToSphericalPolynomialTools() {
  79587. }
  79588. /**
  79589. * Converts a texture to the according Spherical Polynomial data.
  79590. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79591. *
  79592. * @param texture The texture to extract the information from.
  79593. * @return The Spherical Polynomial data.
  79594. */
  79595. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79596. if (!texture.isCube) {
  79597. // Only supports cube Textures currently.
  79598. return null;
  79599. }
  79600. var size = texture.getSize().width;
  79601. var right = texture.readPixels(0);
  79602. var left = texture.readPixels(1);
  79603. var up;
  79604. var down;
  79605. if (texture.isRenderTarget) {
  79606. up = texture.readPixels(3);
  79607. down = texture.readPixels(2);
  79608. }
  79609. else {
  79610. up = texture.readPixels(2);
  79611. down = texture.readPixels(3);
  79612. }
  79613. var front = texture.readPixels(4);
  79614. var back = texture.readPixels(5);
  79615. var gammaSpace = texture.gammaSpace;
  79616. // Always read as RGBA.
  79617. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79618. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79619. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79620. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79621. }
  79622. var cubeInfo = {
  79623. size: size,
  79624. right: right,
  79625. left: left,
  79626. up: up,
  79627. down: down,
  79628. front: front,
  79629. back: back,
  79630. format: format,
  79631. type: type,
  79632. gammaSpace: gammaSpace,
  79633. };
  79634. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79635. };
  79636. /**
  79637. * Converts a cubemap to the according Spherical Polynomial data.
  79638. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79639. *
  79640. * @param cubeInfo The Cube map to extract the information from.
  79641. * @return The Spherical Polynomial data.
  79642. */
  79643. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79644. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79645. var totalSolidAngle = 0.0;
  79646. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79647. var du = 2.0 / cubeInfo.size;
  79648. var dv = du;
  79649. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79650. var minUV = du * 0.5 - 1.0;
  79651. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79652. var fileFace = this.FileFaces[faceIndex];
  79653. var dataArray = cubeInfo[fileFace.name];
  79654. var v = minUV;
  79655. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79656. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79657. // Because SP is still linear, so summation is fine in that basis.
  79658. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79659. for (var y = 0; y < cubeInfo.size; y++) {
  79660. var u = minUV;
  79661. for (var x = 0; x < cubeInfo.size; x++) {
  79662. // World direction (not normalised)
  79663. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79664. worldDirection.normalize();
  79665. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79666. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79667. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79668. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79669. // Handle Integer types.
  79670. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79671. r /= 255;
  79672. g /= 255;
  79673. b /= 255;
  79674. }
  79675. // Handle Gamma space textures.
  79676. if (cubeInfo.gammaSpace) {
  79677. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79678. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79679. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79680. }
  79681. var color = new BABYLON.Color3(r, g, b);
  79682. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79683. totalSolidAngle += deltaSolidAngle;
  79684. u += du;
  79685. }
  79686. v += dv;
  79687. }
  79688. }
  79689. // Solid angle for entire sphere is 4*pi
  79690. var sphereSolidAngle = 4.0 * Math.PI;
  79691. // Adjust the solid angle to allow for how many faces we processed.
  79692. var facesProcessed = 6.0;
  79693. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79694. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79695. // This is needed because the numerical integration over the cube uses a
  79696. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79697. // and also to compensate for accumulative error due to float precision in the summation.
  79698. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79699. sphericalHarmonics.scale(correctionFactor);
  79700. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79701. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79702. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79703. };
  79704. CubeMapToSphericalPolynomialTools.FileFaces = [
  79705. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79706. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79707. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79708. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79709. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79710. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79711. ];
  79712. return CubeMapToSphericalPolynomialTools;
  79713. }());
  79714. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79715. })(BABYLON || (BABYLON = {}));
  79716. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79717. var BABYLON;
  79718. (function (BABYLON) {
  79719. /**
  79720. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79721. */
  79722. var PanoramaToCubeMapTools = /** @class */ (function () {
  79723. function PanoramaToCubeMapTools() {
  79724. }
  79725. /**
  79726. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79727. *
  79728. * @param float32Array The source data.
  79729. * @param inputWidth The width of the input panorama.
  79730. * @param inputhHeight The height of the input panorama.
  79731. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79732. * @return The cubemap data
  79733. */
  79734. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79735. if (!float32Array) {
  79736. throw "ConvertPanoramaToCubemap: input cannot be null";
  79737. }
  79738. if (float32Array.length != inputWidth * inputHeight * 3) {
  79739. throw "ConvertPanoramaToCubemap: input size is wrong";
  79740. }
  79741. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79742. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79743. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79744. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79745. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79746. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79747. return {
  79748. front: textureFront,
  79749. back: textureBack,
  79750. left: textureLeft,
  79751. right: textureRight,
  79752. up: textureUp,
  79753. down: textureDown,
  79754. size: size,
  79755. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79756. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79757. gammaSpace: false,
  79758. };
  79759. };
  79760. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79761. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79762. var textureArray = new Float32Array(buffer);
  79763. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79764. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79765. var dy = 1 / texSize;
  79766. var fy = 0;
  79767. for (var y = 0; y < texSize; y++) {
  79768. var xv1 = faceData[0];
  79769. var xv2 = faceData[2];
  79770. for (var x = 0; x < texSize; x++) {
  79771. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79772. v.normalize();
  79773. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79774. // 3 channels per pixels
  79775. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79776. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79777. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79778. xv1 = xv1.add(rotDX1);
  79779. xv2 = xv2.add(rotDX2);
  79780. }
  79781. fy += dy;
  79782. }
  79783. return textureArray;
  79784. };
  79785. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79786. var theta = Math.atan2(vDir.z, vDir.x);
  79787. var phi = Math.acos(vDir.y);
  79788. while (theta < -Math.PI)
  79789. theta += 2 * Math.PI;
  79790. while (theta > Math.PI)
  79791. theta -= 2 * Math.PI;
  79792. var dx = theta / Math.PI;
  79793. var dy = phi / Math.PI;
  79794. // recenter.
  79795. dx = dx * 0.5 + 0.5;
  79796. var px = Math.round(dx * inputWidth);
  79797. if (px < 0)
  79798. px = 0;
  79799. else if (px >= inputWidth)
  79800. px = inputWidth - 1;
  79801. var py = Math.round(dy * inputHeight);
  79802. if (py < 0)
  79803. py = 0;
  79804. else if (py >= inputHeight)
  79805. py = inputHeight - 1;
  79806. var inputY = (inputHeight - py - 1);
  79807. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79808. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79809. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79810. return {
  79811. r: r,
  79812. g: g,
  79813. b: b
  79814. };
  79815. };
  79816. PanoramaToCubeMapTools.FACE_FRONT = [
  79817. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79818. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79819. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79820. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79821. ];
  79822. PanoramaToCubeMapTools.FACE_BACK = [
  79823. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79824. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79825. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79826. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79827. ];
  79828. PanoramaToCubeMapTools.FACE_RIGHT = [
  79829. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79830. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79831. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79832. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79833. ];
  79834. PanoramaToCubeMapTools.FACE_LEFT = [
  79835. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79836. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79837. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79838. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79839. ];
  79840. PanoramaToCubeMapTools.FACE_DOWN = [
  79841. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79842. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79843. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79844. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79845. ];
  79846. PanoramaToCubeMapTools.FACE_UP = [
  79847. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79848. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79849. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79850. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79851. ];
  79852. return PanoramaToCubeMapTools;
  79853. }());
  79854. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79855. })(BABYLON || (BABYLON = {}));
  79856. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79857. var BABYLON;
  79858. (function (BABYLON) {
  79859. ;
  79860. /**
  79861. * This groups tools to convert HDR texture to native colors array.
  79862. */
  79863. var HDRTools = /** @class */ (function () {
  79864. function HDRTools() {
  79865. }
  79866. HDRTools.Ldexp = function (mantissa, exponent) {
  79867. if (exponent > 1023) {
  79868. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79869. }
  79870. if (exponent < -1074) {
  79871. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79872. }
  79873. return mantissa * Math.pow(2, exponent);
  79874. };
  79875. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79876. if (exponent > 0) { /*nonzero pixel*/
  79877. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79878. float32array[index + 0] = red * exponent;
  79879. float32array[index + 1] = green * exponent;
  79880. float32array[index + 2] = blue * exponent;
  79881. }
  79882. else {
  79883. float32array[index + 0] = 0;
  79884. float32array[index + 1] = 0;
  79885. float32array[index + 2] = 0;
  79886. }
  79887. };
  79888. HDRTools.readStringLine = function (uint8array, startIndex) {
  79889. var line = "";
  79890. var character = "";
  79891. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79892. character = String.fromCharCode(uint8array[i]);
  79893. if (character == "\n") {
  79894. break;
  79895. }
  79896. line += character;
  79897. }
  79898. return line;
  79899. };
  79900. /**
  79901. * Reads header information from an RGBE texture stored in a native array.
  79902. * More information on this format are available here:
  79903. * https://en.wikipedia.org/wiki/RGBE_image_format
  79904. *
  79905. * @param uint8array The binary file stored in native array.
  79906. * @return The header information.
  79907. */
  79908. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79909. var height = 0;
  79910. var width = 0;
  79911. var line = this.readStringLine(uint8array, 0);
  79912. if (line[0] != '#' || line[1] != '?') {
  79913. throw "Bad HDR Format.";
  79914. }
  79915. var endOfHeader = false;
  79916. var findFormat = false;
  79917. var lineIndex = 0;
  79918. do {
  79919. lineIndex += (line.length + 1);
  79920. line = this.readStringLine(uint8array, lineIndex);
  79921. if (line == "FORMAT=32-bit_rle_rgbe") {
  79922. findFormat = true;
  79923. }
  79924. else if (line.length == 0) {
  79925. endOfHeader = true;
  79926. }
  79927. } while (!endOfHeader);
  79928. if (!findFormat) {
  79929. throw "HDR Bad header format, unsupported FORMAT";
  79930. }
  79931. lineIndex += (line.length + 1);
  79932. line = this.readStringLine(uint8array, lineIndex);
  79933. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79934. var match = sizeRegexp.exec(line);
  79935. // TODO. Support +Y and -X if needed.
  79936. if (!match || match.length < 3) {
  79937. throw "HDR Bad header format, no size";
  79938. }
  79939. width = parseInt(match[2]);
  79940. height = parseInt(match[1]);
  79941. if (width < 8 || width > 0x7fff) {
  79942. throw "HDR Bad header format, unsupported size";
  79943. }
  79944. lineIndex += (line.length + 1);
  79945. return {
  79946. height: height,
  79947. width: width,
  79948. dataPosition: lineIndex
  79949. };
  79950. };
  79951. /**
  79952. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79953. * This RGBE texture needs to store the information as a panorama.
  79954. *
  79955. * More information on this format are available here:
  79956. * https://en.wikipedia.org/wiki/RGBE_image_format
  79957. *
  79958. * @param buffer The binary file stored in an array buffer.
  79959. * @param size The expected size of the extracted cubemap.
  79960. * @return The Cube Map information.
  79961. */
  79962. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  79963. var uint8array = new Uint8Array(buffer);
  79964. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  79965. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79966. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  79967. return cubeMapData;
  79968. };
  79969. /**
  79970. * Returns the pixels data extracted from an RGBE texture.
  79971. * This pixels will be stored left to right up to down in the R G B order in one array.
  79972. *
  79973. * More information on this format are available here:
  79974. * https://en.wikipedia.org/wiki/RGBE_image_format
  79975. *
  79976. * @param uint8array The binary file stored in an array buffer.
  79977. * @param hdrInfo The header information of the file.
  79978. * @return The pixels data in RGB right to left up to down order.
  79979. */
  79980. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  79981. // Keep for multi format supports.
  79982. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79983. };
  79984. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  79985. var num_scanlines = hdrInfo.height;
  79986. var scanline_width = hdrInfo.width;
  79987. var a, b, c, d, count;
  79988. var dataIndex = hdrInfo.dataPosition;
  79989. var index = 0, endIndex = 0, i = 0;
  79990. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  79991. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  79992. // 3 channels of 4 bytes per pixel in float.
  79993. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  79994. var resultArray = new Float32Array(resultBuffer);
  79995. // read in each successive scanline
  79996. while (num_scanlines > 0) {
  79997. a = uint8array[dataIndex++];
  79998. b = uint8array[dataIndex++];
  79999. c = uint8array[dataIndex++];
  80000. d = uint8array[dataIndex++];
  80001. if (a != 2 || b != 2 || (c & 0x80)) {
  80002. // this file is not run length encoded
  80003. throw "HDR Bad header format, not RLE";
  80004. }
  80005. if (((c << 8) | d) != scanline_width) {
  80006. throw "HDR Bad header format, wrong scan line width";
  80007. }
  80008. index = 0;
  80009. // read each of the four channels for the scanline into the buffer
  80010. for (i = 0; i < 4; i++) {
  80011. endIndex = (i + 1) * scanline_width;
  80012. while (index < endIndex) {
  80013. a = uint8array[dataIndex++];
  80014. b = uint8array[dataIndex++];
  80015. if (a > 128) {
  80016. // a run of the same value
  80017. count = a - 128;
  80018. if ((count == 0) || (count > endIndex - index)) {
  80019. throw "HDR Bad Format, bad scanline data (run)";
  80020. }
  80021. while (count-- > 0) {
  80022. scanLineArray[index++] = b;
  80023. }
  80024. }
  80025. else {
  80026. // a non-run
  80027. count = a;
  80028. if ((count == 0) || (count > endIndex - index)) {
  80029. throw "HDR Bad Format, bad scanline data (non-run)";
  80030. }
  80031. scanLineArray[index++] = b;
  80032. if (--count > 0) {
  80033. for (var j = 0; j < count; j++) {
  80034. scanLineArray[index++] = uint8array[dataIndex++];
  80035. }
  80036. }
  80037. }
  80038. }
  80039. }
  80040. // now convert data from buffer into floats
  80041. for (i = 0; i < scanline_width; i++) {
  80042. a = scanLineArray[i];
  80043. b = scanLineArray[i + scanline_width];
  80044. c = scanLineArray[i + 2 * scanline_width];
  80045. d = scanLineArray[i + 3 * scanline_width];
  80046. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80047. }
  80048. num_scanlines--;
  80049. }
  80050. return resultArray;
  80051. };
  80052. return HDRTools;
  80053. }());
  80054. BABYLON.HDRTools = HDRTools;
  80055. })(BABYLON || (BABYLON = {}));
  80056. //# sourceMappingURL=babylon.hdr.js.map
  80057. var BABYLON;
  80058. (function (BABYLON) {
  80059. /**
  80060. * This represents a texture coming from an HDR input.
  80061. *
  80062. * The only supported format is currently panorama picture stored in RGBE format.
  80063. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80064. */
  80065. var HDRCubeTexture = /** @class */ (function (_super) {
  80066. __extends(HDRCubeTexture, _super);
  80067. /**
  80068. * Instantiates an HDRTexture from the following parameters.
  80069. *
  80070. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80071. * @param scene The scene the texture will be used in
  80072. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80073. * @param noMipmap Forces to not generate the mipmap if true
  80074. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80075. * @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)
  80076. * @param reserved Reserved flag for internal use.
  80077. */
  80078. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80079. if (noMipmap === void 0) { noMipmap = false; }
  80080. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80081. if (gammaSpace === void 0) { gammaSpace = false; }
  80082. if (reserved === void 0) { reserved = false; }
  80083. if (onLoad === void 0) { onLoad = null; }
  80084. if (onError === void 0) { onError = null; }
  80085. var _this = _super.call(this, scene) || this;
  80086. _this._generateHarmonics = true;
  80087. _this._onLoad = null;
  80088. _this._onError = null;
  80089. /**
  80090. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80091. */
  80092. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80093. _this._isBlocking = true;
  80094. _this._rotationY = 0;
  80095. /**
  80096. * Gets or sets the center of the bounding box associated with the cube texture
  80097. * It must define where the camera used to render the texture was set
  80098. */
  80099. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80100. if (!url) {
  80101. return _this;
  80102. }
  80103. _this.name = url;
  80104. _this.url = url;
  80105. _this.hasAlpha = false;
  80106. _this.isCube = true;
  80107. _this._textureMatrix = BABYLON.Matrix.Identity();
  80108. _this._onLoad = onLoad;
  80109. _this._onError = onError;
  80110. _this.gammaSpace = gammaSpace;
  80111. _this._noMipmap = noMipmap;
  80112. _this._size = size;
  80113. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80114. if (!_this._texture) {
  80115. if (!scene.useDelayedTextureLoading) {
  80116. _this.loadTexture();
  80117. }
  80118. else {
  80119. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80120. }
  80121. }
  80122. return _this;
  80123. }
  80124. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80125. /**
  80126. * Gets wether or not the texture is blocking during loading.
  80127. */
  80128. get: function () {
  80129. return this._isBlocking;
  80130. },
  80131. /**
  80132. * Sets wether or not the texture is blocking during loading.
  80133. */
  80134. set: function (value) {
  80135. this._isBlocking = value;
  80136. },
  80137. enumerable: true,
  80138. configurable: true
  80139. });
  80140. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80141. /**
  80142. * Gets texture matrix rotation angle around Y axis radians.
  80143. */
  80144. get: function () {
  80145. return this._rotationY;
  80146. },
  80147. /**
  80148. * Sets texture matrix rotation angle around Y axis in radians.
  80149. */
  80150. set: function (value) {
  80151. this._rotationY = value;
  80152. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80153. },
  80154. enumerable: true,
  80155. configurable: true
  80156. });
  80157. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80158. get: function () {
  80159. return this._boundingBoxSize;
  80160. },
  80161. /**
  80162. * Gets or sets the size of the bounding box associated with the cube texture
  80163. * When defined, the cubemap will switch to local mode
  80164. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80165. * @example https://www.babylonjs-playground.com/#RNASML
  80166. */
  80167. set: function (value) {
  80168. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80169. return;
  80170. }
  80171. this._boundingBoxSize = value;
  80172. var scene = this.getScene();
  80173. if (scene) {
  80174. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80175. }
  80176. },
  80177. enumerable: true,
  80178. configurable: true
  80179. });
  80180. /**
  80181. * Occurs when the file is raw .hdr file.
  80182. */
  80183. HDRCubeTexture.prototype.loadTexture = function () {
  80184. var _this = this;
  80185. var callback = function (buffer) {
  80186. var scene = _this.getScene();
  80187. if (!scene) {
  80188. return null;
  80189. }
  80190. // Extract the raw linear data.
  80191. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80192. // Generate harmonics if needed.
  80193. if (_this._generateHarmonics) {
  80194. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80195. _this.sphericalPolynomial = sphericalPolynomial;
  80196. }
  80197. var results = [];
  80198. var byteArray = null;
  80199. // Push each faces.
  80200. for (var j = 0; j < 6; j++) {
  80201. // Create uintarray fallback.
  80202. if (!scene.getEngine().getCaps().textureFloat) {
  80203. // 3 channels of 1 bytes per pixel in bytes.
  80204. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80205. byteArray = new Uint8Array(byteBuffer);
  80206. }
  80207. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80208. // If special cases.
  80209. if (_this.gammaSpace || byteArray) {
  80210. for (var i = 0; i < _this._size * _this._size; i++) {
  80211. // Put in gamma space if requested.
  80212. if (_this.gammaSpace) {
  80213. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80214. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80215. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80216. }
  80217. // Convert to int texture for fallback.
  80218. if (byteArray) {
  80219. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80220. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80221. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80222. // May use luminance instead if the result is not accurate.
  80223. var max = Math.max(Math.max(r, g), b);
  80224. if (max > 255) {
  80225. var scale = 255 / max;
  80226. r *= scale;
  80227. g *= scale;
  80228. b *= scale;
  80229. }
  80230. byteArray[(i * 3) + 0] = r;
  80231. byteArray[(i * 3) + 1] = g;
  80232. byteArray[(i * 3) + 2] = b;
  80233. }
  80234. }
  80235. }
  80236. if (byteArray) {
  80237. results.push(byteArray);
  80238. }
  80239. else {
  80240. results.push(dataFace);
  80241. }
  80242. }
  80243. return results;
  80244. };
  80245. var scene = this.getScene();
  80246. if (scene) {
  80247. 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);
  80248. }
  80249. };
  80250. HDRCubeTexture.prototype.clone = function () {
  80251. var scene = this.getScene();
  80252. if (!scene) {
  80253. return this;
  80254. }
  80255. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80256. // Base texture
  80257. newTexture.level = this.level;
  80258. newTexture.wrapU = this.wrapU;
  80259. newTexture.wrapV = this.wrapV;
  80260. newTexture.coordinatesIndex = this.coordinatesIndex;
  80261. newTexture.coordinatesMode = this.coordinatesMode;
  80262. return newTexture;
  80263. };
  80264. // Methods
  80265. HDRCubeTexture.prototype.delayLoad = function () {
  80266. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80267. return;
  80268. }
  80269. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80270. this._texture = this._getFromCache(this.url, this._noMipmap);
  80271. if (!this._texture) {
  80272. this.loadTexture();
  80273. }
  80274. };
  80275. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80276. return this._textureMatrix;
  80277. };
  80278. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80279. this._textureMatrix = value;
  80280. };
  80281. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80282. var texture = null;
  80283. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80284. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80285. texture.name = parsedTexture.name;
  80286. texture.hasAlpha = parsedTexture.hasAlpha;
  80287. texture.level = parsedTexture.level;
  80288. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80289. texture.isBlocking = parsedTexture.isBlocking;
  80290. }
  80291. if (texture) {
  80292. if (parsedTexture.boundingBoxPosition) {
  80293. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80294. }
  80295. if (parsedTexture.boundingBoxSize) {
  80296. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80297. }
  80298. if (parsedTexture.rotationY) {
  80299. texture.rotationY = parsedTexture.rotationY;
  80300. }
  80301. }
  80302. return texture;
  80303. };
  80304. HDRCubeTexture.prototype.serialize = function () {
  80305. if (!this.name) {
  80306. return null;
  80307. }
  80308. var serializationObject = {};
  80309. serializationObject.name = this.name;
  80310. serializationObject.hasAlpha = this.hasAlpha;
  80311. serializationObject.isCube = true;
  80312. serializationObject.level = this.level;
  80313. serializationObject.size = this._size;
  80314. serializationObject.coordinatesMode = this.coordinatesMode;
  80315. serializationObject.useInGammaSpace = this.gammaSpace;
  80316. serializationObject.generateHarmonics = this._generateHarmonics;
  80317. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80318. serializationObject.noMipmap = this._noMipmap;
  80319. serializationObject.isBlocking = this._isBlocking;
  80320. serializationObject.rotationY = this._rotationY;
  80321. return serializationObject;
  80322. };
  80323. HDRCubeTexture._facesMapping = [
  80324. "right",
  80325. "left",
  80326. "up",
  80327. "down",
  80328. "front",
  80329. "back"
  80330. ];
  80331. return HDRCubeTexture;
  80332. }(BABYLON.BaseTexture));
  80333. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80334. })(BABYLON || (BABYLON = {}));
  80335. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80336. var BABYLON;
  80337. (function (BABYLON) {
  80338. var IndexedVector2 = /** @class */ (function (_super) {
  80339. __extends(IndexedVector2, _super);
  80340. function IndexedVector2(original, index) {
  80341. var _this = _super.call(this, original.x, original.y) || this;
  80342. _this.index = index;
  80343. return _this;
  80344. }
  80345. return IndexedVector2;
  80346. }(BABYLON.Vector2));
  80347. var PolygonPoints = /** @class */ (function () {
  80348. function PolygonPoints() {
  80349. this.elements = new Array();
  80350. }
  80351. PolygonPoints.prototype.add = function (originalPoints) {
  80352. var _this = this;
  80353. var result = new Array();
  80354. originalPoints.forEach(function (point) {
  80355. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80356. var newPoint = new IndexedVector2(point, _this.elements.length);
  80357. result.push(newPoint);
  80358. _this.elements.push(newPoint);
  80359. }
  80360. });
  80361. return result;
  80362. };
  80363. PolygonPoints.prototype.computeBounds = function () {
  80364. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80365. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80366. this.elements.forEach(function (point) {
  80367. // x
  80368. if (point.x < lmin.x) {
  80369. lmin.x = point.x;
  80370. }
  80371. else if (point.x > lmax.x) {
  80372. lmax.x = point.x;
  80373. }
  80374. // y
  80375. if (point.y < lmin.y) {
  80376. lmin.y = point.y;
  80377. }
  80378. else if (point.y > lmax.y) {
  80379. lmax.y = point.y;
  80380. }
  80381. });
  80382. return {
  80383. min: lmin,
  80384. max: lmax,
  80385. width: lmax.x - lmin.x,
  80386. height: lmax.y - lmin.y
  80387. };
  80388. };
  80389. return PolygonPoints;
  80390. }());
  80391. var Polygon = /** @class */ (function () {
  80392. function Polygon() {
  80393. }
  80394. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80395. return [
  80396. new BABYLON.Vector2(xmin, ymin),
  80397. new BABYLON.Vector2(xmax, ymin),
  80398. new BABYLON.Vector2(xmax, ymax),
  80399. new BABYLON.Vector2(xmin, ymax)
  80400. ];
  80401. };
  80402. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80403. if (cx === void 0) { cx = 0; }
  80404. if (cy === void 0) { cy = 0; }
  80405. if (numberOfSides === void 0) { numberOfSides = 32; }
  80406. var result = new Array();
  80407. var angle = 0;
  80408. var increment = (Math.PI * 2) / numberOfSides;
  80409. for (var i = 0; i < numberOfSides; i++) {
  80410. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80411. angle -= increment;
  80412. }
  80413. return result;
  80414. };
  80415. Polygon.Parse = function (input) {
  80416. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80417. var i, result = [];
  80418. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80419. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80420. }
  80421. return result;
  80422. };
  80423. Polygon.StartingAt = function (x, y) {
  80424. return BABYLON.Path2.StartingAt(x, y);
  80425. };
  80426. return Polygon;
  80427. }());
  80428. BABYLON.Polygon = Polygon;
  80429. var PolygonMeshBuilder = /** @class */ (function () {
  80430. function PolygonMeshBuilder(name, contours, scene) {
  80431. this._points = new PolygonPoints();
  80432. this._outlinepoints = new PolygonPoints();
  80433. this._holes = new Array();
  80434. this._epoints = new Array();
  80435. this._eholes = new Array();
  80436. this._name = name;
  80437. this._scene = scene;
  80438. var points;
  80439. if (contours instanceof BABYLON.Path2) {
  80440. points = contours.getPoints();
  80441. }
  80442. else {
  80443. points = contours;
  80444. }
  80445. this._addToepoint(points);
  80446. this._points.add(points);
  80447. this._outlinepoints.add(points);
  80448. if (typeof earcut === 'undefined') {
  80449. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80450. }
  80451. }
  80452. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80453. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80454. var p = points_1[_i];
  80455. this._epoints.push(p.x, p.y);
  80456. }
  80457. };
  80458. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80459. this._points.add(hole);
  80460. var holepoints = new PolygonPoints();
  80461. holepoints.add(hole);
  80462. this._holes.push(holepoints);
  80463. this._eholes.push(this._epoints.length / 2);
  80464. this._addToepoint(hole);
  80465. return this;
  80466. };
  80467. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80468. var _this = this;
  80469. if (updatable === void 0) { updatable = false; }
  80470. if (depth === void 0) { depth = 0; }
  80471. var result = new BABYLON.Mesh(this._name, this._scene);
  80472. var normals = new Array();
  80473. var positions = new Array();
  80474. var uvs = new Array();
  80475. var bounds = this._points.computeBounds();
  80476. this._points.elements.forEach(function (p) {
  80477. normals.push(0, 1.0, 0);
  80478. positions.push(p.x, 0, p.y);
  80479. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80480. });
  80481. var indices = new Array();
  80482. var res = earcut(this._epoints, this._eholes, 2);
  80483. for (var i = 0; i < res.length; i++) {
  80484. indices.push(res[i]);
  80485. }
  80486. if (depth > 0) {
  80487. var positionscount = (positions.length / 3); //get the current pointcount
  80488. this._points.elements.forEach(function (p) {
  80489. normals.push(0, -1.0, 0);
  80490. positions.push(p.x, -depth, p.y);
  80491. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80492. });
  80493. var totalCount = indices.length;
  80494. for (var i = 0; i < totalCount; i += 3) {
  80495. var i0 = indices[i + 0];
  80496. var i1 = indices[i + 1];
  80497. var i2 = indices[i + 2];
  80498. indices.push(i2 + positionscount);
  80499. indices.push(i1 + positionscount);
  80500. indices.push(i0 + positionscount);
  80501. }
  80502. //Add the sides
  80503. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80504. this._holes.forEach(function (hole) {
  80505. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80506. });
  80507. }
  80508. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80509. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80510. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80511. result.setIndices(indices);
  80512. return result;
  80513. };
  80514. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80515. var StartIndex = positions.length / 3;
  80516. var ulength = 0;
  80517. for (var i = 0; i < points.elements.length; i++) {
  80518. var p = points.elements[i];
  80519. var p1;
  80520. if ((i + 1) > points.elements.length - 1) {
  80521. p1 = points.elements[0];
  80522. }
  80523. else {
  80524. p1 = points.elements[i + 1];
  80525. }
  80526. positions.push(p.x, 0, p.y);
  80527. positions.push(p.x, -depth, p.y);
  80528. positions.push(p1.x, 0, p1.y);
  80529. positions.push(p1.x, -depth, p1.y);
  80530. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80531. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80532. var v3 = v2.subtract(v1);
  80533. var v4 = new BABYLON.Vector3(0, 1, 0);
  80534. var vn = BABYLON.Vector3.Cross(v3, v4);
  80535. vn = vn.normalize();
  80536. uvs.push(ulength / bounds.width, 0);
  80537. uvs.push(ulength / bounds.width, 1);
  80538. ulength += v3.length();
  80539. uvs.push((ulength / bounds.width), 0);
  80540. uvs.push((ulength / bounds.width), 1);
  80541. if (!flip) {
  80542. normals.push(-vn.x, -vn.y, -vn.z);
  80543. normals.push(-vn.x, -vn.y, -vn.z);
  80544. normals.push(-vn.x, -vn.y, -vn.z);
  80545. normals.push(-vn.x, -vn.y, -vn.z);
  80546. indices.push(StartIndex);
  80547. indices.push(StartIndex + 1);
  80548. indices.push(StartIndex + 2);
  80549. indices.push(StartIndex + 1);
  80550. indices.push(StartIndex + 3);
  80551. indices.push(StartIndex + 2);
  80552. }
  80553. else {
  80554. normals.push(vn.x, vn.y, vn.z);
  80555. normals.push(vn.x, vn.y, vn.z);
  80556. normals.push(vn.x, vn.y, vn.z);
  80557. normals.push(vn.x, vn.y, vn.z);
  80558. indices.push(StartIndex);
  80559. indices.push(StartIndex + 2);
  80560. indices.push(StartIndex + 1);
  80561. indices.push(StartIndex + 1);
  80562. indices.push(StartIndex + 2);
  80563. indices.push(StartIndex + 3);
  80564. }
  80565. StartIndex += 4;
  80566. }
  80567. ;
  80568. };
  80569. return PolygonMeshBuilder;
  80570. }());
  80571. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80572. })(BABYLON || (BABYLON = {}));
  80573. //# sourceMappingURL=babylon.polygonMesh.js.map
  80574. var BABYLON;
  80575. (function (BABYLON) {
  80576. // Unique ID when we import meshes from Babylon to CSG
  80577. var currentCSGMeshId = 0;
  80578. // # class Vertex
  80579. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80580. // one to provide additional features like texture coordinates and vertex
  80581. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80582. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80583. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80584. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80585. // is not used anywhere else.
  80586. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80587. var Vertex = /** @class */ (function () {
  80588. function Vertex(pos, normal, uv) {
  80589. this.pos = pos;
  80590. this.normal = normal;
  80591. this.uv = uv;
  80592. }
  80593. Vertex.prototype.clone = function () {
  80594. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80595. };
  80596. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80597. // orientation of a polygon is flipped.
  80598. Vertex.prototype.flip = function () {
  80599. this.normal = this.normal.scale(-1);
  80600. };
  80601. // Create a new vertex between this vertex and `other` by linearly
  80602. // interpolating all properties using a parameter of `t`. Subclasses should
  80603. // override this to interpolate additional properties.
  80604. Vertex.prototype.interpolate = function (other, t) {
  80605. 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));
  80606. };
  80607. return Vertex;
  80608. }());
  80609. // # class Plane
  80610. // Represents a plane in 3D space.
  80611. var Plane = /** @class */ (function () {
  80612. function Plane(normal, w) {
  80613. this.normal = normal;
  80614. this.w = w;
  80615. }
  80616. Plane.FromPoints = function (a, b, c) {
  80617. var v0 = c.subtract(a);
  80618. var v1 = b.subtract(a);
  80619. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80620. return null;
  80621. }
  80622. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80623. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80624. };
  80625. Plane.prototype.clone = function () {
  80626. return new Plane(this.normal.clone(), this.w);
  80627. };
  80628. Plane.prototype.flip = function () {
  80629. this.normal.scaleInPlace(-1);
  80630. this.w = -this.w;
  80631. };
  80632. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80633. // fragments in the appropriate lists. Coplanar polygons go into either
  80634. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80635. // respect to this plane. Polygons in front or in back of this plane go into
  80636. // either `front` or `back`.
  80637. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80638. var COPLANAR = 0;
  80639. var FRONT = 1;
  80640. var BACK = 2;
  80641. var SPANNING = 3;
  80642. // Classify each point as well as the entire polygon into one of the above
  80643. // four classes.
  80644. var polygonType = 0;
  80645. var types = [];
  80646. var i;
  80647. var t;
  80648. for (i = 0; i < polygon.vertices.length; i++) {
  80649. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80650. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80651. polygonType |= type;
  80652. types.push(type);
  80653. }
  80654. // Put the polygon in the correct list, splitting it when necessary.
  80655. switch (polygonType) {
  80656. case COPLANAR:
  80657. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80658. break;
  80659. case FRONT:
  80660. front.push(polygon);
  80661. break;
  80662. case BACK:
  80663. back.push(polygon);
  80664. break;
  80665. case SPANNING:
  80666. var f = [], b = [];
  80667. for (i = 0; i < polygon.vertices.length; i++) {
  80668. var j = (i + 1) % polygon.vertices.length;
  80669. var ti = types[i], tj = types[j];
  80670. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80671. if (ti !== BACK)
  80672. f.push(vi);
  80673. if (ti !== FRONT)
  80674. b.push(ti !== BACK ? vi.clone() : vi);
  80675. if ((ti | tj) === SPANNING) {
  80676. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80677. var v = vi.interpolate(vj, t);
  80678. f.push(v);
  80679. b.push(v.clone());
  80680. }
  80681. }
  80682. var poly;
  80683. if (f.length >= 3) {
  80684. poly = new Polygon(f, polygon.shared);
  80685. if (poly.plane)
  80686. front.push(poly);
  80687. }
  80688. if (b.length >= 3) {
  80689. poly = new Polygon(b, polygon.shared);
  80690. if (poly.plane)
  80691. back.push(poly);
  80692. }
  80693. break;
  80694. }
  80695. };
  80696. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80697. // point is on the plane.
  80698. Plane.EPSILON = 1e-5;
  80699. return Plane;
  80700. }());
  80701. // # class Polygon
  80702. // Represents a convex polygon. The vertices used to initialize a polygon must
  80703. // be coplanar and form a convex loop.
  80704. //
  80705. // Each convex polygon has a `shared` property, which is shared between all
  80706. // polygons that are clones of each other or were split from the same polygon.
  80707. // This can be used to define per-polygon properties (such as surface color).
  80708. var Polygon = /** @class */ (function () {
  80709. function Polygon(vertices, shared) {
  80710. this.vertices = vertices;
  80711. this.shared = shared;
  80712. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80713. }
  80714. Polygon.prototype.clone = function () {
  80715. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80716. return new Polygon(vertices, this.shared);
  80717. };
  80718. Polygon.prototype.flip = function () {
  80719. this.vertices.reverse().map(function (v) { v.flip(); });
  80720. this.plane.flip();
  80721. };
  80722. return Polygon;
  80723. }());
  80724. // # class Node
  80725. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80726. // by picking a polygon to split along. That polygon (and all other coplanar
  80727. // polygons) are added directly to that node and the other polygons are added to
  80728. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80729. // no distinction between internal and leaf nodes.
  80730. var Node = /** @class */ (function () {
  80731. function Node(polygons) {
  80732. this.plane = null;
  80733. this.front = null;
  80734. this.back = null;
  80735. this.polygons = new Array();
  80736. if (polygons) {
  80737. this.build(polygons);
  80738. }
  80739. }
  80740. Node.prototype.clone = function () {
  80741. var node = new Node();
  80742. node.plane = this.plane && this.plane.clone();
  80743. node.front = this.front && this.front.clone();
  80744. node.back = this.back && this.back.clone();
  80745. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80746. return node;
  80747. };
  80748. // Convert solid space to empty space and empty space to solid space.
  80749. Node.prototype.invert = function () {
  80750. for (var i = 0; i < this.polygons.length; i++) {
  80751. this.polygons[i].flip();
  80752. }
  80753. if (this.plane) {
  80754. this.plane.flip();
  80755. }
  80756. if (this.front) {
  80757. this.front.invert();
  80758. }
  80759. if (this.back) {
  80760. this.back.invert();
  80761. }
  80762. var temp = this.front;
  80763. this.front = this.back;
  80764. this.back = temp;
  80765. };
  80766. // Recursively remove all polygons in `polygons` that are inside this BSP
  80767. // tree.
  80768. Node.prototype.clipPolygons = function (polygons) {
  80769. if (!this.plane)
  80770. return polygons.slice();
  80771. var front = new Array(), back = new Array();
  80772. for (var i = 0; i < polygons.length; i++) {
  80773. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80774. }
  80775. if (this.front) {
  80776. front = this.front.clipPolygons(front);
  80777. }
  80778. if (this.back) {
  80779. back = this.back.clipPolygons(back);
  80780. }
  80781. else {
  80782. back = [];
  80783. }
  80784. return front.concat(back);
  80785. };
  80786. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80787. // `bsp`.
  80788. Node.prototype.clipTo = function (bsp) {
  80789. this.polygons = bsp.clipPolygons(this.polygons);
  80790. if (this.front)
  80791. this.front.clipTo(bsp);
  80792. if (this.back)
  80793. this.back.clipTo(bsp);
  80794. };
  80795. // Return a list of all polygons in this BSP tree.
  80796. Node.prototype.allPolygons = function () {
  80797. var polygons = this.polygons.slice();
  80798. if (this.front)
  80799. polygons = polygons.concat(this.front.allPolygons());
  80800. if (this.back)
  80801. polygons = polygons.concat(this.back.allPolygons());
  80802. return polygons;
  80803. };
  80804. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80805. // new polygons are filtered down to the bottom of the tree and become new
  80806. // nodes there. Each set of polygons is partitioned using the first polygon
  80807. // (no heuristic is used to pick a good split).
  80808. Node.prototype.build = function (polygons) {
  80809. if (!polygons.length)
  80810. return;
  80811. if (!this.plane)
  80812. this.plane = polygons[0].plane.clone();
  80813. var front = new Array(), back = new Array();
  80814. for (var i = 0; i < polygons.length; i++) {
  80815. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80816. }
  80817. if (front.length) {
  80818. if (!this.front)
  80819. this.front = new Node();
  80820. this.front.build(front);
  80821. }
  80822. if (back.length) {
  80823. if (!this.back)
  80824. this.back = new Node();
  80825. this.back.build(back);
  80826. }
  80827. };
  80828. return Node;
  80829. }());
  80830. var CSG = /** @class */ (function () {
  80831. function CSG() {
  80832. this.polygons = new Array();
  80833. }
  80834. // Convert BABYLON.Mesh to BABYLON.CSG
  80835. CSG.FromMesh = function (mesh) {
  80836. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80837. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80838. if (mesh instanceof BABYLON.Mesh) {
  80839. mesh.computeWorldMatrix(true);
  80840. matrix = mesh.getWorldMatrix();
  80841. meshPosition = mesh.position.clone();
  80842. meshRotation = mesh.rotation.clone();
  80843. if (mesh.rotationQuaternion) {
  80844. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80845. }
  80846. meshScaling = mesh.scaling.clone();
  80847. }
  80848. else {
  80849. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80850. }
  80851. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80852. var subMeshes = mesh.subMeshes;
  80853. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80854. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80855. vertices = [];
  80856. for (var j = 0; j < 3; j++) {
  80857. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80858. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80859. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80860. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80861. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80862. vertex = new Vertex(position, normal, uv);
  80863. vertices.push(vertex);
  80864. }
  80865. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80866. // To handle the case of degenerated triangle
  80867. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80868. if (polygon.plane)
  80869. polygons.push(polygon);
  80870. }
  80871. }
  80872. var csg = CSG.FromPolygons(polygons);
  80873. csg.matrix = matrix;
  80874. csg.position = meshPosition;
  80875. csg.rotation = meshRotation;
  80876. csg.scaling = meshScaling;
  80877. csg.rotationQuaternion = meshRotationQuaternion;
  80878. currentCSGMeshId++;
  80879. return csg;
  80880. };
  80881. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80882. CSG.FromPolygons = function (polygons) {
  80883. var csg = new CSG();
  80884. csg.polygons = polygons;
  80885. return csg;
  80886. };
  80887. CSG.prototype.clone = function () {
  80888. var csg = new CSG();
  80889. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  80890. csg.copyTransformAttributes(this);
  80891. return csg;
  80892. };
  80893. CSG.prototype.union = function (csg) {
  80894. var a = new Node(this.clone().polygons);
  80895. var b = new Node(csg.clone().polygons);
  80896. a.clipTo(b);
  80897. b.clipTo(a);
  80898. b.invert();
  80899. b.clipTo(a);
  80900. b.invert();
  80901. a.build(b.allPolygons());
  80902. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80903. };
  80904. CSG.prototype.unionInPlace = function (csg) {
  80905. var a = new Node(this.polygons);
  80906. var b = new Node(csg.polygons);
  80907. a.clipTo(b);
  80908. b.clipTo(a);
  80909. b.invert();
  80910. b.clipTo(a);
  80911. b.invert();
  80912. a.build(b.allPolygons());
  80913. this.polygons = a.allPolygons();
  80914. };
  80915. CSG.prototype.subtract = function (csg) {
  80916. var a = new Node(this.clone().polygons);
  80917. var b = new Node(csg.clone().polygons);
  80918. a.invert();
  80919. a.clipTo(b);
  80920. b.clipTo(a);
  80921. b.invert();
  80922. b.clipTo(a);
  80923. b.invert();
  80924. a.build(b.allPolygons());
  80925. a.invert();
  80926. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80927. };
  80928. CSG.prototype.subtractInPlace = function (csg) {
  80929. var a = new Node(this.polygons);
  80930. var b = new Node(csg.polygons);
  80931. a.invert();
  80932. a.clipTo(b);
  80933. b.clipTo(a);
  80934. b.invert();
  80935. b.clipTo(a);
  80936. b.invert();
  80937. a.build(b.allPolygons());
  80938. a.invert();
  80939. this.polygons = a.allPolygons();
  80940. };
  80941. CSG.prototype.intersect = function (csg) {
  80942. var a = new Node(this.clone().polygons);
  80943. var b = new Node(csg.clone().polygons);
  80944. a.invert();
  80945. b.clipTo(a);
  80946. b.invert();
  80947. a.clipTo(b);
  80948. b.clipTo(a);
  80949. a.build(b.allPolygons());
  80950. a.invert();
  80951. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80952. };
  80953. CSG.prototype.intersectInPlace = function (csg) {
  80954. var a = new Node(this.polygons);
  80955. var b = new Node(csg.polygons);
  80956. a.invert();
  80957. b.clipTo(a);
  80958. b.invert();
  80959. a.clipTo(b);
  80960. b.clipTo(a);
  80961. a.build(b.allPolygons());
  80962. a.invert();
  80963. this.polygons = a.allPolygons();
  80964. };
  80965. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  80966. // not modified.
  80967. CSG.prototype.inverse = function () {
  80968. var csg = this.clone();
  80969. csg.inverseInPlace();
  80970. return csg;
  80971. };
  80972. CSG.prototype.inverseInPlace = function () {
  80973. this.polygons.map(function (p) { p.flip(); });
  80974. };
  80975. // This is used to keep meshes transformations so they can be restored
  80976. // when we build back a Babylon Mesh
  80977. // NB : All CSG operations are performed in world coordinates
  80978. CSG.prototype.copyTransformAttributes = function (csg) {
  80979. this.matrix = csg.matrix;
  80980. this.position = csg.position;
  80981. this.rotation = csg.rotation;
  80982. this.scaling = csg.scaling;
  80983. this.rotationQuaternion = csg.rotationQuaternion;
  80984. return this;
  80985. };
  80986. // Build Raw mesh from CSG
  80987. // Coordinates here are in world space
  80988. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  80989. var matrix = this.matrix.clone();
  80990. matrix.invert();
  80991. 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;
  80992. if (keepSubMeshes) {
  80993. // Sort Polygons, since subMeshes are indices range
  80994. polygons.sort(function (a, b) {
  80995. if (a.shared.meshId === b.shared.meshId) {
  80996. return a.shared.subMeshId - b.shared.subMeshId;
  80997. }
  80998. else {
  80999. return a.shared.meshId - b.shared.meshId;
  81000. }
  81001. });
  81002. }
  81003. for (var i = 0, il = polygons.length; i < il; i++) {
  81004. polygon = polygons[i];
  81005. // Building SubMeshes
  81006. if (!subMesh_dict[polygon.shared.meshId]) {
  81007. subMesh_dict[polygon.shared.meshId] = {};
  81008. }
  81009. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81010. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81011. indexStart: +Infinity,
  81012. indexEnd: -Infinity,
  81013. materialIndex: polygon.shared.materialIndex
  81014. };
  81015. }
  81016. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81017. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81018. polygonIndices[0] = 0;
  81019. polygonIndices[1] = j - 1;
  81020. polygonIndices[2] = j;
  81021. for (var k = 0; k < 3; k++) {
  81022. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81023. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81024. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81025. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81026. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81027. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81028. // Check if 2 points can be merged
  81029. if (!(typeof vertex_idx !== 'undefined' &&
  81030. normals[vertex_idx * 3] === localNormal.x &&
  81031. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81032. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81033. uvs[vertex_idx * 2] === uv.x &&
  81034. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81035. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81036. uvs.push(uv.x, uv.y);
  81037. normals.push(normal.x, normal.y, normal.z);
  81038. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81039. }
  81040. indices.push(vertex_idx);
  81041. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81042. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81043. currentIndex++;
  81044. }
  81045. }
  81046. }
  81047. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81048. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81049. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81050. mesh.setIndices(indices, null);
  81051. if (keepSubMeshes) {
  81052. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81053. var materialIndexOffset = 0, materialMaxIndex;
  81054. mesh.subMeshes = new Array();
  81055. for (var m in subMesh_dict) {
  81056. materialMaxIndex = -1;
  81057. for (var sm in subMesh_dict[m]) {
  81058. subMesh_obj = subMesh_dict[m][sm];
  81059. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81060. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81061. }
  81062. materialIndexOffset += ++materialMaxIndex;
  81063. }
  81064. }
  81065. return mesh;
  81066. };
  81067. // Build Mesh from CSG taking material and transforms into account
  81068. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81069. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81070. mesh.material = material;
  81071. mesh.position.copyFrom(this.position);
  81072. mesh.rotation.copyFrom(this.rotation);
  81073. if (this.rotationQuaternion) {
  81074. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81075. }
  81076. mesh.scaling.copyFrom(this.scaling);
  81077. mesh.computeWorldMatrix(true);
  81078. return mesh;
  81079. };
  81080. return CSG;
  81081. }());
  81082. BABYLON.CSG = CSG;
  81083. })(BABYLON || (BABYLON = {}));
  81084. //# sourceMappingURL=babylon.csg.js.map
  81085. var BABYLON;
  81086. (function (BABYLON) {
  81087. var LensFlare = /** @class */ (function () {
  81088. function LensFlare(size, position, color, imgUrl, system) {
  81089. this.size = size;
  81090. this.position = position;
  81091. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81092. this.color = color || new BABYLON.Color3(1, 1, 1);
  81093. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81094. this._system = system;
  81095. system.lensFlares.push(this);
  81096. }
  81097. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81098. return new LensFlare(size, position, color, imgUrl, system);
  81099. };
  81100. LensFlare.prototype.dispose = function () {
  81101. if (this.texture) {
  81102. this.texture.dispose();
  81103. }
  81104. // Remove from scene
  81105. var index = this._system.lensFlares.indexOf(this);
  81106. this._system.lensFlares.splice(index, 1);
  81107. };
  81108. ;
  81109. return LensFlare;
  81110. }());
  81111. BABYLON.LensFlare = LensFlare;
  81112. })(BABYLON || (BABYLON = {}));
  81113. //# sourceMappingURL=babylon.lensFlare.js.map
  81114. var BABYLON;
  81115. (function (BABYLON) {
  81116. var LensFlareSystem = /** @class */ (function () {
  81117. function LensFlareSystem(name, emitter, scene) {
  81118. this.name = name;
  81119. this.lensFlares = new Array();
  81120. this.borderLimit = 300;
  81121. this.viewportBorder = 0;
  81122. this.layerMask = 0x0FFFFFFF;
  81123. this._vertexBuffers = {};
  81124. this._isEnabled = true;
  81125. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81126. this._emitter = emitter;
  81127. this.id = name;
  81128. scene.lensFlareSystems.push(this);
  81129. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81130. var engine = scene.getEngine();
  81131. // VBO
  81132. var vertices = [];
  81133. vertices.push(1, 1);
  81134. vertices.push(-1, 1);
  81135. vertices.push(-1, -1);
  81136. vertices.push(1, -1);
  81137. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81138. // Indices
  81139. var indices = [];
  81140. indices.push(0);
  81141. indices.push(1);
  81142. indices.push(2);
  81143. indices.push(0);
  81144. indices.push(2);
  81145. indices.push(3);
  81146. this._indexBuffer = engine.createIndexBuffer(indices);
  81147. // Effects
  81148. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81149. }
  81150. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81151. get: function () {
  81152. return this._isEnabled;
  81153. },
  81154. set: function (value) {
  81155. this._isEnabled = value;
  81156. },
  81157. enumerable: true,
  81158. configurable: true
  81159. });
  81160. LensFlareSystem.prototype.getScene = function () {
  81161. return this._scene;
  81162. };
  81163. LensFlareSystem.prototype.getEmitter = function () {
  81164. return this._emitter;
  81165. };
  81166. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81167. this._emitter = newEmitter;
  81168. };
  81169. LensFlareSystem.prototype.getEmitterPosition = function () {
  81170. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81171. };
  81172. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81173. var position = this.getEmitterPosition();
  81174. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81175. this._positionX = position.x;
  81176. this._positionY = position.y;
  81177. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81178. if (this.viewportBorder > 0) {
  81179. globalViewport.x -= this.viewportBorder;
  81180. globalViewport.y -= this.viewportBorder;
  81181. globalViewport.width += this.viewportBorder * 2;
  81182. globalViewport.height += this.viewportBorder * 2;
  81183. position.x += this.viewportBorder;
  81184. position.y += this.viewportBorder;
  81185. this._positionX += this.viewportBorder;
  81186. this._positionY += this.viewportBorder;
  81187. }
  81188. if (position.z > 0) {
  81189. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81190. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81191. return true;
  81192. }
  81193. return true;
  81194. }
  81195. return false;
  81196. };
  81197. LensFlareSystem.prototype._isVisible = function () {
  81198. if (!this._isEnabled || !this._scene.activeCamera) {
  81199. return false;
  81200. }
  81201. var emitterPosition = this.getEmitterPosition();
  81202. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81203. var distance = direction.length();
  81204. direction.normalize();
  81205. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81206. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81207. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81208. };
  81209. LensFlareSystem.prototype.render = function () {
  81210. if (!this._effect.isReady() || !this._scene.activeCamera)
  81211. return false;
  81212. var engine = this._scene.getEngine();
  81213. var viewport = this._scene.activeCamera.viewport;
  81214. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81215. // Position
  81216. if (!this.computeEffectivePosition(globalViewport)) {
  81217. return false;
  81218. }
  81219. // Visibility
  81220. if (!this._isVisible()) {
  81221. return false;
  81222. }
  81223. // Intensity
  81224. var awayX;
  81225. var awayY;
  81226. if (this._positionX < this.borderLimit + globalViewport.x) {
  81227. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81228. }
  81229. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81230. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81231. }
  81232. else {
  81233. awayX = 0;
  81234. }
  81235. if (this._positionY < this.borderLimit + globalViewport.y) {
  81236. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81237. }
  81238. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81239. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81240. }
  81241. else {
  81242. awayY = 0;
  81243. }
  81244. var away = (awayX > awayY) ? awayX : awayY;
  81245. away -= this.viewportBorder;
  81246. if (away > this.borderLimit) {
  81247. away = this.borderLimit;
  81248. }
  81249. var intensity = 1.0 - (away / this.borderLimit);
  81250. if (intensity < 0) {
  81251. return false;
  81252. }
  81253. if (intensity > 1.0) {
  81254. intensity = 1.0;
  81255. }
  81256. if (this.viewportBorder > 0) {
  81257. globalViewport.x += this.viewportBorder;
  81258. globalViewport.y += this.viewportBorder;
  81259. globalViewport.width -= this.viewportBorder * 2;
  81260. globalViewport.height -= this.viewportBorder * 2;
  81261. this._positionX -= this.viewportBorder;
  81262. this._positionY -= this.viewportBorder;
  81263. }
  81264. // Position
  81265. var centerX = globalViewport.x + globalViewport.width / 2;
  81266. var centerY = globalViewport.y + globalViewport.height / 2;
  81267. var distX = centerX - this._positionX;
  81268. var distY = centerY - this._positionY;
  81269. // Effects
  81270. engine.enableEffect(this._effect);
  81271. engine.setState(false);
  81272. engine.setDepthBuffer(false);
  81273. // VBOs
  81274. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81275. // Flares
  81276. for (var index = 0; index < this.lensFlares.length; index++) {
  81277. var flare = this.lensFlares[index];
  81278. engine.setAlphaMode(flare.alphaMode);
  81279. var x = centerX - (distX * flare.position);
  81280. var y = centerY - (distY * flare.position);
  81281. var cw = flare.size;
  81282. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81283. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81284. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81285. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81286. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81287. // Texture
  81288. this._effect.setTexture("textureSampler", flare.texture);
  81289. // Color
  81290. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81291. // Draw order
  81292. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81293. }
  81294. engine.setDepthBuffer(true);
  81295. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81296. return true;
  81297. };
  81298. LensFlareSystem.prototype.dispose = function () {
  81299. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81300. if (vertexBuffer) {
  81301. vertexBuffer.dispose();
  81302. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81303. }
  81304. if (this._indexBuffer) {
  81305. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81306. this._indexBuffer = null;
  81307. }
  81308. while (this.lensFlares.length) {
  81309. this.lensFlares[0].dispose();
  81310. }
  81311. // Remove from scene
  81312. var index = this._scene.lensFlareSystems.indexOf(this);
  81313. this._scene.lensFlareSystems.splice(index, 1);
  81314. };
  81315. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81316. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81317. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81318. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81319. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81320. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81321. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81322. var parsedFlare = parsedLensFlareSystem.flares[index];
  81323. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81324. }
  81325. return lensFlareSystem;
  81326. };
  81327. LensFlareSystem.prototype.serialize = function () {
  81328. var serializationObject = {};
  81329. serializationObject.id = this.id;
  81330. serializationObject.name = this.name;
  81331. serializationObject.emitterId = this.getEmitter().id;
  81332. serializationObject.borderLimit = this.borderLimit;
  81333. serializationObject.flares = [];
  81334. for (var index = 0; index < this.lensFlares.length; index++) {
  81335. var flare = this.lensFlares[index];
  81336. serializationObject.flares.push({
  81337. size: flare.size,
  81338. position: flare.position,
  81339. color: flare.color.asArray(),
  81340. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81341. });
  81342. }
  81343. return serializationObject;
  81344. };
  81345. return LensFlareSystem;
  81346. }());
  81347. BABYLON.LensFlareSystem = LensFlareSystem;
  81348. })(BABYLON || (BABYLON = {}));
  81349. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81350. var BABYLON;
  81351. (function (BABYLON) {
  81352. /**
  81353. * This is a holder class for the physics joint created by the physics plugin.
  81354. * It holds a set of functions to control the underlying joint.
  81355. */
  81356. var PhysicsJoint = /** @class */ (function () {
  81357. function PhysicsJoint(type, jointData) {
  81358. this.type = type;
  81359. this.jointData = jointData;
  81360. jointData.nativeParams = jointData.nativeParams || {};
  81361. }
  81362. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81363. get: function () {
  81364. return this._physicsJoint;
  81365. },
  81366. set: function (newJoint) {
  81367. if (this._physicsJoint) {
  81368. //remove from the wolrd
  81369. }
  81370. this._physicsJoint = newJoint;
  81371. },
  81372. enumerable: true,
  81373. configurable: true
  81374. });
  81375. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81376. set: function (physicsPlugin) {
  81377. this._physicsPlugin = physicsPlugin;
  81378. },
  81379. enumerable: true,
  81380. configurable: true
  81381. });
  81382. /**
  81383. * Execute a function that is physics-plugin specific.
  81384. * @param {Function} func the function that will be executed.
  81385. * It accepts two parameters: the physics world and the physics joint.
  81386. */
  81387. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81388. func(this._physicsPlugin.world, this._physicsJoint);
  81389. };
  81390. //TODO check if the native joints are the same
  81391. //Joint Types
  81392. PhysicsJoint.DistanceJoint = 0;
  81393. PhysicsJoint.HingeJoint = 1;
  81394. PhysicsJoint.BallAndSocketJoint = 2;
  81395. PhysicsJoint.WheelJoint = 3;
  81396. PhysicsJoint.SliderJoint = 4;
  81397. //OIMO
  81398. PhysicsJoint.PrismaticJoint = 5;
  81399. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81400. PhysicsJoint.UniversalJoint = 6;
  81401. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81402. //Cannon
  81403. //Similar to a Ball-Joint. Different in params
  81404. PhysicsJoint.PointToPointJoint = 8;
  81405. //Cannon only at the moment
  81406. PhysicsJoint.SpringJoint = 9;
  81407. PhysicsJoint.LockJoint = 10;
  81408. return PhysicsJoint;
  81409. }());
  81410. BABYLON.PhysicsJoint = PhysicsJoint;
  81411. /**
  81412. * A class representing a physics distance joint.
  81413. */
  81414. var DistanceJoint = /** @class */ (function (_super) {
  81415. __extends(DistanceJoint, _super);
  81416. function DistanceJoint(jointData) {
  81417. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81418. }
  81419. /**
  81420. * Update the predefined distance.
  81421. */
  81422. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81423. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81424. };
  81425. return DistanceJoint;
  81426. }(PhysicsJoint));
  81427. BABYLON.DistanceJoint = DistanceJoint;
  81428. var MotorEnabledJoint = /** @class */ (function (_super) {
  81429. __extends(MotorEnabledJoint, _super);
  81430. function MotorEnabledJoint(type, jointData) {
  81431. return _super.call(this, type, jointData) || this;
  81432. }
  81433. /**
  81434. * Set the motor values.
  81435. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81436. * @param {number} force the force to apply
  81437. * @param {number} maxForce max force for this motor.
  81438. */
  81439. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81440. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81441. };
  81442. /**
  81443. * Set the motor's limits.
  81444. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81445. */
  81446. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81447. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81448. };
  81449. return MotorEnabledJoint;
  81450. }(PhysicsJoint));
  81451. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81452. /**
  81453. * This class represents a single hinge physics joint
  81454. */
  81455. var HingeJoint = /** @class */ (function (_super) {
  81456. __extends(HingeJoint, _super);
  81457. function HingeJoint(jointData) {
  81458. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81459. }
  81460. /**
  81461. * Set the motor values.
  81462. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81463. * @param {number} force the force to apply
  81464. * @param {number} maxForce max force for this motor.
  81465. */
  81466. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81467. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81468. };
  81469. /**
  81470. * Set the motor's limits.
  81471. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81472. */
  81473. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81474. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81475. };
  81476. return HingeJoint;
  81477. }(MotorEnabledJoint));
  81478. BABYLON.HingeJoint = HingeJoint;
  81479. /**
  81480. * This class represents a dual hinge physics joint (same as wheel joint)
  81481. */
  81482. var Hinge2Joint = /** @class */ (function (_super) {
  81483. __extends(Hinge2Joint, _super);
  81484. function Hinge2Joint(jointData) {
  81485. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81486. }
  81487. /**
  81488. * Set the motor values.
  81489. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81490. * @param {number} force the force to apply
  81491. * @param {number} maxForce max force for this motor.
  81492. * @param {motorIndex} the motor's index, 0 or 1.
  81493. */
  81494. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81495. if (motorIndex === void 0) { motorIndex = 0; }
  81496. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81497. };
  81498. /**
  81499. * Set the motor limits.
  81500. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81501. * @param {number} upperLimit the upper limit
  81502. * @param {number} lowerLimit lower limit
  81503. * @param {motorIndex} the motor's index, 0 or 1.
  81504. */
  81505. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81506. if (motorIndex === void 0) { motorIndex = 0; }
  81507. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81508. };
  81509. return Hinge2Joint;
  81510. }(MotorEnabledJoint));
  81511. BABYLON.Hinge2Joint = Hinge2Joint;
  81512. })(BABYLON || (BABYLON = {}));
  81513. //# sourceMappingURL=babylon.physicsJoint.js.map
  81514. var BABYLON;
  81515. (function (BABYLON) {
  81516. var PhysicsImpostor = /** @class */ (function () {
  81517. function PhysicsImpostor(object, type, _options, _scene) {
  81518. if (_options === void 0) { _options = { mass: 0 }; }
  81519. var _this = this;
  81520. this.object = object;
  81521. this.type = type;
  81522. this._options = _options;
  81523. this._scene = _scene;
  81524. this._bodyUpdateRequired = false;
  81525. this._onBeforePhysicsStepCallbacks = new Array();
  81526. this._onAfterPhysicsStepCallbacks = new Array();
  81527. this._onPhysicsCollideCallbacks = [];
  81528. this._deltaPosition = BABYLON.Vector3.Zero();
  81529. this._isDisposed = false;
  81530. //temp variables for parent rotation calculations
  81531. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81532. this._tmpQuat = new BABYLON.Quaternion();
  81533. this._tmpQuat2 = new BABYLON.Quaternion();
  81534. /**
  81535. * this function is executed by the physics engine.
  81536. */
  81537. this.beforeStep = function () {
  81538. if (!_this._physicsEngine) {
  81539. return;
  81540. }
  81541. _this.object.translate(_this._deltaPosition, -1);
  81542. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81543. _this.object.computeWorldMatrix(false);
  81544. if (_this.object.parent && _this.object.rotationQuaternion) {
  81545. _this.getParentsRotation();
  81546. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81547. }
  81548. else {
  81549. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81550. }
  81551. if (!_this._options.disableBidirectionalTransformation) {
  81552. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81553. }
  81554. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81555. func(_this);
  81556. });
  81557. };
  81558. /**
  81559. * this function is executed by the physics engine.
  81560. */
  81561. this.afterStep = function () {
  81562. if (!_this._physicsEngine) {
  81563. return;
  81564. }
  81565. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81566. func(_this);
  81567. });
  81568. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81569. // object has now its world rotation. needs to be converted to local.
  81570. if (_this.object.parent && _this.object.rotationQuaternion) {
  81571. _this.getParentsRotation();
  81572. _this._tmpQuat.conjugateInPlace();
  81573. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81574. }
  81575. // take the position set and make it the absolute position of this object.
  81576. _this.object.setAbsolutePosition(_this.object.position);
  81577. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81578. _this.object.translate(_this._deltaPosition, 1);
  81579. };
  81580. /**
  81581. * Legacy collision detection event support
  81582. */
  81583. this.onCollideEvent = null;
  81584. //event and body object due to cannon's event-based architecture.
  81585. this.onCollide = function (e) {
  81586. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81587. return;
  81588. }
  81589. if (!_this._physicsEngine) {
  81590. return;
  81591. }
  81592. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81593. if (otherImpostor) {
  81594. // Legacy collision detection event support
  81595. if (_this.onCollideEvent) {
  81596. _this.onCollideEvent(_this, otherImpostor);
  81597. }
  81598. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81599. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81600. }).forEach(function (obj) {
  81601. obj.callback(_this, otherImpostor);
  81602. });
  81603. }
  81604. };
  81605. //sanity check!
  81606. if (!this.object) {
  81607. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81608. return;
  81609. }
  81610. //legacy support for old syntax.
  81611. if (!this._scene && object.getScene) {
  81612. this._scene = object.getScene();
  81613. }
  81614. if (!this._scene) {
  81615. return;
  81616. }
  81617. this._physicsEngine = this._scene.getPhysicsEngine();
  81618. if (!this._physicsEngine) {
  81619. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81620. }
  81621. else {
  81622. //set the object's quaternion, if not set
  81623. if (!this.object.rotationQuaternion) {
  81624. if (this.object.rotation) {
  81625. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81626. }
  81627. else {
  81628. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81629. }
  81630. }
  81631. //default options params
  81632. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81633. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81634. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81635. this._joints = [];
  81636. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81637. if (!this.object.parent || this._options.ignoreParent) {
  81638. this._init();
  81639. }
  81640. else if (this.object.parent.physicsImpostor) {
  81641. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81642. }
  81643. }
  81644. }
  81645. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81646. get: function () {
  81647. return this._isDisposed;
  81648. },
  81649. enumerable: true,
  81650. configurable: true
  81651. });
  81652. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81653. get: function () {
  81654. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81655. },
  81656. set: function (value) {
  81657. this.setMass(value);
  81658. },
  81659. enumerable: true,
  81660. configurable: true
  81661. });
  81662. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81663. get: function () {
  81664. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81665. },
  81666. set: function (value) {
  81667. if (!this._physicsEngine) {
  81668. return;
  81669. }
  81670. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81671. },
  81672. enumerable: true,
  81673. configurable: true
  81674. });
  81675. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81676. get: function () {
  81677. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81678. },
  81679. set: function (value) {
  81680. if (!this._physicsEngine) {
  81681. return;
  81682. }
  81683. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81684. },
  81685. enumerable: true,
  81686. configurable: true
  81687. });
  81688. /**
  81689. * This function will completly initialize this impostor.
  81690. * It will create a new body - but only if this mesh has no parent.
  81691. * If it has, this impostor will not be used other than to define the impostor
  81692. * of the child mesh.
  81693. */
  81694. PhysicsImpostor.prototype._init = function () {
  81695. if (!this._physicsEngine) {
  81696. return;
  81697. }
  81698. this._physicsEngine.removeImpostor(this);
  81699. this.physicsBody = null;
  81700. this._parent = this._parent || this._getPhysicsParent();
  81701. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81702. this._physicsEngine.addImpostor(this);
  81703. }
  81704. };
  81705. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81706. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81707. var parentMesh = this.object.parent;
  81708. return parentMesh.physicsImpostor;
  81709. }
  81710. return null;
  81711. };
  81712. /**
  81713. * Should a new body be generated.
  81714. */
  81715. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81716. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81717. };
  81718. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81719. this.forceUpdate();
  81720. };
  81721. /**
  81722. * Force a regeneration of this or the parent's impostor's body.
  81723. * Use under cautious - This will remove all joints already implemented.
  81724. */
  81725. PhysicsImpostor.prototype.forceUpdate = function () {
  81726. this._init();
  81727. if (this.parent && !this._options.ignoreParent) {
  81728. this.parent.forceUpdate();
  81729. }
  81730. };
  81731. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81732. /*public get mesh(): AbstractMesh {
  81733. return this._mesh;
  81734. }*/
  81735. /**
  81736. * Gets the body that holds this impostor. Either its own, or its parent.
  81737. */
  81738. get: function () {
  81739. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81740. },
  81741. /**
  81742. * Set the physics body. Used mainly by the physics engine/plugin
  81743. */
  81744. set: function (physicsBody) {
  81745. if (this._physicsBody && this._physicsEngine) {
  81746. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81747. }
  81748. this._physicsBody = physicsBody;
  81749. this.resetUpdateFlags();
  81750. },
  81751. enumerable: true,
  81752. configurable: true
  81753. });
  81754. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81755. get: function () {
  81756. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81757. },
  81758. set: function (value) {
  81759. this._parent = value;
  81760. },
  81761. enumerable: true,
  81762. configurable: true
  81763. });
  81764. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81765. this._bodyUpdateRequired = false;
  81766. };
  81767. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81768. if (this.object.getBoundingInfo) {
  81769. var q = this.object.rotationQuaternion;
  81770. //reset rotation
  81771. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81772. //calculate the world matrix with no rotation
  81773. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81774. var boundingInfo = this.object.getBoundingInfo();
  81775. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81776. //bring back the rotation
  81777. this.object.rotationQuaternion = q;
  81778. //calculate the world matrix with the new rotation
  81779. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81780. return size;
  81781. }
  81782. else {
  81783. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81784. }
  81785. };
  81786. PhysicsImpostor.prototype.getObjectCenter = function () {
  81787. if (this.object.getBoundingInfo) {
  81788. var boundingInfo = this.object.getBoundingInfo();
  81789. return boundingInfo.boundingBox.centerWorld;
  81790. }
  81791. else {
  81792. return this.object.position;
  81793. }
  81794. };
  81795. /**
  81796. * Get a specific parametes from the options parameter.
  81797. */
  81798. PhysicsImpostor.prototype.getParam = function (paramName) {
  81799. return this._options[paramName];
  81800. };
  81801. /**
  81802. * Sets a specific parameter in the options given to the physics plugin
  81803. */
  81804. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81805. this._options[paramName] = value;
  81806. this._bodyUpdateRequired = true;
  81807. };
  81808. /**
  81809. * Specifically change the body's mass option. Won't recreate the physics body object
  81810. */
  81811. PhysicsImpostor.prototype.setMass = function (mass) {
  81812. if (this.getParam("mass") !== mass) {
  81813. this.setParam("mass", mass);
  81814. }
  81815. if (this._physicsEngine) {
  81816. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81817. }
  81818. };
  81819. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81820. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81821. };
  81822. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81823. if (this._physicsEngine) {
  81824. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81825. }
  81826. };
  81827. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81828. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81829. };
  81830. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81831. if (this._physicsEngine) {
  81832. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81833. }
  81834. };
  81835. /**
  81836. * Execute a function with the physics plugin native code.
  81837. * Provide a function the will have two variables - the world object and the physics body object.
  81838. */
  81839. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81840. if (this._physicsEngine) {
  81841. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81842. }
  81843. };
  81844. /**
  81845. * Register a function that will be executed before the physics world is stepping forward.
  81846. */
  81847. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81848. this._onBeforePhysicsStepCallbacks.push(func);
  81849. };
  81850. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81851. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81852. if (index > -1) {
  81853. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81854. }
  81855. else {
  81856. BABYLON.Tools.Warn("Function to remove was not found");
  81857. }
  81858. };
  81859. /**
  81860. * Register a function that will be executed after the physics step
  81861. */
  81862. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81863. this._onAfterPhysicsStepCallbacks.push(func);
  81864. };
  81865. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81866. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81867. if (index > -1) {
  81868. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81869. }
  81870. else {
  81871. BABYLON.Tools.Warn("Function to remove was not found");
  81872. }
  81873. };
  81874. /**
  81875. * register a function that will be executed when this impostor collides against a different body.
  81876. */
  81877. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81878. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81879. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81880. };
  81881. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81882. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81883. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81884. if (index > -1) {
  81885. this._onPhysicsCollideCallbacks.splice(index, 1);
  81886. }
  81887. else {
  81888. BABYLON.Tools.Warn("Function to remove was not found");
  81889. }
  81890. };
  81891. PhysicsImpostor.prototype.getParentsRotation = function () {
  81892. var parent = this.object.parent;
  81893. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  81894. while (parent) {
  81895. if (parent.rotationQuaternion) {
  81896. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  81897. }
  81898. else {
  81899. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  81900. }
  81901. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  81902. parent = parent.parent;
  81903. }
  81904. return this._tmpQuat;
  81905. };
  81906. /**
  81907. * Apply a force
  81908. */
  81909. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  81910. if (this._physicsEngine) {
  81911. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  81912. }
  81913. return this;
  81914. };
  81915. /**
  81916. * Apply an impulse
  81917. */
  81918. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  81919. if (this._physicsEngine) {
  81920. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  81921. }
  81922. return this;
  81923. };
  81924. /**
  81925. * A help function to create a joint.
  81926. */
  81927. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  81928. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  81929. this.addJoint(otherImpostor, joint);
  81930. return this;
  81931. };
  81932. /**
  81933. * Add a joint to this impostor with a different impostor.
  81934. */
  81935. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  81936. this._joints.push({
  81937. otherImpostor: otherImpostor,
  81938. joint: joint
  81939. });
  81940. if (this._physicsEngine) {
  81941. this._physicsEngine.addJoint(this, otherImpostor, joint);
  81942. }
  81943. return this;
  81944. };
  81945. /**
  81946. * Will keep this body still, in a sleep mode.
  81947. */
  81948. PhysicsImpostor.prototype.sleep = function () {
  81949. if (this._physicsEngine) {
  81950. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  81951. }
  81952. return this;
  81953. };
  81954. /**
  81955. * Wake the body up.
  81956. */
  81957. PhysicsImpostor.prototype.wakeUp = function () {
  81958. if (this._physicsEngine) {
  81959. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  81960. }
  81961. return this;
  81962. };
  81963. PhysicsImpostor.prototype.clone = function (newObject) {
  81964. if (!newObject)
  81965. return null;
  81966. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  81967. };
  81968. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  81969. var _this = this;
  81970. //no dispose if no physics engine is available.
  81971. if (!this._physicsEngine) {
  81972. return;
  81973. }
  81974. this._joints.forEach(function (j) {
  81975. if (_this._physicsEngine) {
  81976. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  81977. }
  81978. });
  81979. //dispose the physics body
  81980. this._physicsEngine.removeImpostor(this);
  81981. if (this.parent) {
  81982. this.parent.forceUpdate();
  81983. }
  81984. else {
  81985. /*this._object.getChildMeshes().forEach(function(mesh) {
  81986. if (mesh.physicsImpostor) {
  81987. if (disposeChildren) {
  81988. mesh.physicsImpostor.dispose();
  81989. mesh.physicsImpostor = null;
  81990. }
  81991. }
  81992. })*/
  81993. }
  81994. this._isDisposed = true;
  81995. };
  81996. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  81997. this._deltaPosition.copyFrom(position);
  81998. };
  81999. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82000. if (!this._deltaRotation) {
  82001. this._deltaRotation = new BABYLON.Quaternion();
  82002. }
  82003. this._deltaRotation.copyFrom(rotation);
  82004. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82005. };
  82006. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82007. if (this._physicsEngine) {
  82008. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82009. }
  82010. return this;
  82011. };
  82012. PhysicsImpostor.prototype.getRadius = function () {
  82013. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82014. };
  82015. /**
  82016. * Sync a bone with this impostor
  82017. * @param bone The bone to sync to the impostor.
  82018. * @param boneMesh The mesh that the bone is influencing.
  82019. * @param jointPivot The pivot of the joint / bone in local space.
  82020. * @param distToJoint Optional distance from the impostor to the joint.
  82021. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82022. */
  82023. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82024. var tempVec = PhysicsImpostor._tmpVecs[0];
  82025. var mesh = this.object;
  82026. if (mesh.rotationQuaternion) {
  82027. if (adjustRotation) {
  82028. var tempQuat = PhysicsImpostor._tmpQuat;
  82029. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82030. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82031. }
  82032. else {
  82033. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82034. }
  82035. }
  82036. tempVec.x = 0;
  82037. tempVec.y = 0;
  82038. tempVec.z = 0;
  82039. if (jointPivot) {
  82040. tempVec.x = jointPivot.x;
  82041. tempVec.y = jointPivot.y;
  82042. tempVec.z = jointPivot.z;
  82043. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82044. if (distToJoint === undefined || distToJoint === null) {
  82045. distToJoint = jointPivot.length();
  82046. }
  82047. tempVec.x *= distToJoint;
  82048. tempVec.y *= distToJoint;
  82049. tempVec.z *= distToJoint;
  82050. }
  82051. if (bone.getParent()) {
  82052. tempVec.addInPlace(mesh.getAbsolutePosition());
  82053. bone.setAbsolutePosition(tempVec, boneMesh);
  82054. }
  82055. else {
  82056. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82057. boneMesh.position.x -= tempVec.x;
  82058. boneMesh.position.y -= tempVec.y;
  82059. boneMesh.position.z -= tempVec.z;
  82060. }
  82061. };
  82062. /**
  82063. * Sync impostor to a bone
  82064. * @param bone The bone that the impostor will be synced to.
  82065. * @param boneMesh The mesh that the bone is influencing.
  82066. * @param jointPivot The pivot of the joint / bone in local space.
  82067. * @param distToJoint Optional distance from the impostor to the joint.
  82068. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82069. * @param boneAxis Optional vector3 axis the bone is aligned with
  82070. */
  82071. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82072. var mesh = this.object;
  82073. if (mesh.rotationQuaternion) {
  82074. if (adjustRotation) {
  82075. var tempQuat = PhysicsImpostor._tmpQuat;
  82076. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82077. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82078. }
  82079. else {
  82080. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82081. }
  82082. }
  82083. var pos = PhysicsImpostor._tmpVecs[0];
  82084. var boneDir = PhysicsImpostor._tmpVecs[1];
  82085. if (!boneAxis) {
  82086. boneAxis = PhysicsImpostor._tmpVecs[2];
  82087. boneAxis.x = 0;
  82088. boneAxis.y = 1;
  82089. boneAxis.z = 0;
  82090. }
  82091. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82092. bone.getAbsolutePositionToRef(boneMesh, pos);
  82093. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82094. distToJoint = jointPivot.length();
  82095. }
  82096. if (distToJoint !== undefined && distToJoint !== null) {
  82097. pos.x += boneDir.x * distToJoint;
  82098. pos.y += boneDir.y * distToJoint;
  82099. pos.z += boneDir.z * distToJoint;
  82100. }
  82101. mesh.setAbsolutePosition(pos);
  82102. };
  82103. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82104. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82105. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82106. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82107. //Impostor types
  82108. PhysicsImpostor.NoImpostor = 0;
  82109. PhysicsImpostor.SphereImpostor = 1;
  82110. PhysicsImpostor.BoxImpostor = 2;
  82111. PhysicsImpostor.PlaneImpostor = 3;
  82112. PhysicsImpostor.MeshImpostor = 4;
  82113. PhysicsImpostor.CylinderImpostor = 7;
  82114. PhysicsImpostor.ParticleImpostor = 8;
  82115. PhysicsImpostor.HeightmapImpostor = 9;
  82116. return PhysicsImpostor;
  82117. }());
  82118. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82119. })(BABYLON || (BABYLON = {}));
  82120. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82121. var BABYLON;
  82122. (function (BABYLON) {
  82123. var PhysicsEngine = /** @class */ (function () {
  82124. function PhysicsEngine(gravity, _physicsPlugin) {
  82125. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82126. this._physicsPlugin = _physicsPlugin;
  82127. //new methods and parameters
  82128. this._impostors = [];
  82129. this._joints = [];
  82130. if (!this._physicsPlugin.isSupported()) {
  82131. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82132. + "Please make sure it is included.");
  82133. }
  82134. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82135. this.setGravity(gravity);
  82136. this.setTimeStep();
  82137. }
  82138. PhysicsEngine.prototype.setGravity = function (gravity) {
  82139. this.gravity = gravity;
  82140. this._physicsPlugin.setGravity(this.gravity);
  82141. };
  82142. /**
  82143. * Set the time step of the physics engine.
  82144. * default is 1/60.
  82145. * To slow it down, enter 1/600 for example.
  82146. * To speed it up, 1/30
  82147. * @param {number} newTimeStep the new timestep to apply to this world.
  82148. */
  82149. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82150. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82151. this._physicsPlugin.setTimeStep(newTimeStep);
  82152. };
  82153. /**
  82154. * Get the time step of the physics engine.
  82155. */
  82156. PhysicsEngine.prototype.getTimeStep = function () {
  82157. return this._physicsPlugin.getTimeStep();
  82158. };
  82159. PhysicsEngine.prototype.dispose = function () {
  82160. this._impostors.forEach(function (impostor) {
  82161. impostor.dispose();
  82162. });
  82163. this._physicsPlugin.dispose();
  82164. };
  82165. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82166. return this._physicsPlugin.name;
  82167. };
  82168. /**
  82169. * Adding a new impostor for the impostor tracking.
  82170. * This will be done by the impostor itself.
  82171. * @param {PhysicsImpostor} impostor the impostor to add
  82172. */
  82173. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82174. impostor.uniqueId = this._impostors.push(impostor);
  82175. //if no parent, generate the body
  82176. if (!impostor.parent) {
  82177. this._physicsPlugin.generatePhysicsBody(impostor);
  82178. }
  82179. };
  82180. /**
  82181. * Remove an impostor from the engine.
  82182. * This impostor and its mesh will not longer be updated by the physics engine.
  82183. * @param {PhysicsImpostor} impostor the impostor to remove
  82184. */
  82185. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82186. var index = this._impostors.indexOf(impostor);
  82187. if (index > -1) {
  82188. var removed = this._impostors.splice(index, 1);
  82189. //Is it needed?
  82190. if (removed.length) {
  82191. //this will also remove it from the world.
  82192. removed[0].physicsBody = null;
  82193. }
  82194. }
  82195. };
  82196. /**
  82197. * Add a joint to the physics engine
  82198. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82199. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82200. * @param {PhysicsJoint} the joint that will connect both impostors.
  82201. */
  82202. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82203. var impostorJoint = {
  82204. mainImpostor: mainImpostor,
  82205. connectedImpostor: connectedImpostor,
  82206. joint: joint
  82207. };
  82208. joint.physicsPlugin = this._physicsPlugin;
  82209. this._joints.push(impostorJoint);
  82210. this._physicsPlugin.generateJoint(impostorJoint);
  82211. };
  82212. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82213. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82214. return (impostorJoint.connectedImpostor === connectedImpostor
  82215. && impostorJoint.joint === joint
  82216. && impostorJoint.mainImpostor === mainImpostor);
  82217. });
  82218. if (matchingJoints.length) {
  82219. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82220. //TODO remove it from the list as well
  82221. }
  82222. };
  82223. /**
  82224. * Called by the scene. no need to call it.
  82225. */
  82226. PhysicsEngine.prototype._step = function (delta) {
  82227. var _this = this;
  82228. //check if any mesh has no body / requires an update
  82229. this._impostors.forEach(function (impostor) {
  82230. if (impostor.isBodyInitRequired()) {
  82231. _this._physicsPlugin.generatePhysicsBody(impostor);
  82232. }
  82233. });
  82234. if (delta > 0.1) {
  82235. delta = 0.1;
  82236. }
  82237. else if (delta <= 0) {
  82238. delta = 1.0 / 60.0;
  82239. }
  82240. this._physicsPlugin.executeStep(delta, this._impostors);
  82241. };
  82242. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82243. return this._physicsPlugin;
  82244. };
  82245. PhysicsEngine.prototype.getImpostors = function () {
  82246. return this._impostors;
  82247. };
  82248. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82249. for (var i = 0; i < this._impostors.length; ++i) {
  82250. if (this._impostors[i].object === object) {
  82251. return this._impostors[i];
  82252. }
  82253. }
  82254. return null;
  82255. };
  82256. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82257. for (var i = 0; i < this._impostors.length; ++i) {
  82258. if (this._impostors[i].physicsBody === body) {
  82259. return this._impostors[i];
  82260. }
  82261. }
  82262. return null;
  82263. };
  82264. // Statics
  82265. PhysicsEngine.Epsilon = 0.001;
  82266. return PhysicsEngine;
  82267. }());
  82268. BABYLON.PhysicsEngine = PhysicsEngine;
  82269. })(BABYLON || (BABYLON = {}));
  82270. //# sourceMappingURL=babylon.physicsEngine.js.map
  82271. var BABYLON;
  82272. (function (BABYLON) {
  82273. var PhysicsHelper = /** @class */ (function () {
  82274. function PhysicsHelper(scene) {
  82275. this._scene = scene;
  82276. this._physicsEngine = this._scene.getPhysicsEngine();
  82277. if (!this._physicsEngine) {
  82278. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82279. }
  82280. }
  82281. /**
  82282. * @param {Vector3} origin the origin of the explosion
  82283. * @param {number} radius the explosion radius
  82284. * @param {number} strength the explosion strength
  82285. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82286. */
  82287. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82288. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82289. if (!this._physicsEngine) {
  82290. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82291. return null;
  82292. }
  82293. var impostors = this._physicsEngine.getImpostors();
  82294. if (impostors.length === 0) {
  82295. return null;
  82296. }
  82297. var event = new PhysicsRadialExplosionEvent(this._scene);
  82298. impostors.forEach(function (impostor) {
  82299. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82300. if (!impostorForceAndContactPoint) {
  82301. return;
  82302. }
  82303. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82304. });
  82305. event.dispose(false);
  82306. return event;
  82307. };
  82308. /**
  82309. * @param {Vector3} origin the origin of the explosion
  82310. * @param {number} radius the explosion radius
  82311. * @param {number} strength the explosion strength
  82312. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82313. */
  82314. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82315. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82316. if (!this._physicsEngine) {
  82317. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82318. return null;
  82319. }
  82320. var impostors = this._physicsEngine.getImpostors();
  82321. if (impostors.length === 0) {
  82322. return null;
  82323. }
  82324. var event = new PhysicsRadialExplosionEvent(this._scene);
  82325. impostors.forEach(function (impostor) {
  82326. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82327. if (!impostorForceAndContactPoint) {
  82328. return;
  82329. }
  82330. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82331. });
  82332. event.dispose(false);
  82333. return event;
  82334. };
  82335. /**
  82336. * @param {Vector3} origin the origin of the explosion
  82337. * @param {number} radius the explosion radius
  82338. * @param {number} strength the explosion strength
  82339. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82340. */
  82341. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82342. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82343. if (!this._physicsEngine) {
  82344. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82345. return null;
  82346. }
  82347. var impostors = this._physicsEngine.getImpostors();
  82348. if (impostors.length === 0) {
  82349. return null;
  82350. }
  82351. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82352. event.dispose(false);
  82353. return event;
  82354. };
  82355. /**
  82356. * @param {Vector3} origin the origin of the updraft
  82357. * @param {number} radius the radius of the updraft
  82358. * @param {number} strength the strength of the updraft
  82359. * @param {number} height the height of the updraft
  82360. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82361. */
  82362. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82363. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82364. if (!this._physicsEngine) {
  82365. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82366. return null;
  82367. }
  82368. if (this._physicsEngine.getImpostors().length === 0) {
  82369. return null;
  82370. }
  82371. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82372. event.dispose(false);
  82373. return event;
  82374. };
  82375. /**
  82376. * @param {Vector3} origin the of the vortex
  82377. * @param {number} radius the radius of the vortex
  82378. * @param {number} strength the strength of the vortex
  82379. * @param {number} height the height of the vortex
  82380. */
  82381. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82382. if (!this._physicsEngine) {
  82383. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82384. return null;
  82385. }
  82386. if (this._physicsEngine.getImpostors().length === 0) {
  82387. return null;
  82388. }
  82389. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82390. event.dispose(false);
  82391. return event;
  82392. };
  82393. return PhysicsHelper;
  82394. }());
  82395. BABYLON.PhysicsHelper = PhysicsHelper;
  82396. /***** Radial explosion *****/
  82397. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82398. function PhysicsRadialExplosionEvent(scene) {
  82399. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82400. this._rays = [];
  82401. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82402. this._scene = scene;
  82403. }
  82404. /**
  82405. * Returns the data related to the radial explosion event (sphere & rays).
  82406. * @returns {PhysicsRadialExplosionEventData}
  82407. */
  82408. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82409. this._dataFetched = true;
  82410. return {
  82411. sphere: this._sphere,
  82412. rays: this._rays,
  82413. };
  82414. };
  82415. /**
  82416. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82417. * @param impostor
  82418. * @param {Vector3} origin the origin of the explosion
  82419. * @param {number} radius the explosion radius
  82420. * @param {number} strength the explosion strength
  82421. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82422. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82423. */
  82424. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82425. if (impostor.mass === 0) {
  82426. return null;
  82427. }
  82428. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82429. return null;
  82430. }
  82431. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82432. return null;
  82433. }
  82434. var impostorObjectCenter = impostor.getObjectCenter();
  82435. var direction = impostorObjectCenter.subtract(origin);
  82436. var ray = new BABYLON.Ray(origin, direction, radius);
  82437. this._rays.push(ray);
  82438. var hit = ray.intersectsMesh(impostor.object);
  82439. var contactPoint = hit.pickedPoint;
  82440. if (!contactPoint) {
  82441. return null;
  82442. }
  82443. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82444. if (distanceFromOrigin > radius) {
  82445. return null;
  82446. }
  82447. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82448. ? strength
  82449. : strength * (1 - (distanceFromOrigin / radius));
  82450. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82451. return { force: force, contactPoint: contactPoint };
  82452. };
  82453. /**
  82454. * Disposes the sphere.
  82455. * @param {bolean} force
  82456. */
  82457. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82458. var _this = this;
  82459. if (force === void 0) { force = true; }
  82460. if (force) {
  82461. this._sphere.dispose();
  82462. }
  82463. else {
  82464. setTimeout(function () {
  82465. if (!_this._dataFetched) {
  82466. _this._sphere.dispose();
  82467. }
  82468. }, 0);
  82469. }
  82470. };
  82471. /*** Helpers ***/
  82472. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82473. if (!this._sphere) {
  82474. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82475. this._sphere.isVisible = false;
  82476. }
  82477. };
  82478. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82479. var impostorObject = impostor.object;
  82480. this._prepareSphere();
  82481. this._sphere.position = origin;
  82482. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82483. this._sphere._updateBoundingInfo();
  82484. this._sphere.computeWorldMatrix(true);
  82485. return this._sphere.intersectsMesh(impostorObject, true);
  82486. };
  82487. return PhysicsRadialExplosionEvent;
  82488. }());
  82489. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82490. /***** Gravitational Field *****/
  82491. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82492. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82493. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82494. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82495. this._physicsHelper = physicsHelper;
  82496. this._scene = scene;
  82497. this._origin = origin;
  82498. this._radius = radius;
  82499. this._strength = strength;
  82500. this._falloff = falloff;
  82501. this._tickCallback = this._tick.bind(this);
  82502. }
  82503. /**
  82504. * Returns the data related to the gravitational field event (sphere).
  82505. * @returns {PhysicsGravitationalFieldEventData}
  82506. */
  82507. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82508. this._dataFetched = true;
  82509. return {
  82510. sphere: this._sphere,
  82511. };
  82512. };
  82513. /**
  82514. * Enables the gravitational field.
  82515. */
  82516. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82517. this._tickCallback.call(this);
  82518. this._scene.registerBeforeRender(this._tickCallback);
  82519. };
  82520. /**
  82521. * Disables the gravitational field.
  82522. */
  82523. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82524. this._scene.unregisterBeforeRender(this._tickCallback);
  82525. };
  82526. /**
  82527. * Disposes the sphere.
  82528. * @param {bolean} force
  82529. */
  82530. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82531. var _this = this;
  82532. if (force === void 0) { force = true; }
  82533. if (force) {
  82534. this._sphere.dispose();
  82535. }
  82536. else {
  82537. setTimeout(function () {
  82538. if (!_this._dataFetched) {
  82539. _this._sphere.dispose();
  82540. }
  82541. }, 0);
  82542. }
  82543. };
  82544. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82545. // Since the params won't change, we fetch the event only once
  82546. if (this._sphere) {
  82547. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82548. }
  82549. else {
  82550. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82551. if (radialExplosionEvent) {
  82552. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82553. }
  82554. }
  82555. };
  82556. return PhysicsGravitationalFieldEvent;
  82557. }());
  82558. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82559. /***** Updraft *****/
  82560. var PhysicsUpdraftEvent = /** @class */ (function () {
  82561. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82562. this._scene = _scene;
  82563. this._origin = _origin;
  82564. this._radius = _radius;
  82565. this._strength = _strength;
  82566. this._height = _height;
  82567. this._updraftMode = _updraftMode;
  82568. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82569. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82570. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82571. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82572. this._physicsEngine = this._scene.getPhysicsEngine();
  82573. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82574. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82575. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82576. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82577. }
  82578. this._tickCallback = this._tick.bind(this);
  82579. }
  82580. /**
  82581. * Returns the data related to the updraft event (cylinder).
  82582. * @returns {PhysicsUpdraftEventData}
  82583. */
  82584. PhysicsUpdraftEvent.prototype.getData = function () {
  82585. this._dataFetched = true;
  82586. return {
  82587. cylinder: this._cylinder,
  82588. };
  82589. };
  82590. /**
  82591. * Enables the updraft.
  82592. */
  82593. PhysicsUpdraftEvent.prototype.enable = function () {
  82594. this._tickCallback.call(this);
  82595. this._scene.registerBeforeRender(this._tickCallback);
  82596. };
  82597. /**
  82598. * Disables the cortex.
  82599. */
  82600. PhysicsUpdraftEvent.prototype.disable = function () {
  82601. this._scene.unregisterBeforeRender(this._tickCallback);
  82602. };
  82603. /**
  82604. * Disposes the sphere.
  82605. * @param {bolean} force
  82606. */
  82607. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82608. var _this = this;
  82609. if (force === void 0) { force = true; }
  82610. if (force) {
  82611. this._cylinder.dispose();
  82612. }
  82613. else {
  82614. setTimeout(function () {
  82615. if (!_this._dataFetched) {
  82616. _this._cylinder.dispose();
  82617. }
  82618. }, 0);
  82619. }
  82620. };
  82621. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82622. if (impostor.mass === 0) {
  82623. return null;
  82624. }
  82625. if (!this._intersectsWithCylinder(impostor)) {
  82626. return null;
  82627. }
  82628. var impostorObjectCenter = impostor.getObjectCenter();
  82629. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82630. var direction = this._originDirection;
  82631. }
  82632. else {
  82633. var direction = impostorObjectCenter.subtract(this._originTop);
  82634. }
  82635. var multiplier = this._strength * -1;
  82636. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82637. return { force: force, contactPoint: impostorObjectCenter };
  82638. };
  82639. PhysicsUpdraftEvent.prototype._tick = function () {
  82640. var _this = this;
  82641. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82642. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82643. if (!impostorForceAndContactPoint) {
  82644. return;
  82645. }
  82646. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82647. });
  82648. };
  82649. /*** Helpers ***/
  82650. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82651. if (!this._cylinder) {
  82652. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82653. height: this._height,
  82654. diameter: this._radius * 2,
  82655. }, this._scene);
  82656. this._cylinder.isVisible = false;
  82657. }
  82658. };
  82659. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82660. var impostorObject = impostor.object;
  82661. this._prepareCylinder();
  82662. this._cylinder.position = this._cylinderPosition;
  82663. return this._cylinder.intersectsMesh(impostorObject, true);
  82664. };
  82665. return PhysicsUpdraftEvent;
  82666. }());
  82667. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82668. /***** Vortex *****/
  82669. var PhysicsVortexEvent = /** @class */ (function () {
  82670. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82671. this._scene = _scene;
  82672. this._origin = _origin;
  82673. this._radius = _radius;
  82674. this._strength = _strength;
  82675. this._height = _height;
  82676. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82677. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82678. this._updraftMultiplier = 0.02;
  82679. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82680. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82681. this._physicsEngine = this._scene.getPhysicsEngine();
  82682. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82683. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82684. this._tickCallback = this._tick.bind(this);
  82685. }
  82686. /**
  82687. * Returns the data related to the vortex event (cylinder).
  82688. * @returns {PhysicsVortexEventData}
  82689. */
  82690. PhysicsVortexEvent.prototype.getData = function () {
  82691. this._dataFetched = true;
  82692. return {
  82693. cylinder: this._cylinder,
  82694. };
  82695. };
  82696. /**
  82697. * Enables the vortex.
  82698. */
  82699. PhysicsVortexEvent.prototype.enable = function () {
  82700. this._tickCallback.call(this);
  82701. this._scene.registerBeforeRender(this._tickCallback);
  82702. };
  82703. /**
  82704. * Disables the cortex.
  82705. */
  82706. PhysicsVortexEvent.prototype.disable = function () {
  82707. this._scene.unregisterBeforeRender(this._tickCallback);
  82708. };
  82709. /**
  82710. * Disposes the sphere.
  82711. * @param {bolean} force
  82712. */
  82713. PhysicsVortexEvent.prototype.dispose = function (force) {
  82714. var _this = this;
  82715. if (force === void 0) { force = true; }
  82716. if (force) {
  82717. this._cylinder.dispose();
  82718. }
  82719. else {
  82720. setTimeout(function () {
  82721. if (!_this._dataFetched) {
  82722. _this._cylinder.dispose();
  82723. }
  82724. }, 0);
  82725. }
  82726. };
  82727. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82728. if (impostor.mass === 0) {
  82729. return null;
  82730. }
  82731. if (!this._intersectsWithCylinder(impostor)) {
  82732. return null;
  82733. }
  82734. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82735. return null;
  82736. }
  82737. var impostorObjectCenter = impostor.getObjectCenter();
  82738. 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)
  82739. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82740. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82741. var hit = ray.intersectsMesh(impostor.object);
  82742. var contactPoint = hit.pickedPoint;
  82743. if (!contactPoint) {
  82744. return null;
  82745. }
  82746. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82747. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82748. var directionToOrigin = contactPoint.normalize();
  82749. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82750. directionToOrigin = directionToOrigin.negate();
  82751. }
  82752. // TODO: find a more physically based solution
  82753. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82754. var forceX = directionToOrigin.x * this._strength / 8;
  82755. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82756. var forceZ = directionToOrigin.z * this._strength / 8;
  82757. }
  82758. else {
  82759. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82760. var forceY = this._originTop.y * this._updraftMultiplier;
  82761. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82762. }
  82763. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82764. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82765. return { force: force, contactPoint: impostorObjectCenter };
  82766. };
  82767. PhysicsVortexEvent.prototype._tick = function () {
  82768. var _this = this;
  82769. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82770. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82771. if (!impostorForceAndContactPoint) {
  82772. return;
  82773. }
  82774. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82775. });
  82776. };
  82777. /*** Helpers ***/
  82778. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82779. if (!this._cylinder) {
  82780. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82781. height: this._height,
  82782. diameter: this._radius * 2,
  82783. }, this._scene);
  82784. this._cylinder.isVisible = false;
  82785. }
  82786. };
  82787. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82788. var impostorObject = impostor.object;
  82789. this._prepareCylinder();
  82790. this._cylinder.position = this._cylinderPosition;
  82791. return this._cylinder.intersectsMesh(impostorObject, true);
  82792. };
  82793. return PhysicsVortexEvent;
  82794. }());
  82795. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82796. /***** Enums *****/
  82797. /**
  82798. * The strenght of the force in correspondence to the distance of the affected object
  82799. */
  82800. var PhysicsRadialImpulseFalloff;
  82801. (function (PhysicsRadialImpulseFalloff) {
  82802. /** Defines that impulse is constant in strength across it's whole radius */
  82803. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82804. /** DEfines that impulse gets weaker if it's further from the origin */
  82805. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82806. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82807. /**
  82808. * The strenght of the force in correspondence to the distance of the affected object
  82809. */
  82810. var PhysicsUpdraftMode;
  82811. (function (PhysicsUpdraftMode) {
  82812. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82813. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82814. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82815. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82816. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82817. })(BABYLON || (BABYLON = {}));
  82818. //# sourceMappingURL=babylon.physicsHelper.js.map
  82819. var BABYLON;
  82820. (function (BABYLON) {
  82821. var CannonJSPlugin = /** @class */ (function () {
  82822. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82823. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82824. if (iterations === void 0) { iterations = 10; }
  82825. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82826. this.name = "CannonJSPlugin";
  82827. this._physicsMaterials = new Array();
  82828. this._fixedTimeStep = 1 / 60;
  82829. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82830. this.BJSCANNON = CANNON;
  82831. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82832. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82833. this._tmpPosition = BABYLON.Vector3.Zero();
  82834. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82835. this._tmpUnityRotation = new BABYLON.Quaternion();
  82836. if (!this.isSupported()) {
  82837. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82838. return;
  82839. }
  82840. this._extendNamespace();
  82841. this.world = new this.BJSCANNON.World();
  82842. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82843. this.world.solver.iterations = iterations;
  82844. }
  82845. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82846. this.world.gravity.copy(gravity);
  82847. };
  82848. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82849. this._fixedTimeStep = timeStep;
  82850. };
  82851. CannonJSPlugin.prototype.getTimeStep = function () {
  82852. return this._fixedTimeStep;
  82853. };
  82854. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82855. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82856. };
  82857. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82858. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82859. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82860. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82861. };
  82862. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82863. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82864. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82865. impostor.physicsBody.applyForce(impulse, worldPoint);
  82866. };
  82867. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82868. //parent-child relationship. Does this impostor has a parent impostor?
  82869. if (impostor.parent) {
  82870. if (impostor.physicsBody) {
  82871. this.removePhysicsBody(impostor);
  82872. //TODO is that needed?
  82873. impostor.forceUpdate();
  82874. }
  82875. return;
  82876. }
  82877. //should a new body be created for this impostor?
  82878. if (impostor.isBodyInitRequired()) {
  82879. var shape = this._createShape(impostor);
  82880. //unregister events, if body is being changed
  82881. var oldBody = impostor.physicsBody;
  82882. if (oldBody) {
  82883. this.removePhysicsBody(impostor);
  82884. }
  82885. //create the body and material
  82886. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  82887. var bodyCreationObject = {
  82888. mass: impostor.getParam("mass"),
  82889. material: material
  82890. };
  82891. // A simple extend, in case native options were used.
  82892. var nativeOptions = impostor.getParam("nativeOptions");
  82893. for (var key in nativeOptions) {
  82894. if (nativeOptions.hasOwnProperty(key)) {
  82895. bodyCreationObject[key] = nativeOptions[key];
  82896. }
  82897. }
  82898. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  82899. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  82900. this.world.addEventListener("preStep", impostor.beforeStep);
  82901. this.world.addEventListener("postStep", impostor.afterStep);
  82902. impostor.physicsBody.addShape(shape);
  82903. this.world.add(impostor.physicsBody);
  82904. //try to keep the body moving in the right direction by taking old properties.
  82905. //Should be tested!
  82906. if (oldBody) {
  82907. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  82908. impostor.physicsBody[param].copy(oldBody[param]);
  82909. });
  82910. }
  82911. this._processChildMeshes(impostor);
  82912. }
  82913. //now update the body's transformation
  82914. this._updatePhysicsBodyTransformation(impostor);
  82915. };
  82916. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  82917. var _this = this;
  82918. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  82919. var currentRotation = mainImpostor.object.rotationQuaternion;
  82920. if (meshChildren.length) {
  82921. var processMesh = function (localPosition, mesh) {
  82922. if (!currentRotation || !mesh.rotationQuaternion) {
  82923. return;
  82924. }
  82925. var childImpostor = mesh.getPhysicsImpostor();
  82926. if (childImpostor) {
  82927. var parent = childImpostor.parent;
  82928. if (parent !== mainImpostor) {
  82929. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  82930. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  82931. if (childImpostor.physicsBody) {
  82932. _this.removePhysicsBody(childImpostor);
  82933. childImpostor.physicsBody = null;
  82934. }
  82935. childImpostor.parent = mainImpostor;
  82936. childImpostor.resetUpdateFlags();
  82937. 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));
  82938. //Add the mass of the children.
  82939. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  82940. }
  82941. }
  82942. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  82943. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  82944. };
  82945. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  82946. }
  82947. };
  82948. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82949. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  82950. this.world.removeEventListener("preStep", impostor.beforeStep);
  82951. this.world.removeEventListener("postStep", impostor.afterStep);
  82952. this.world.remove(impostor.physicsBody);
  82953. };
  82954. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82955. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82956. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82957. if (!mainBody || !connectedBody) {
  82958. return;
  82959. }
  82960. var constraint;
  82961. var jointData = impostorJoint.joint.jointData;
  82962. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  82963. var constraintData = {
  82964. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  82965. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  82966. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  82967. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  82968. maxForce: jointData.nativeParams.maxForce,
  82969. collideConnected: !!jointData.collision
  82970. };
  82971. switch (impostorJoint.joint.type) {
  82972. case BABYLON.PhysicsJoint.HingeJoint:
  82973. case BABYLON.PhysicsJoint.Hinge2Joint:
  82974. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  82975. break;
  82976. case BABYLON.PhysicsJoint.DistanceJoint:
  82977. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  82978. break;
  82979. case BABYLON.PhysicsJoint.SpringJoint:
  82980. var springData = jointData;
  82981. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  82982. restLength: springData.length,
  82983. stiffness: springData.stiffness,
  82984. damping: springData.damping,
  82985. localAnchorA: constraintData.pivotA,
  82986. localAnchorB: constraintData.pivotB
  82987. });
  82988. break;
  82989. case BABYLON.PhysicsJoint.LockJoint:
  82990. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  82991. break;
  82992. case BABYLON.PhysicsJoint.PointToPointJoint:
  82993. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82994. default:
  82995. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  82996. break;
  82997. }
  82998. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  82999. constraint.collideConnected = !!jointData.collision;
  83000. impostorJoint.joint.physicsJoint = constraint;
  83001. //don't add spring as constraint, as it is not one.
  83002. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83003. this.world.addConstraint(constraint);
  83004. }
  83005. else {
  83006. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83007. constraint.applyForce();
  83008. });
  83009. }
  83010. };
  83011. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83012. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83013. };
  83014. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83015. var index;
  83016. var mat;
  83017. for (index = 0; index < this._physicsMaterials.length; index++) {
  83018. mat = this._physicsMaterials[index];
  83019. if (mat.friction === friction && mat.restitution === restitution) {
  83020. return mat;
  83021. }
  83022. }
  83023. var currentMat = new this.BJSCANNON.Material(name);
  83024. currentMat.friction = friction;
  83025. currentMat.restitution = restitution;
  83026. this._physicsMaterials.push(currentMat);
  83027. return currentMat;
  83028. };
  83029. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83030. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83031. };
  83032. CannonJSPlugin.prototype._createShape = function (impostor) {
  83033. var object = impostor.object;
  83034. var returnValue;
  83035. var extendSize = impostor.getObjectExtendSize();
  83036. switch (impostor.type) {
  83037. case BABYLON.PhysicsImpostor.SphereImpostor:
  83038. var radiusX = extendSize.x;
  83039. var radiusY = extendSize.y;
  83040. var radiusZ = extendSize.z;
  83041. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83042. break;
  83043. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83044. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83045. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83046. break;
  83047. case BABYLON.PhysicsImpostor.BoxImpostor:
  83048. var box = extendSize.scale(0.5);
  83049. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83050. break;
  83051. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83052. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83053. returnValue = new this.BJSCANNON.Plane();
  83054. break;
  83055. case BABYLON.PhysicsImpostor.MeshImpostor:
  83056. // should transform the vertex data to world coordinates!!
  83057. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83058. var rawFaces = object.getIndices ? object.getIndices() : [];
  83059. if (!rawVerts)
  83060. return;
  83061. // get only scale! so the object could transform correctly.
  83062. var oldPosition = object.position.clone();
  83063. var oldRotation = object.rotation && object.rotation.clone();
  83064. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83065. object.position.copyFromFloats(0, 0, 0);
  83066. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83067. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83068. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83069. var transform = object.computeWorldMatrix(true);
  83070. // convert rawVerts to object space
  83071. var temp = new Array();
  83072. var index;
  83073. for (index = 0; index < rawVerts.length; index += 3) {
  83074. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83075. }
  83076. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83077. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83078. //now set back the transformation!
  83079. object.position.copyFrom(oldPosition);
  83080. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83081. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83082. break;
  83083. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83084. var oldPosition2 = object.position.clone();
  83085. var oldRotation2 = object.rotation && object.rotation.clone();
  83086. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83087. object.position.copyFromFloats(0, 0, 0);
  83088. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83089. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83090. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83091. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83092. returnValue = this._createHeightmap(object);
  83093. object.position.copyFrom(oldPosition2);
  83094. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83095. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83096. object.computeWorldMatrix(true);
  83097. break;
  83098. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83099. returnValue = new this.BJSCANNON.Particle();
  83100. break;
  83101. }
  83102. return returnValue;
  83103. };
  83104. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83105. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83106. var transform = object.computeWorldMatrix(true);
  83107. // convert rawVerts to object space
  83108. var temp = new Array();
  83109. var index;
  83110. for (index = 0; index < pos.length; index += 3) {
  83111. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83112. }
  83113. pos = temp;
  83114. var matrix = new Array();
  83115. //For now pointDepth will not be used and will be automatically calculated.
  83116. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83117. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83118. var boundingInfo = object.getBoundingInfo();
  83119. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83120. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83121. var elementSize = dim * 2 / arraySize;
  83122. for (var i = 0; i < pos.length; i = i + 3) {
  83123. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83124. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83125. var y = -pos[i + 2] + minY;
  83126. if (!matrix[x]) {
  83127. matrix[x] = [];
  83128. }
  83129. if (!matrix[x][z]) {
  83130. matrix[x][z] = y;
  83131. }
  83132. matrix[x][z] = Math.max(y, matrix[x][z]);
  83133. }
  83134. for (var x = 0; x <= arraySize; ++x) {
  83135. if (!matrix[x]) {
  83136. var loc = 1;
  83137. while (!matrix[(x + loc) % arraySize]) {
  83138. loc++;
  83139. }
  83140. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83141. //console.log("missing x", x);
  83142. }
  83143. for (var z = 0; z <= arraySize; ++z) {
  83144. if (!matrix[x][z]) {
  83145. var loc = 1;
  83146. var newValue;
  83147. while (newValue === undefined) {
  83148. newValue = matrix[x][(z + loc++) % arraySize];
  83149. }
  83150. matrix[x][z] = newValue;
  83151. }
  83152. }
  83153. }
  83154. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83155. elementSize: elementSize
  83156. });
  83157. //For future reference, needed for body transformation
  83158. shape.minY = minY;
  83159. return shape;
  83160. };
  83161. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83162. var object = impostor.object;
  83163. //make sure it is updated...
  83164. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83165. // The delta between the mesh position and the mesh bounding box center
  83166. var bInfo = object.getBoundingInfo();
  83167. if (!bInfo)
  83168. return;
  83169. var center = impostor.getObjectCenter();
  83170. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83171. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83172. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83173. this._tmpPosition.copyFrom(center);
  83174. var quaternion = object.rotationQuaternion;
  83175. if (!quaternion) {
  83176. return;
  83177. }
  83178. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83179. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83180. //-90 DEG in X, precalculated
  83181. quaternion = quaternion.multiply(this._minus90X);
  83182. //Invert! (Precalculated, 90 deg in X)
  83183. //No need to clone. this will never change.
  83184. impostor.setDeltaRotation(this._plus90X);
  83185. }
  83186. //If it is a heightfield, if should be centered.
  83187. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83188. var mesh = object;
  83189. var boundingInfo = mesh.getBoundingInfo();
  83190. //calculate the correct body position:
  83191. var rotationQuaternion = mesh.rotationQuaternion;
  83192. mesh.rotationQuaternion = this._tmpUnityRotation;
  83193. mesh.computeWorldMatrix(true);
  83194. //get original center with no rotation
  83195. var c = center.clone();
  83196. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83197. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83198. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83199. mesh.setPreTransformMatrix(p);
  83200. mesh.computeWorldMatrix(true);
  83201. //calculate the translation
  83202. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83203. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83204. //add it inverted to the delta
  83205. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83206. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83207. //rotation is back
  83208. mesh.rotationQuaternion = rotationQuaternion;
  83209. mesh.setPreTransformMatrix(oldPivot);
  83210. mesh.computeWorldMatrix(true);
  83211. }
  83212. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83213. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83214. //this._tmpPosition.copyFrom(object.position);
  83215. }
  83216. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83217. //Now update the impostor object
  83218. impostor.physicsBody.position.copy(this._tmpPosition);
  83219. impostor.physicsBody.quaternion.copy(quaternion);
  83220. };
  83221. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83222. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83223. if (impostor.object.rotationQuaternion) {
  83224. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83225. }
  83226. };
  83227. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83228. impostor.physicsBody.position.copy(newPosition);
  83229. impostor.physicsBody.quaternion.copy(newRotation);
  83230. };
  83231. CannonJSPlugin.prototype.isSupported = function () {
  83232. return this.BJSCANNON !== undefined;
  83233. };
  83234. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83235. impostor.physicsBody.velocity.copy(velocity);
  83236. };
  83237. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83238. impostor.physicsBody.angularVelocity.copy(velocity);
  83239. };
  83240. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83241. var v = impostor.physicsBody.velocity;
  83242. if (!v) {
  83243. return null;
  83244. }
  83245. return new BABYLON.Vector3(v.x, v.y, v.z);
  83246. };
  83247. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83248. var v = impostor.physicsBody.angularVelocity;
  83249. if (!v) {
  83250. return null;
  83251. }
  83252. return new BABYLON.Vector3(v.x, v.y, v.z);
  83253. };
  83254. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83255. impostor.physicsBody.mass = mass;
  83256. impostor.physicsBody.updateMassProperties();
  83257. };
  83258. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83259. return impostor.physicsBody.mass;
  83260. };
  83261. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83262. return impostor.physicsBody.material.friction;
  83263. };
  83264. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83265. impostor.physicsBody.material.friction = friction;
  83266. };
  83267. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83268. return impostor.physicsBody.material.restitution;
  83269. };
  83270. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83271. impostor.physicsBody.material.restitution = restitution;
  83272. };
  83273. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83274. impostor.physicsBody.sleep();
  83275. };
  83276. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83277. impostor.physicsBody.wakeUp();
  83278. };
  83279. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83280. joint.physicsJoint.distance = maxDistance;
  83281. };
  83282. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83283. // if (!motorIndex) {
  83284. // joint.physicsJoint.enableMotor();
  83285. // }
  83286. // }
  83287. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83288. // if (!motorIndex) {
  83289. // joint.physicsJoint.disableMotor();
  83290. // }
  83291. // }
  83292. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83293. if (!motorIndex) {
  83294. joint.physicsJoint.enableMotor();
  83295. joint.physicsJoint.setMotorSpeed(speed);
  83296. if (maxForce) {
  83297. this.setLimit(joint, maxForce);
  83298. }
  83299. }
  83300. };
  83301. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83302. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83303. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83304. };
  83305. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83306. var body = impostor.physicsBody;
  83307. mesh.position.x = body.position.x;
  83308. mesh.position.y = body.position.y;
  83309. mesh.position.z = body.position.z;
  83310. if (mesh.rotationQuaternion) {
  83311. mesh.rotationQuaternion.x = body.quaternion.x;
  83312. mesh.rotationQuaternion.y = body.quaternion.y;
  83313. mesh.rotationQuaternion.z = body.quaternion.z;
  83314. mesh.rotationQuaternion.w = body.quaternion.w;
  83315. }
  83316. };
  83317. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83318. var shape = impostor.physicsBody.shapes[0];
  83319. return shape.boundingSphereRadius;
  83320. };
  83321. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83322. var shape = impostor.physicsBody.shapes[0];
  83323. result.x = shape.halfExtents.x * 2;
  83324. result.y = shape.halfExtents.y * 2;
  83325. result.z = shape.halfExtents.z * 2;
  83326. };
  83327. CannonJSPlugin.prototype.dispose = function () {
  83328. };
  83329. CannonJSPlugin.prototype._extendNamespace = function () {
  83330. //this will force cannon to execute at least one step when using interpolation
  83331. var step_tmp1 = new this.BJSCANNON.Vec3();
  83332. var Engine = this.BJSCANNON;
  83333. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83334. maxSubSteps = maxSubSteps || 10;
  83335. timeSinceLastCalled = timeSinceLastCalled || 0;
  83336. if (timeSinceLastCalled === 0) {
  83337. this.internalStep(dt);
  83338. this.time += dt;
  83339. }
  83340. else {
  83341. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83342. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83343. var t0 = performance.now();
  83344. for (var i = 0; i !== internalSteps; i++) {
  83345. this.internalStep(dt);
  83346. if (performance.now() - t0 > dt * 1000) {
  83347. break;
  83348. }
  83349. }
  83350. this.time += timeSinceLastCalled;
  83351. var h = this.time % dt;
  83352. var h_div_dt = h / dt;
  83353. var interpvelo = step_tmp1;
  83354. var bodies = this.bodies;
  83355. for (var j = 0; j !== bodies.length; j++) {
  83356. var b = bodies[j];
  83357. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83358. b.position.vsub(b.previousPosition, interpvelo);
  83359. interpvelo.scale(h_div_dt, interpvelo);
  83360. b.position.vadd(interpvelo, b.interpolatedPosition);
  83361. }
  83362. else {
  83363. b.interpolatedPosition.copy(b.position);
  83364. b.interpolatedQuaternion.copy(b.quaternion);
  83365. }
  83366. }
  83367. }
  83368. };
  83369. };
  83370. return CannonJSPlugin;
  83371. }());
  83372. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83373. })(BABYLON || (BABYLON = {}));
  83374. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83375. var BABYLON;
  83376. (function (BABYLON) {
  83377. var OimoJSPlugin = /** @class */ (function () {
  83378. function OimoJSPlugin(iterations) {
  83379. this.name = "OimoJSPlugin";
  83380. this._tmpImpostorsArray = [];
  83381. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83382. this.BJSOIMO = OIMO;
  83383. this.world = new this.BJSOIMO.World({
  83384. iterations: iterations
  83385. });
  83386. this.world.clear();
  83387. }
  83388. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83389. this.world.gravity.copy(gravity);
  83390. };
  83391. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83392. this.world.timeStep = timeStep;
  83393. };
  83394. OimoJSPlugin.prototype.getTimeStep = function () {
  83395. return this.world.timeStep;
  83396. };
  83397. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83398. var _this = this;
  83399. impostors.forEach(function (impostor) {
  83400. impostor.beforeStep();
  83401. });
  83402. this.world.step();
  83403. impostors.forEach(function (impostor) {
  83404. impostor.afterStep();
  83405. //update the ordered impostors array
  83406. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83407. });
  83408. //check for collisions
  83409. var contact = this.world.contacts;
  83410. while (contact !== null) {
  83411. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83412. contact = contact.next;
  83413. continue;
  83414. }
  83415. //is this body colliding with any other? get the impostor
  83416. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83417. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83418. if (!mainImpostor || !collidingImpostor) {
  83419. contact = contact.next;
  83420. continue;
  83421. }
  83422. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83423. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83424. contact = contact.next;
  83425. }
  83426. };
  83427. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83428. var mass = impostor.physicsBody.mass;
  83429. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83430. };
  83431. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83432. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83433. this.applyImpulse(impostor, force, contactPoint);
  83434. };
  83435. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83436. var _this = this;
  83437. //parent-child relationship. Does this impostor has a parent impostor?
  83438. if (impostor.parent) {
  83439. if (impostor.physicsBody) {
  83440. this.removePhysicsBody(impostor);
  83441. //TODO is that needed?
  83442. impostor.forceUpdate();
  83443. }
  83444. return;
  83445. }
  83446. if (impostor.isBodyInitRequired()) {
  83447. var bodyConfig = {
  83448. name: impostor.uniqueId,
  83449. //Oimo must have mass, also for static objects.
  83450. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83451. size: [],
  83452. type: [],
  83453. pos: [],
  83454. posShape: [],
  83455. rot: [],
  83456. rotShape: [],
  83457. move: impostor.getParam("mass") !== 0,
  83458. density: impostor.getParam("mass"),
  83459. friction: impostor.getParam("friction"),
  83460. restitution: impostor.getParam("restitution"),
  83461. //Supporting older versions of Oimo
  83462. world: this.world
  83463. };
  83464. var impostors = [impostor];
  83465. var addToArray = function (parent) {
  83466. if (!parent.getChildMeshes)
  83467. return;
  83468. parent.getChildMeshes().forEach(function (m) {
  83469. if (m.physicsImpostor) {
  83470. impostors.push(m.physicsImpostor);
  83471. //m.physicsImpostor._init();
  83472. }
  83473. });
  83474. };
  83475. addToArray(impostor.object);
  83476. var checkWithEpsilon_1 = function (value) {
  83477. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83478. };
  83479. impostors.forEach(function (i) {
  83480. if (!i.object.rotationQuaternion) {
  83481. return;
  83482. }
  83483. //get the correct bounding box
  83484. var oldQuaternion = i.object.rotationQuaternion;
  83485. var rot = oldQuaternion.toEulerAngles();
  83486. var extendSize = i.getObjectExtendSize();
  83487. var radToDeg = 57.295779513082320876;
  83488. if (i === impostor) {
  83489. var center = impostor.getObjectCenter();
  83490. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83491. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83492. //Can also use Array.prototype.push.apply
  83493. bodyConfig.pos.push(center.x);
  83494. bodyConfig.pos.push(center.y);
  83495. bodyConfig.pos.push(center.z);
  83496. bodyConfig.posShape.push(0, 0, 0);
  83497. //tmp solution
  83498. bodyConfig.rot.push(rot.x * radToDeg);
  83499. bodyConfig.rot.push(rot.y * radToDeg);
  83500. bodyConfig.rot.push(rot.z * radToDeg);
  83501. bodyConfig.rotShape.push(0, 0, 0);
  83502. }
  83503. else {
  83504. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83505. bodyConfig.posShape.push(localPosition.x);
  83506. bodyConfig.posShape.push(localPosition.y);
  83507. bodyConfig.posShape.push(localPosition.z);
  83508. bodyConfig.pos.push(0, 0, 0);
  83509. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83510. bodyConfig.rot.push(0);
  83511. bodyConfig.rot.push(0);
  83512. bodyConfig.rot.push(0);
  83513. bodyConfig.rotShape.push(rot.x * radToDeg);
  83514. bodyConfig.rotShape.push(rot.y * radToDeg);
  83515. bodyConfig.rotShape.push(rot.z * radToDeg);
  83516. }
  83517. // register mesh
  83518. switch (i.type) {
  83519. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83520. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83521. case BABYLON.PhysicsImpostor.SphereImpostor:
  83522. var radiusX = extendSize.x;
  83523. var radiusY = extendSize.y;
  83524. var radiusZ = extendSize.z;
  83525. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83526. bodyConfig.type.push('sphere');
  83527. //due to the way oimo works with compounds, add 3 times
  83528. bodyConfig.size.push(size);
  83529. bodyConfig.size.push(size);
  83530. bodyConfig.size.push(size);
  83531. break;
  83532. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83533. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83534. var sizeY = checkWithEpsilon_1(extendSize.y);
  83535. bodyConfig.type.push('cylinder');
  83536. bodyConfig.size.push(sizeX);
  83537. bodyConfig.size.push(sizeY);
  83538. //due to the way oimo works with compounds, add one more value.
  83539. bodyConfig.size.push(sizeY);
  83540. break;
  83541. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83542. case BABYLON.PhysicsImpostor.BoxImpostor:
  83543. default:
  83544. var sizeX = checkWithEpsilon_1(extendSize.x);
  83545. var sizeY = checkWithEpsilon_1(extendSize.y);
  83546. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83547. bodyConfig.type.push('box');
  83548. //if (i === impostor) {
  83549. bodyConfig.size.push(sizeX);
  83550. bodyConfig.size.push(sizeY);
  83551. bodyConfig.size.push(sizeZ);
  83552. //} else {
  83553. // bodyConfig.size.push(0,0,0);
  83554. //}
  83555. break;
  83556. }
  83557. //actually not needed, but hey...
  83558. i.object.rotationQuaternion = oldQuaternion;
  83559. });
  83560. impostor.physicsBody = this.world.add(bodyConfig);
  83561. }
  83562. else {
  83563. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83564. }
  83565. impostor.setDeltaPosition(this._tmpPositionVector);
  83566. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83567. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83568. };
  83569. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83570. //impostor.physicsBody.dispose();
  83571. //Same as : (older oimo versions)
  83572. this.world.removeRigidBody(impostor.physicsBody);
  83573. };
  83574. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83575. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83576. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83577. if (!mainBody || !connectedBody) {
  83578. return;
  83579. }
  83580. var jointData = impostorJoint.joint.jointData;
  83581. var options = jointData.nativeParams || {};
  83582. var type;
  83583. var nativeJointData = {
  83584. body1: mainBody,
  83585. body2: connectedBody,
  83586. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83587. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83588. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83589. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83590. min: options.min,
  83591. max: options.max,
  83592. collision: options.collision || jointData.collision,
  83593. spring: options.spring,
  83594. //supporting older version of Oimo
  83595. world: this.world
  83596. };
  83597. switch (impostorJoint.joint.type) {
  83598. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83599. type = "jointBall";
  83600. break;
  83601. case BABYLON.PhysicsJoint.SpringJoint:
  83602. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83603. var springData = jointData;
  83604. nativeJointData.min = springData.length || nativeJointData.min;
  83605. //Max should also be set, just make sure it is at least min
  83606. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83607. case BABYLON.PhysicsJoint.DistanceJoint:
  83608. type = "jointDistance";
  83609. nativeJointData.max = jointData.maxDistance;
  83610. break;
  83611. case BABYLON.PhysicsJoint.PrismaticJoint:
  83612. type = "jointPrisme";
  83613. break;
  83614. case BABYLON.PhysicsJoint.SliderJoint:
  83615. type = "jointSlide";
  83616. break;
  83617. case BABYLON.PhysicsJoint.WheelJoint:
  83618. type = "jointWheel";
  83619. break;
  83620. case BABYLON.PhysicsJoint.HingeJoint:
  83621. default:
  83622. type = "jointHinge";
  83623. break;
  83624. }
  83625. nativeJointData.type = type;
  83626. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83627. };
  83628. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83629. //Bug in Oimo prevents us from disposing a joint in the playground
  83630. //joint.joint.physicsJoint.dispose();
  83631. //So we will bruteforce it!
  83632. try {
  83633. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83634. }
  83635. catch (e) {
  83636. BABYLON.Tools.Warn(e);
  83637. }
  83638. };
  83639. OimoJSPlugin.prototype.isSupported = function () {
  83640. return this.BJSOIMO !== undefined;
  83641. };
  83642. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83643. if (!impostor.physicsBody.sleeping) {
  83644. //TODO check that
  83645. /*if (impostor.physicsBody.shapes.next) {
  83646. var parentShape = this._getLastShape(impostor.physicsBody);
  83647. impostor.object.position.copyFrom(parentShape.position);
  83648. console.log(parentShape.position);
  83649. } else {*/
  83650. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83651. //}
  83652. if (impostor.object.rotationQuaternion) {
  83653. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83654. }
  83655. }
  83656. };
  83657. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83658. var body = impostor.physicsBody;
  83659. body.position.copy(newPosition);
  83660. body.orientation.copy(newRotation);
  83661. body.syncShapes();
  83662. body.awake();
  83663. };
  83664. /*private _getLastShape(body: any): any {
  83665. var lastShape = body.shapes;
  83666. while (lastShape.next) {
  83667. lastShape = lastShape.next;
  83668. }
  83669. return lastShape;
  83670. }*/
  83671. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83672. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83673. };
  83674. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83675. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83676. };
  83677. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83678. var v = impostor.physicsBody.linearVelocity;
  83679. if (!v) {
  83680. return null;
  83681. }
  83682. return new BABYLON.Vector3(v.x, v.y, v.z);
  83683. };
  83684. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83685. var v = impostor.physicsBody.angularVelocity;
  83686. if (!v) {
  83687. return null;
  83688. }
  83689. return new BABYLON.Vector3(v.x, v.y, v.z);
  83690. };
  83691. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83692. var staticBody = mass === 0;
  83693. //this will actually set the body's density and not its mass.
  83694. //But this is how oimo treats the mass variable.
  83695. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83696. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83697. };
  83698. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83699. return impostor.physicsBody.shapes.density;
  83700. };
  83701. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83702. return impostor.physicsBody.shapes.friction;
  83703. };
  83704. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83705. impostor.physicsBody.shapes.friction = friction;
  83706. };
  83707. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83708. return impostor.physicsBody.shapes.restitution;
  83709. };
  83710. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83711. impostor.physicsBody.shapes.restitution = restitution;
  83712. };
  83713. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83714. impostor.physicsBody.sleep();
  83715. };
  83716. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83717. impostor.physicsBody.awake();
  83718. };
  83719. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83720. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83721. if (minDistance !== void 0) {
  83722. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83723. }
  83724. };
  83725. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83726. //TODO separate rotational and transational motors.
  83727. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83728. if (motor) {
  83729. motor.setMotor(speed, maxForce);
  83730. }
  83731. };
  83732. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83733. //TODO separate rotational and transational motors.
  83734. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83735. if (motor) {
  83736. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83737. }
  83738. };
  83739. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83740. var body = impostor.physicsBody;
  83741. mesh.position.x = body.position.x;
  83742. mesh.position.y = body.position.y;
  83743. mesh.position.z = body.position.z;
  83744. if (mesh.rotationQuaternion) {
  83745. mesh.rotationQuaternion.x = body.orientation.x;
  83746. mesh.rotationQuaternion.y = body.orientation.y;
  83747. mesh.rotationQuaternion.z = body.orientation.z;
  83748. mesh.rotationQuaternion.w = body.orientation.s;
  83749. }
  83750. };
  83751. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83752. return impostor.physicsBody.shapes.radius;
  83753. };
  83754. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83755. var shape = impostor.physicsBody.shapes;
  83756. result.x = shape.halfWidth * 2;
  83757. result.y = shape.halfHeight * 2;
  83758. result.z = shape.halfDepth * 2;
  83759. };
  83760. OimoJSPlugin.prototype.dispose = function () {
  83761. this.world.clear();
  83762. };
  83763. return OimoJSPlugin;
  83764. }());
  83765. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83766. })(BABYLON || (BABYLON = {}));
  83767. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83768. var BABYLON;
  83769. (function (BABYLON) {
  83770. /*
  83771. * Based on jsTGALoader - Javascript loader for TGA file
  83772. * By Vincent Thibault
  83773. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83774. */
  83775. var TGATools = /** @class */ (function () {
  83776. function TGATools() {
  83777. }
  83778. TGATools.GetTGAHeader = function (data) {
  83779. var offset = 0;
  83780. var header = {
  83781. id_length: data[offset++],
  83782. colormap_type: data[offset++],
  83783. image_type: data[offset++],
  83784. colormap_index: data[offset++] | data[offset++] << 8,
  83785. colormap_length: data[offset++] | data[offset++] << 8,
  83786. colormap_size: data[offset++],
  83787. origin: [
  83788. data[offset++] | data[offset++] << 8,
  83789. data[offset++] | data[offset++] << 8
  83790. ],
  83791. width: data[offset++] | data[offset++] << 8,
  83792. height: data[offset++] | data[offset++] << 8,
  83793. pixel_size: data[offset++],
  83794. flags: data[offset++]
  83795. };
  83796. return header;
  83797. };
  83798. TGATools.UploadContent = function (gl, data) {
  83799. // Not enough data to contain header ?
  83800. if (data.length < 19) {
  83801. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83802. return;
  83803. }
  83804. // Read Header
  83805. var offset = 18;
  83806. var header = TGATools.GetTGAHeader(data);
  83807. // Assume it's a valid Targa file.
  83808. if (header.id_length + offset > data.length) {
  83809. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83810. return;
  83811. }
  83812. // Skip not needed data
  83813. offset += header.id_length;
  83814. var use_rle = false;
  83815. var use_pal = false;
  83816. var use_grey = false;
  83817. // Get some informations.
  83818. switch (header.image_type) {
  83819. case TGATools._TYPE_RLE_INDEXED:
  83820. use_rle = true;
  83821. case TGATools._TYPE_INDEXED:
  83822. use_pal = true;
  83823. break;
  83824. case TGATools._TYPE_RLE_RGB:
  83825. use_rle = true;
  83826. case TGATools._TYPE_RGB:
  83827. // use_rgb = true;
  83828. break;
  83829. case TGATools._TYPE_RLE_GREY:
  83830. use_rle = true;
  83831. case TGATools._TYPE_GREY:
  83832. use_grey = true;
  83833. break;
  83834. }
  83835. var pixel_data;
  83836. // var numAlphaBits = header.flags & 0xf;
  83837. var pixel_size = header.pixel_size >> 3;
  83838. var pixel_total = header.width * header.height * pixel_size;
  83839. // Read palettes
  83840. var palettes;
  83841. if (use_pal) {
  83842. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83843. }
  83844. // Read LRE
  83845. if (use_rle) {
  83846. pixel_data = new Uint8Array(pixel_total);
  83847. var c, count, i;
  83848. var localOffset = 0;
  83849. var pixels = new Uint8Array(pixel_size);
  83850. while (offset < pixel_total && localOffset < pixel_total) {
  83851. c = data[offset++];
  83852. count = (c & 0x7f) + 1;
  83853. // RLE pixels
  83854. if (c & 0x80) {
  83855. // Bind pixel tmp array
  83856. for (i = 0; i < pixel_size; ++i) {
  83857. pixels[i] = data[offset++];
  83858. }
  83859. // Copy pixel array
  83860. for (i = 0; i < count; ++i) {
  83861. pixel_data.set(pixels, localOffset + i * pixel_size);
  83862. }
  83863. localOffset += pixel_size * count;
  83864. }
  83865. // Raw pixels
  83866. else {
  83867. count *= pixel_size;
  83868. for (i = 0; i < count; ++i) {
  83869. pixel_data[localOffset + i] = data[offset++];
  83870. }
  83871. localOffset += count;
  83872. }
  83873. }
  83874. }
  83875. // RAW Pixels
  83876. else {
  83877. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83878. }
  83879. // Load to texture
  83880. var x_start, y_start, x_step, y_step, y_end, x_end;
  83881. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83882. default:
  83883. case TGATools._ORIGIN_UL:
  83884. x_start = 0;
  83885. x_step = 1;
  83886. x_end = header.width;
  83887. y_start = 0;
  83888. y_step = 1;
  83889. y_end = header.height;
  83890. break;
  83891. case TGATools._ORIGIN_BL:
  83892. x_start = 0;
  83893. x_step = 1;
  83894. x_end = header.width;
  83895. y_start = header.height - 1;
  83896. y_step = -1;
  83897. y_end = -1;
  83898. break;
  83899. case TGATools._ORIGIN_UR:
  83900. x_start = header.width - 1;
  83901. x_step = -1;
  83902. x_end = -1;
  83903. y_start = 0;
  83904. y_step = 1;
  83905. y_end = header.height;
  83906. break;
  83907. case TGATools._ORIGIN_BR:
  83908. x_start = header.width - 1;
  83909. x_step = -1;
  83910. x_end = -1;
  83911. y_start = header.height - 1;
  83912. y_step = -1;
  83913. y_end = -1;
  83914. break;
  83915. }
  83916. // Load the specify method
  83917. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  83918. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  83919. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  83920. };
  83921. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83922. var image = pixel_data, colormap = palettes;
  83923. var width = header.width, height = header.height;
  83924. var color, i = 0, x, y;
  83925. var imageData = new Uint8Array(width * height * 4);
  83926. for (y = y_start; y !== y_end; y += y_step) {
  83927. for (x = x_start; x !== x_end; x += x_step, i++) {
  83928. color = image[i];
  83929. imageData[(x + width * y) * 4 + 3] = 255;
  83930. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  83931. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  83932. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  83933. }
  83934. }
  83935. return imageData;
  83936. };
  83937. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83938. var image = pixel_data;
  83939. var width = header.width, height = header.height;
  83940. var color, i = 0, x, y;
  83941. var imageData = new Uint8Array(width * height * 4);
  83942. for (y = y_start; y !== y_end; y += y_step) {
  83943. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83944. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  83945. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  83946. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  83947. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  83948. imageData[(x + width * y) * 4 + 0] = r;
  83949. imageData[(x + width * y) * 4 + 1] = g;
  83950. imageData[(x + width * y) * 4 + 2] = b;
  83951. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  83952. }
  83953. }
  83954. return imageData;
  83955. };
  83956. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83957. var image = pixel_data;
  83958. var width = header.width, height = header.height;
  83959. var i = 0, x, y;
  83960. var imageData = new Uint8Array(width * height * 4);
  83961. for (y = y_start; y !== y_end; y += y_step) {
  83962. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  83963. imageData[(x + width * y) * 4 + 3] = 255;
  83964. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83965. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83966. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83967. }
  83968. }
  83969. return imageData;
  83970. };
  83971. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83972. var image = pixel_data;
  83973. var width = header.width, height = header.height;
  83974. var i = 0, x, y;
  83975. var imageData = new Uint8Array(width * height * 4);
  83976. for (y = y_start; y !== y_end; y += y_step) {
  83977. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  83978. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83979. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83980. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83981. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  83982. }
  83983. }
  83984. return imageData;
  83985. };
  83986. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83987. var image = pixel_data;
  83988. var width = header.width, height = header.height;
  83989. var color, i = 0, x, y;
  83990. var imageData = new Uint8Array(width * height * 4);
  83991. for (y = y_start; y !== y_end; y += y_step) {
  83992. for (x = x_start; x !== x_end; x += x_step, i++) {
  83993. color = image[i];
  83994. imageData[(x + width * y) * 4 + 0] = color;
  83995. imageData[(x + width * y) * 4 + 1] = color;
  83996. imageData[(x + width * y) * 4 + 2] = color;
  83997. imageData[(x + width * y) * 4 + 3] = 255;
  83998. }
  83999. }
  84000. return imageData;
  84001. };
  84002. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84003. var image = pixel_data;
  84004. var width = header.width, height = header.height;
  84005. var i = 0, x, y;
  84006. var imageData = new Uint8Array(width * height * 4);
  84007. for (y = y_start; y !== y_end; y += y_step) {
  84008. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84009. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84010. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84011. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84012. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84013. }
  84014. }
  84015. return imageData;
  84016. };
  84017. //private static _TYPE_NO_DATA = 0;
  84018. TGATools._TYPE_INDEXED = 1;
  84019. TGATools._TYPE_RGB = 2;
  84020. TGATools._TYPE_GREY = 3;
  84021. TGATools._TYPE_RLE_INDEXED = 9;
  84022. TGATools._TYPE_RLE_RGB = 10;
  84023. TGATools._TYPE_RLE_GREY = 11;
  84024. TGATools._ORIGIN_MASK = 0x30;
  84025. TGATools._ORIGIN_SHIFT = 0x04;
  84026. TGATools._ORIGIN_BL = 0x00;
  84027. TGATools._ORIGIN_BR = 0x01;
  84028. TGATools._ORIGIN_UL = 0x02;
  84029. TGATools._ORIGIN_UR = 0x03;
  84030. return TGATools;
  84031. }());
  84032. BABYLON.TGATools = TGATools;
  84033. })(BABYLON || (BABYLON = {}));
  84034. //# sourceMappingURL=babylon.tga.js.map
  84035. var BABYLON;
  84036. (function (BABYLON) {
  84037. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84038. // All values and structures referenced from:
  84039. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84040. var DDS_MAGIC = 0x20534444;
  84041. var
  84042. //DDSD_CAPS = 0x1,
  84043. //DDSD_HEIGHT = 0x2,
  84044. //DDSD_WIDTH = 0x4,
  84045. //DDSD_PITCH = 0x8,
  84046. //DDSD_PIXELFORMAT = 0x1000,
  84047. DDSD_MIPMAPCOUNT = 0x20000;
  84048. //DDSD_LINEARSIZE = 0x80000,
  84049. //DDSD_DEPTH = 0x800000;
  84050. // var DDSCAPS_COMPLEX = 0x8,
  84051. // DDSCAPS_MIPMAP = 0x400000,
  84052. // DDSCAPS_TEXTURE = 0x1000;
  84053. var DDSCAPS2_CUBEMAP = 0x200;
  84054. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84055. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84056. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84057. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84058. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84059. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84060. // DDSCAPS2_VOLUME = 0x200000;
  84061. var
  84062. //DDPF_ALPHAPIXELS = 0x1,
  84063. //DDPF_ALPHA = 0x2,
  84064. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84065. //DDPF_YUV = 0x200,
  84066. DDPF_LUMINANCE = 0x20000;
  84067. function FourCCToInt32(value) {
  84068. return value.charCodeAt(0) +
  84069. (value.charCodeAt(1) << 8) +
  84070. (value.charCodeAt(2) << 16) +
  84071. (value.charCodeAt(3) << 24);
  84072. }
  84073. function Int32ToFourCC(value) {
  84074. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84075. }
  84076. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84077. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84078. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84079. var FOURCC_DX10 = FourCCToInt32("DX10");
  84080. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84081. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84082. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84083. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84084. var headerLengthInt = 31; // The header length in 32 bit ints
  84085. // Offsets into the header array
  84086. var off_magic = 0;
  84087. var off_size = 1;
  84088. var off_flags = 2;
  84089. var off_height = 3;
  84090. var off_width = 4;
  84091. var off_mipmapCount = 7;
  84092. var off_pfFlags = 20;
  84093. var off_pfFourCC = 21;
  84094. var off_RGBbpp = 22;
  84095. var off_RMask = 23;
  84096. var off_GMask = 24;
  84097. var off_BMask = 25;
  84098. var off_AMask = 26;
  84099. // var off_caps1 = 27;
  84100. var off_caps2 = 28;
  84101. // var off_caps3 = 29;
  84102. // var off_caps4 = 30;
  84103. var off_dxgiFormat = 32;
  84104. ;
  84105. var DDSTools = /** @class */ (function () {
  84106. function DDSTools() {
  84107. }
  84108. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84109. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84110. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84111. var mipmapCount = 1;
  84112. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84113. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84114. }
  84115. var fourCC = header[off_pfFourCC];
  84116. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84117. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84118. switch (fourCC) {
  84119. case FOURCC_D3DFMT_R16G16B16A16F:
  84120. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84121. break;
  84122. case FOURCC_D3DFMT_R32G32B32A32F:
  84123. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84124. break;
  84125. case FOURCC_DX10:
  84126. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84127. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84128. break;
  84129. }
  84130. }
  84131. return {
  84132. width: header[off_width],
  84133. height: header[off_height],
  84134. mipmapCount: mipmapCount,
  84135. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84136. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84137. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84138. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84139. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84140. dxgiFormat: dxgiFormat,
  84141. textureType: textureType
  84142. };
  84143. };
  84144. DDSTools._ToHalfFloat = function (value) {
  84145. if (!DDSTools._FloatView) {
  84146. DDSTools._FloatView = new Float32Array(1);
  84147. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84148. }
  84149. DDSTools._FloatView[0] = value;
  84150. var x = DDSTools._Int32View[0];
  84151. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84152. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84153. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84154. /* If zero, or denormal, or exponent underflows too much for a denormal
  84155. * half, return signed zero. */
  84156. if (e < 103) {
  84157. return bits;
  84158. }
  84159. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84160. if (e > 142) {
  84161. bits |= 0x7c00;
  84162. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84163. * not Inf, so make sure we set one mantissa bit too. */
  84164. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84165. return bits;
  84166. }
  84167. /* If exponent underflows but not too much, return a denormal */
  84168. if (e < 113) {
  84169. m |= 0x0800;
  84170. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84171. * to 1, which is OK. */
  84172. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84173. return bits;
  84174. }
  84175. bits |= ((e - 112) << 10) | (m >> 1);
  84176. bits += m & 1;
  84177. return bits;
  84178. };
  84179. DDSTools._FromHalfFloat = function (value) {
  84180. var s = (value & 0x8000) >> 15;
  84181. var e = (value & 0x7C00) >> 10;
  84182. var f = value & 0x03FF;
  84183. if (e === 0) {
  84184. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84185. }
  84186. else if (e == 0x1F) {
  84187. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84188. }
  84189. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84190. };
  84191. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84192. var destArray = new Float32Array(dataLength);
  84193. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84194. var index = 0;
  84195. for (var y = 0; y < height; y++) {
  84196. for (var x = 0; x < width; x++) {
  84197. var srcPos = (x + y * width) * 4;
  84198. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84199. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84200. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84201. if (DDSTools.StoreLODInAlphaChannel) {
  84202. destArray[index + 3] = lod;
  84203. }
  84204. else {
  84205. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84206. }
  84207. index += 4;
  84208. }
  84209. }
  84210. return destArray;
  84211. };
  84212. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84213. if (DDSTools.StoreLODInAlphaChannel) {
  84214. var destArray = new Uint16Array(dataLength);
  84215. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84216. var index = 0;
  84217. for (var y = 0; y < height; y++) {
  84218. for (var x = 0; x < width; x++) {
  84219. var srcPos = (x + y * width) * 4;
  84220. destArray[index] = srcData[srcPos];
  84221. destArray[index + 1] = srcData[srcPos + 1];
  84222. destArray[index + 2] = srcData[srcPos + 2];
  84223. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84224. index += 4;
  84225. }
  84226. }
  84227. return destArray;
  84228. }
  84229. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84230. };
  84231. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84232. if (DDSTools.StoreLODInAlphaChannel) {
  84233. var destArray = new Float32Array(dataLength);
  84234. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84235. var index = 0;
  84236. for (var y = 0; y < height; y++) {
  84237. for (var x = 0; x < width; x++) {
  84238. var srcPos = (x + y * width) * 4;
  84239. destArray[index] = srcData[srcPos];
  84240. destArray[index + 1] = srcData[srcPos + 1];
  84241. destArray[index + 2] = srcData[srcPos + 2];
  84242. destArray[index + 3] = lod;
  84243. index += 4;
  84244. }
  84245. }
  84246. return destArray;
  84247. }
  84248. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84249. };
  84250. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84251. var destArray = new Uint8Array(dataLength);
  84252. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84253. var index = 0;
  84254. for (var y = 0; y < height; y++) {
  84255. for (var x = 0; x < width; x++) {
  84256. var srcPos = (x + y * width) * 4;
  84257. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84258. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84259. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84260. if (DDSTools.StoreLODInAlphaChannel) {
  84261. destArray[index + 3] = lod;
  84262. }
  84263. else {
  84264. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84265. }
  84266. index += 4;
  84267. }
  84268. }
  84269. return destArray;
  84270. };
  84271. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84272. var destArray = new Uint8Array(dataLength);
  84273. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84274. var index = 0;
  84275. for (var y = 0; y < height; y++) {
  84276. for (var x = 0; x < width; x++) {
  84277. var srcPos = (x + y * width) * 4;
  84278. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84279. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84280. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84281. if (DDSTools.StoreLODInAlphaChannel) {
  84282. destArray[index + 3] = lod;
  84283. }
  84284. else {
  84285. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84286. }
  84287. index += 4;
  84288. }
  84289. }
  84290. return destArray;
  84291. };
  84292. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84293. var byteArray = new Uint8Array(dataLength);
  84294. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84295. var index = 0;
  84296. for (var y = 0; y < height; y++) {
  84297. for (var x = 0; x < width; x++) {
  84298. var srcPos = (x + y * width) * 4;
  84299. byteArray[index] = srcData[srcPos + rOffset];
  84300. byteArray[index + 1] = srcData[srcPos + gOffset];
  84301. byteArray[index + 2] = srcData[srcPos + bOffset];
  84302. byteArray[index + 3] = srcData[srcPos + aOffset];
  84303. index += 4;
  84304. }
  84305. }
  84306. return byteArray;
  84307. };
  84308. DDSTools._ExtractLongWordOrder = function (value) {
  84309. if (value === 0 || value === 255 || value === -16777216) {
  84310. return 0;
  84311. }
  84312. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84313. };
  84314. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84315. var byteArray = new Uint8Array(dataLength);
  84316. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84317. var index = 0;
  84318. for (var y = 0; y < height; y++) {
  84319. for (var x = 0; x < width; x++) {
  84320. var srcPos = (x + y * width) * 3;
  84321. byteArray[index] = srcData[srcPos + rOffset];
  84322. byteArray[index + 1] = srcData[srcPos + gOffset];
  84323. byteArray[index + 2] = srcData[srcPos + bOffset];
  84324. index += 3;
  84325. }
  84326. }
  84327. return byteArray;
  84328. };
  84329. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84330. var byteArray = new Uint8Array(dataLength);
  84331. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84332. var index = 0;
  84333. for (var y = 0; y < height; y++) {
  84334. for (var x = 0; x < width; x++) {
  84335. var srcPos = (x + y * width);
  84336. byteArray[index] = srcData[srcPos];
  84337. index++;
  84338. }
  84339. }
  84340. return byteArray;
  84341. };
  84342. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84343. if (lodIndex === void 0) { lodIndex = -1; }
  84344. var sphericalPolynomialFaces = null;
  84345. if (info.sphericalPolynomial) {
  84346. sphericalPolynomialFaces = new Array();
  84347. }
  84348. var ext = engine.getCaps().s3tc;
  84349. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84350. var fourCC, width, height, dataLength = 0, dataOffset;
  84351. var byteArray, mipmapCount, mip;
  84352. var internalFormat = 0;
  84353. var format = 0;
  84354. var blockBytes = 1;
  84355. if (header[off_magic] !== DDS_MAGIC) {
  84356. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84357. return;
  84358. }
  84359. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84360. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84361. return;
  84362. }
  84363. if (info.isCompressed && !ext) {
  84364. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84365. return;
  84366. }
  84367. var bpp = header[off_RGBbpp];
  84368. dataOffset = header[off_size] + 4;
  84369. var computeFormats = false;
  84370. if (info.isFourCC) {
  84371. fourCC = header[off_pfFourCC];
  84372. switch (fourCC) {
  84373. case FOURCC_DXT1:
  84374. blockBytes = 8;
  84375. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84376. break;
  84377. case FOURCC_DXT3:
  84378. blockBytes = 16;
  84379. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84380. break;
  84381. case FOURCC_DXT5:
  84382. blockBytes = 16;
  84383. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84384. break;
  84385. case FOURCC_D3DFMT_R16G16B16A16F:
  84386. computeFormats = true;
  84387. break;
  84388. case FOURCC_D3DFMT_R32G32B32A32F:
  84389. computeFormats = true;
  84390. break;
  84391. case FOURCC_DX10:
  84392. // There is an additionnal header so dataOffset need to be changed
  84393. dataOffset += 5 * 4; // 5 uints
  84394. var supported = false;
  84395. switch (info.dxgiFormat) {
  84396. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84397. computeFormats = true;
  84398. supported = true;
  84399. break;
  84400. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84401. info.isRGB = true;
  84402. info.isFourCC = false;
  84403. bpp = 32;
  84404. supported = true;
  84405. break;
  84406. }
  84407. if (supported) {
  84408. break;
  84409. }
  84410. default:
  84411. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84412. return;
  84413. }
  84414. }
  84415. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84416. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84417. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84418. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84419. if (computeFormats) {
  84420. format = engine._getWebGLTextureType(info.textureType);
  84421. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84422. }
  84423. mipmapCount = 1;
  84424. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84425. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84426. }
  84427. for (var face = 0; face < faces; face++) {
  84428. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84429. width = header[off_width];
  84430. height = header[off_height];
  84431. for (mip = 0; mip < mipmapCount; ++mip) {
  84432. if (lodIndex === -1 || lodIndex === mip) {
  84433. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84434. var i = (lodIndex === -1) ? mip : 0;
  84435. if (!info.isCompressed && info.isFourCC) {
  84436. dataLength = width * height * 4;
  84437. var floatArray = null;
  84438. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84439. if (bpp === 128) {
  84440. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84441. if (sphericalPolynomialFaces && i == 0) {
  84442. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84443. }
  84444. }
  84445. else if (bpp === 64) {
  84446. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84447. if (sphericalPolynomialFaces && i == 0) {
  84448. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84449. }
  84450. }
  84451. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84452. format = engine._getWebGLTextureType(info.textureType);
  84453. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84454. }
  84455. else {
  84456. if (bpp === 128) {
  84457. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84458. if (sphericalPolynomialFaces && i == 0) {
  84459. sphericalPolynomialFaces.push(floatArray);
  84460. }
  84461. }
  84462. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84463. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84464. if (sphericalPolynomialFaces && i == 0) {
  84465. sphericalPolynomialFaces.push(floatArray);
  84466. }
  84467. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84468. format = engine._getWebGLTextureType(info.textureType);
  84469. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84470. }
  84471. else { // 64
  84472. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84473. if (sphericalPolynomialFaces && i == 0) {
  84474. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84475. }
  84476. }
  84477. }
  84478. if (floatArray) {
  84479. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84480. }
  84481. }
  84482. else if (info.isRGB) {
  84483. if (bpp === 24) {
  84484. dataLength = width * height * 3;
  84485. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84486. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84487. }
  84488. else { // 32
  84489. dataLength = width * height * 4;
  84490. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84491. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84492. }
  84493. }
  84494. else if (info.isLuminance) {
  84495. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84496. var unpaddedRowSize = width;
  84497. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84498. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84499. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84500. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84501. }
  84502. else {
  84503. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84504. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84505. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84506. }
  84507. }
  84508. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84509. width *= 0.5;
  84510. height *= 0.5;
  84511. width = Math.max(1.0, width);
  84512. height = Math.max(1.0, height);
  84513. }
  84514. if (currentFace !== undefined) {
  84515. // Loading a single face
  84516. break;
  84517. }
  84518. }
  84519. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84520. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84521. size: header[off_width],
  84522. right: sphericalPolynomialFaces[0],
  84523. left: sphericalPolynomialFaces[1],
  84524. up: sphericalPolynomialFaces[2],
  84525. down: sphericalPolynomialFaces[3],
  84526. front: sphericalPolynomialFaces[4],
  84527. back: sphericalPolynomialFaces[5],
  84528. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84529. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84530. gammaSpace: false,
  84531. });
  84532. }
  84533. else {
  84534. info.sphericalPolynomial = undefined;
  84535. }
  84536. };
  84537. DDSTools.StoreLODInAlphaChannel = false;
  84538. return DDSTools;
  84539. }());
  84540. BABYLON.DDSTools = DDSTools;
  84541. })(BABYLON || (BABYLON = {}));
  84542. //# sourceMappingURL=babylon.dds.js.map
  84543. var BABYLON;
  84544. (function (BABYLON) {
  84545. /**
  84546. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84547. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84548. */
  84549. var KhronosTextureContainer = /** @class */ (function () {
  84550. /**
  84551. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84552. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84553. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84554. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84555. */
  84556. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84557. this.arrayBuffer = arrayBuffer;
  84558. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84559. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84560. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84561. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84562. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84563. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84564. BABYLON.Tools.Error("texture missing KTX identifier");
  84565. return;
  84566. }
  84567. // load the reset of the header in native 32 bit int
  84568. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84569. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84570. var oppositeEndianess = header[0] === 0x01020304;
  84571. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84572. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84573. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84574. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84575. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84576. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84577. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84578. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84579. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84580. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84581. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84582. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84583. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84584. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84585. if (this.glType !== 0) {
  84586. BABYLON.Tools.Error("only compressed formats currently supported");
  84587. return;
  84588. }
  84589. else {
  84590. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84591. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84592. }
  84593. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84594. BABYLON.Tools.Error("only 2D textures currently supported");
  84595. return;
  84596. }
  84597. if (this.numberOfArrayElements !== 0) {
  84598. BABYLON.Tools.Error("texture arrays not currently supported");
  84599. return;
  84600. }
  84601. if (this.numberOfFaces !== facesExpected) {
  84602. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84603. return;
  84604. }
  84605. // we now have a completely validated file, so could use existence of loadType as success
  84606. // would need to make this more elaborate & adjust checks above to support more than one load type
  84607. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84608. }
  84609. // not as fast hardware based, but will probably never need to use
  84610. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84611. return ((val & 0xFF) << 24)
  84612. | ((val & 0xFF00) << 8)
  84613. | ((val >> 8) & 0xFF00)
  84614. | ((val >> 24) & 0xFF);
  84615. };
  84616. /**
  84617. * It is assumed that the texture has already been created & is currently bound
  84618. */
  84619. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84620. switch (this.loadType) {
  84621. case KhronosTextureContainer.COMPRESSED_2D:
  84622. this._upload2DCompressedLevels(gl, loadMipmaps);
  84623. break;
  84624. case KhronosTextureContainer.TEX_2D:
  84625. case KhronosTextureContainer.COMPRESSED_3D:
  84626. case KhronosTextureContainer.TEX_3D:
  84627. }
  84628. };
  84629. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84630. // initialize width & height for level 1
  84631. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84632. var width = this.pixelWidth;
  84633. var height = this.pixelHeight;
  84634. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84635. for (var level = 0; level < mipmapCount; level++) {
  84636. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84637. for (var face = 0; face < this.numberOfFaces; face++) {
  84638. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84639. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84640. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84641. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84642. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84643. }
  84644. width = Math.max(1.0, width * 0.5);
  84645. height = Math.max(1.0, height * 0.5);
  84646. }
  84647. };
  84648. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84649. // load types
  84650. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84651. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84652. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84653. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84654. return KhronosTextureContainer;
  84655. }());
  84656. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84657. })(BABYLON || (BABYLON = {}));
  84658. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84659. var BABYLON;
  84660. (function (BABYLON) {
  84661. var Debug;
  84662. (function (Debug) {
  84663. /**
  84664. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84665. */
  84666. var SkeletonViewer = /** @class */ (function () {
  84667. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84668. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84669. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84670. this.skeleton = skeleton;
  84671. this.mesh = mesh;
  84672. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84673. this.renderingGroupId = renderingGroupId;
  84674. this.color = BABYLON.Color3.White();
  84675. this._debugLines = new Array();
  84676. this._isEnabled = false;
  84677. this._scene = scene;
  84678. this.update();
  84679. this._renderFunction = this.update.bind(this);
  84680. }
  84681. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84682. get: function () {
  84683. return this._isEnabled;
  84684. },
  84685. set: function (value) {
  84686. if (this._isEnabled === value) {
  84687. return;
  84688. }
  84689. this._isEnabled = value;
  84690. if (value) {
  84691. this._scene.registerBeforeRender(this._renderFunction);
  84692. }
  84693. else {
  84694. this._scene.unregisterBeforeRender(this._renderFunction);
  84695. }
  84696. },
  84697. enumerable: true,
  84698. configurable: true
  84699. });
  84700. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84701. if (x === void 0) { x = 0; }
  84702. if (y === void 0) { y = 0; }
  84703. if (z === void 0) { z = 0; }
  84704. var tmat = BABYLON.Tmp.Matrix[0];
  84705. var parentBone = bone.getParent();
  84706. tmat.copyFrom(bone.getLocalMatrix());
  84707. if (x !== 0 || y !== 0 || z !== 0) {
  84708. var tmat2 = BABYLON.Tmp.Matrix[1];
  84709. BABYLON.Matrix.IdentityToRef(tmat2);
  84710. tmat2.m[12] = x;
  84711. tmat2.m[13] = y;
  84712. tmat2.m[14] = z;
  84713. tmat2.multiplyToRef(tmat, tmat);
  84714. }
  84715. if (parentBone) {
  84716. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84717. }
  84718. tmat.multiplyToRef(meshMat, tmat);
  84719. position.x = tmat.m[12];
  84720. position.y = tmat.m[13];
  84721. position.z = tmat.m[14];
  84722. };
  84723. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84724. var len = bones.length;
  84725. var meshPos = this.mesh.position;
  84726. for (var i = 0; i < len; i++) {
  84727. var bone = bones[i];
  84728. var points = this._debugLines[i];
  84729. if (!points) {
  84730. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84731. this._debugLines[i] = points;
  84732. }
  84733. this._getBonePosition(points[0], bone, meshMat);
  84734. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84735. points[0].subtractInPlace(meshPos);
  84736. points[1].subtractInPlace(meshPos);
  84737. }
  84738. };
  84739. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84740. var len = bones.length;
  84741. var boneNum = 0;
  84742. var meshPos = this.mesh.position;
  84743. for (var i = len - 1; i >= 0; i--) {
  84744. var childBone = bones[i];
  84745. var parentBone = childBone.getParent();
  84746. if (!parentBone) {
  84747. continue;
  84748. }
  84749. var points = this._debugLines[boneNum];
  84750. if (!points) {
  84751. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84752. this._debugLines[boneNum] = points;
  84753. }
  84754. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84755. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84756. points[0].subtractInPlace(meshPos);
  84757. points[1].subtractInPlace(meshPos);
  84758. boneNum++;
  84759. }
  84760. };
  84761. SkeletonViewer.prototype.update = function () {
  84762. if (this.autoUpdateBonesMatrices) {
  84763. this.skeleton.computeAbsoluteTransforms();
  84764. }
  84765. if (this.skeleton.bones[0].length === undefined) {
  84766. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84767. }
  84768. else {
  84769. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84770. }
  84771. if (!this._debugMesh) {
  84772. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84773. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84774. }
  84775. else {
  84776. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84777. }
  84778. this._debugMesh.position.copyFrom(this.mesh.position);
  84779. this._debugMesh.color = this.color;
  84780. };
  84781. SkeletonViewer.prototype.dispose = function () {
  84782. if (this._debugMesh) {
  84783. this.isEnabled = false;
  84784. this._debugMesh.dispose();
  84785. this._debugMesh = null;
  84786. }
  84787. };
  84788. return SkeletonViewer;
  84789. }());
  84790. Debug.SkeletonViewer = SkeletonViewer;
  84791. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84792. })(BABYLON || (BABYLON = {}));
  84793. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84794. /**
  84795. * Module Debug contains the (visual) components to debug a scene correctly
  84796. */
  84797. var BABYLON;
  84798. (function (BABYLON) {
  84799. var Debug;
  84800. (function (Debug) {
  84801. /**
  84802. * The Axes viewer will show 3 axes in a specific point in space
  84803. */
  84804. var AxesViewer = /** @class */ (function () {
  84805. function AxesViewer(scene, scaleLines) {
  84806. if (scaleLines === void 0) { scaleLines = 1; }
  84807. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84808. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84809. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84810. this.scaleLines = 1;
  84811. this.scaleLines = scaleLines;
  84812. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84813. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84814. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84815. this._xmesh.renderingGroupId = 2;
  84816. this._ymesh.renderingGroupId = 2;
  84817. this._zmesh.renderingGroupId = 2;
  84818. this._xmesh.material.checkReadyOnlyOnce = true;
  84819. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84820. this._ymesh.material.checkReadyOnlyOnce = true;
  84821. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84822. this._zmesh.material.checkReadyOnlyOnce = true;
  84823. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84824. this.scene = scene;
  84825. }
  84826. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84827. var scaleLines = this.scaleLines;
  84828. if (this._xmesh) {
  84829. this._xmesh.position.copyFrom(position);
  84830. }
  84831. if (this._ymesh) {
  84832. this._ymesh.position.copyFrom(position);
  84833. }
  84834. if (this._zmesh) {
  84835. this._zmesh.position.copyFrom(position);
  84836. }
  84837. var point2 = this._xline[1];
  84838. point2.x = xaxis.x * scaleLines;
  84839. point2.y = xaxis.y * scaleLines;
  84840. point2.z = xaxis.z * scaleLines;
  84841. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84842. point2 = this._yline[1];
  84843. point2.x = yaxis.x * scaleLines;
  84844. point2.y = yaxis.y * scaleLines;
  84845. point2.z = yaxis.z * scaleLines;
  84846. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84847. point2 = this._zline[1];
  84848. point2.x = zaxis.x * scaleLines;
  84849. point2.y = zaxis.y * scaleLines;
  84850. point2.z = zaxis.z * scaleLines;
  84851. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84852. };
  84853. AxesViewer.prototype.dispose = function () {
  84854. if (this._xmesh) {
  84855. this._xmesh.dispose();
  84856. }
  84857. if (this._ymesh) {
  84858. this._ymesh.dispose();
  84859. }
  84860. if (this._zmesh) {
  84861. this._zmesh.dispose();
  84862. }
  84863. this._xmesh = null;
  84864. this._ymesh = null;
  84865. this._zmesh = null;
  84866. this.scene = null;
  84867. };
  84868. return AxesViewer;
  84869. }());
  84870. Debug.AxesViewer = AxesViewer;
  84871. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84872. })(BABYLON || (BABYLON = {}));
  84873. //# sourceMappingURL=babylon.axesViewer.js.map
  84874. var BABYLON;
  84875. (function (BABYLON) {
  84876. var Debug;
  84877. (function (Debug) {
  84878. /**
  84879. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84880. */
  84881. var BoneAxesViewer = /** @class */ (function (_super) {
  84882. __extends(BoneAxesViewer, _super);
  84883. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84884. if (scaleLines === void 0) { scaleLines = 1; }
  84885. var _this = _super.call(this, scene, scaleLines) || this;
  84886. _this.pos = BABYLON.Vector3.Zero();
  84887. _this.xaxis = BABYLON.Vector3.Zero();
  84888. _this.yaxis = BABYLON.Vector3.Zero();
  84889. _this.zaxis = BABYLON.Vector3.Zero();
  84890. _this.mesh = mesh;
  84891. _this.bone = bone;
  84892. return _this;
  84893. }
  84894. BoneAxesViewer.prototype.update = function () {
  84895. if (!this.mesh || !this.bone) {
  84896. return;
  84897. }
  84898. var bone = this.bone;
  84899. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  84900. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  84901. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  84902. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  84903. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  84904. };
  84905. BoneAxesViewer.prototype.dispose = function () {
  84906. if (this.mesh) {
  84907. this.mesh = null;
  84908. this.bone = null;
  84909. _super.prototype.dispose.call(this);
  84910. }
  84911. };
  84912. return BoneAxesViewer;
  84913. }(Debug.AxesViewer));
  84914. Debug.BoneAxesViewer = BoneAxesViewer;
  84915. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84916. })(BABYLON || (BABYLON = {}));
  84917. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  84918. var BABYLON;
  84919. (function (BABYLON) {
  84920. var RayHelper = /** @class */ (function () {
  84921. function RayHelper(ray) {
  84922. this.ray = ray;
  84923. }
  84924. RayHelper.CreateAndShow = function (ray, scene, color) {
  84925. var helper = new RayHelper(ray);
  84926. helper.show(scene, color);
  84927. return helper;
  84928. };
  84929. RayHelper.prototype.show = function (scene, color) {
  84930. if (!this._renderFunction && this.ray) {
  84931. var ray = this.ray;
  84932. this._renderFunction = this._render.bind(this);
  84933. this._scene = scene;
  84934. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  84935. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  84936. if (this._renderFunction) {
  84937. this._scene.registerBeforeRender(this._renderFunction);
  84938. }
  84939. }
  84940. if (color && this._renderLine) {
  84941. this._renderLine.color.copyFrom(color);
  84942. }
  84943. };
  84944. RayHelper.prototype.hide = function () {
  84945. if (this._renderFunction && this._scene) {
  84946. this._scene.unregisterBeforeRender(this._renderFunction);
  84947. this._scene = null;
  84948. this._renderFunction = null;
  84949. if (this._renderLine) {
  84950. this._renderLine.dispose();
  84951. this._renderLine = null;
  84952. }
  84953. this._renderPoints = [];
  84954. }
  84955. };
  84956. RayHelper.prototype._render = function () {
  84957. var ray = this.ray;
  84958. if (!ray) {
  84959. return;
  84960. }
  84961. var point = this._renderPoints[1];
  84962. var len = Math.min(ray.length, 1000000);
  84963. point.copyFrom(ray.direction);
  84964. point.scaleInPlace(len);
  84965. point.addInPlace(ray.origin);
  84966. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  84967. };
  84968. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  84969. this._attachedToMesh = mesh;
  84970. var ray = this.ray;
  84971. if (!ray) {
  84972. return;
  84973. }
  84974. if (!ray.direction) {
  84975. ray.direction = BABYLON.Vector3.Zero();
  84976. }
  84977. if (!ray.origin) {
  84978. ray.origin = BABYLON.Vector3.Zero();
  84979. }
  84980. if (length) {
  84981. ray.length = length;
  84982. }
  84983. if (!meshSpaceOrigin) {
  84984. meshSpaceOrigin = BABYLON.Vector3.Zero();
  84985. }
  84986. if (!meshSpaceDirection) {
  84987. // -1 so that this will work with Mesh.lookAt
  84988. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  84989. }
  84990. if (!this._meshSpaceDirection) {
  84991. this._meshSpaceDirection = meshSpaceDirection.clone();
  84992. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  84993. }
  84994. else {
  84995. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  84996. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  84997. }
  84998. if (!this._updateToMeshFunction) {
  84999. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85000. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85001. }
  85002. this._updateToMesh();
  85003. };
  85004. RayHelper.prototype.detachFromMesh = function () {
  85005. if (this._attachedToMesh) {
  85006. if (this._updateToMeshFunction) {
  85007. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85008. }
  85009. this._attachedToMesh = null;
  85010. this._updateToMeshFunction = null;
  85011. }
  85012. };
  85013. RayHelper.prototype._updateToMesh = function () {
  85014. var ray = this.ray;
  85015. if (!this._attachedToMesh || !ray) {
  85016. return;
  85017. }
  85018. if (this._attachedToMesh._isDisposed) {
  85019. this.detachFromMesh();
  85020. return;
  85021. }
  85022. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85023. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85024. };
  85025. RayHelper.prototype.dispose = function () {
  85026. this.hide();
  85027. this.detachFromMesh();
  85028. this.ray = null;
  85029. };
  85030. return RayHelper;
  85031. }());
  85032. BABYLON.RayHelper = RayHelper;
  85033. })(BABYLON || (BABYLON = {}));
  85034. //# sourceMappingURL=babylon.rayHelper.js.map
  85035. var BABYLON;
  85036. (function (BABYLON) {
  85037. // load the inspector using require, if not present in the global namespace.
  85038. var DebugLayer = /** @class */ (function () {
  85039. function DebugLayer(scene) {
  85040. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85041. this._scene = scene;
  85042. // load inspector using require, if it doesn't exist on the global namespace.
  85043. }
  85044. /** Creates the inspector window. */
  85045. DebugLayer.prototype._createInspector = function (config) {
  85046. if (config === void 0) { config = {}; }
  85047. var popup = config.popup || false;
  85048. var initialTab = config.initialTab || 0;
  85049. var parentElement = config.parentElement || null;
  85050. if (!this._inspector) {
  85051. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85052. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85053. } // else nothing to do,; instance is already existing
  85054. };
  85055. DebugLayer.prototype.isVisible = function () {
  85056. if (!this._inspector) {
  85057. return false;
  85058. }
  85059. return true;
  85060. };
  85061. DebugLayer.prototype.hide = function () {
  85062. if (this._inspector) {
  85063. try {
  85064. this._inspector.dispose();
  85065. }
  85066. catch (e) {
  85067. // If the inspector has been removed directly from the inspector tool
  85068. }
  85069. this._inspector = null;
  85070. }
  85071. };
  85072. DebugLayer.prototype.show = function (config) {
  85073. if (config === void 0) { config = {}; }
  85074. if (typeof this.BJSINSPECTOR == 'undefined') {
  85075. // Load inspector and add it to the DOM
  85076. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85077. }
  85078. else {
  85079. // Otherwise creates the inspector
  85080. this._createInspector(config);
  85081. }
  85082. };
  85083. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85084. return DebugLayer;
  85085. }());
  85086. BABYLON.DebugLayer = DebugLayer;
  85087. })(BABYLON || (BABYLON = {}));
  85088. //# sourceMappingURL=babylon.debugLayer.js.map
  85089. var BABYLON;
  85090. (function (BABYLON) {
  85091. var Debug;
  85092. (function (Debug) {
  85093. /**
  85094. * Used to show the physics impostor around the specific mesh.
  85095. */
  85096. var PhysicsViewer = /** @class */ (function () {
  85097. function PhysicsViewer(scene) {
  85098. this._impostors = [];
  85099. this._meshes = [];
  85100. this._numMeshes = 0;
  85101. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85102. var physicEngine = this._scene.getPhysicsEngine();
  85103. if (physicEngine) {
  85104. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85105. }
  85106. }
  85107. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85108. var plugin = this._physicsEnginePlugin;
  85109. for (var i = 0; i < this._numMeshes; i++) {
  85110. var impostor = this._impostors[i];
  85111. if (!impostor) {
  85112. continue;
  85113. }
  85114. if (impostor.isDisposed) {
  85115. this.hideImpostor(this._impostors[i--]);
  85116. }
  85117. else {
  85118. var mesh = this._meshes[i];
  85119. if (mesh && plugin) {
  85120. plugin.syncMeshWithImpostor(mesh, impostor);
  85121. }
  85122. }
  85123. }
  85124. };
  85125. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85126. if (!this._scene) {
  85127. return;
  85128. }
  85129. for (var i = 0; i < this._numMeshes; i++) {
  85130. if (this._impostors[i] == impostor) {
  85131. return;
  85132. }
  85133. }
  85134. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85135. if (debugMesh) {
  85136. this._impostors[this._numMeshes] = impostor;
  85137. this._meshes[this._numMeshes] = debugMesh;
  85138. if (this._numMeshes === 0) {
  85139. this._renderFunction = this._updateDebugMeshes.bind(this);
  85140. this._scene.registerBeforeRender(this._renderFunction);
  85141. }
  85142. this._numMeshes++;
  85143. }
  85144. };
  85145. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85146. if (!impostor || !this._scene) {
  85147. return;
  85148. }
  85149. var removed = false;
  85150. for (var i = 0; i < this._numMeshes; i++) {
  85151. if (this._impostors[i] == impostor) {
  85152. var mesh = this._meshes[i];
  85153. if (!mesh) {
  85154. continue;
  85155. }
  85156. this._scene.removeMesh(mesh);
  85157. mesh.dispose();
  85158. this._numMeshes--;
  85159. if (this._numMeshes > 0) {
  85160. this._meshes[i] = this._meshes[this._numMeshes];
  85161. this._impostors[i] = this._impostors[this._numMeshes];
  85162. this._meshes[this._numMeshes] = null;
  85163. this._impostors[this._numMeshes] = null;
  85164. }
  85165. else {
  85166. this._meshes[0] = null;
  85167. this._impostors[0] = null;
  85168. }
  85169. removed = true;
  85170. break;
  85171. }
  85172. }
  85173. if (removed && this._numMeshes === 0) {
  85174. this._scene.unregisterBeforeRender(this._renderFunction);
  85175. }
  85176. };
  85177. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85178. if (!this._debugMaterial) {
  85179. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85180. this._debugMaterial.wireframe = true;
  85181. }
  85182. return this._debugMaterial;
  85183. };
  85184. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85185. if (!this._debugBoxMesh) {
  85186. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85187. this._debugBoxMesh.renderingGroupId = 1;
  85188. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85189. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85190. scene.removeMesh(this._debugBoxMesh);
  85191. }
  85192. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85193. };
  85194. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85195. if (!this._debugSphereMesh) {
  85196. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85197. this._debugSphereMesh.renderingGroupId = 1;
  85198. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85199. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85200. scene.removeMesh(this._debugSphereMesh);
  85201. }
  85202. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85203. };
  85204. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85205. var mesh = null;
  85206. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85207. mesh = this._getDebugBoxMesh(scene);
  85208. impostor.getBoxSizeToRef(mesh.scaling);
  85209. }
  85210. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85211. mesh = this._getDebugSphereMesh(scene);
  85212. var radius = impostor.getRadius();
  85213. mesh.scaling.x = radius * 2;
  85214. mesh.scaling.y = radius * 2;
  85215. mesh.scaling.z = radius * 2;
  85216. }
  85217. return mesh;
  85218. };
  85219. PhysicsViewer.prototype.dispose = function () {
  85220. for (var i = 0; i < this._numMeshes; i++) {
  85221. this.hideImpostor(this._impostors[i]);
  85222. }
  85223. if (this._debugBoxMesh) {
  85224. this._debugBoxMesh.dispose();
  85225. }
  85226. if (this._debugSphereMesh) {
  85227. this._debugSphereMesh.dispose();
  85228. }
  85229. if (this._debugMaterial) {
  85230. this._debugMaterial.dispose();
  85231. }
  85232. this._impostors.length = 0;
  85233. this._scene = null;
  85234. this._physicsEnginePlugin = null;
  85235. };
  85236. return PhysicsViewer;
  85237. }());
  85238. Debug.PhysicsViewer = PhysicsViewer;
  85239. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85240. })(BABYLON || (BABYLON = {}));
  85241. //# sourceMappingURL=babylon.physicsViewer.js.map
  85242. var BABYLON;
  85243. (function (BABYLON) {
  85244. var BoundingBoxRenderer = /** @class */ (function () {
  85245. function BoundingBoxRenderer(scene) {
  85246. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85247. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85248. this.showBackLines = true;
  85249. this.renderList = new BABYLON.SmartArray(32);
  85250. this._vertexBuffers = {};
  85251. this._scene = scene;
  85252. }
  85253. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85254. if (this._colorShader) {
  85255. return;
  85256. }
  85257. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85258. attributes: [BABYLON.VertexBuffer.PositionKind],
  85259. uniforms: ["world", "viewProjection", "color"]
  85260. });
  85261. var engine = this._scene.getEngine();
  85262. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85263. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85264. this._createIndexBuffer();
  85265. };
  85266. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85267. var engine = this._scene.getEngine();
  85268. 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]);
  85269. };
  85270. BoundingBoxRenderer.prototype._rebuild = function () {
  85271. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85272. if (vb) {
  85273. vb._rebuild();
  85274. }
  85275. this._createIndexBuffer();
  85276. };
  85277. BoundingBoxRenderer.prototype.reset = function () {
  85278. this.renderList.reset();
  85279. };
  85280. BoundingBoxRenderer.prototype.render = function () {
  85281. if (this.renderList.length === 0) {
  85282. return;
  85283. }
  85284. this._prepareRessources();
  85285. if (!this._colorShader.isReady()) {
  85286. return;
  85287. }
  85288. var engine = this._scene.getEngine();
  85289. engine.setDepthWrite(false);
  85290. this._colorShader._preBind();
  85291. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85292. var boundingBox = this.renderList.data[boundingBoxIndex];
  85293. var min = boundingBox.minimum;
  85294. var max = boundingBox.maximum;
  85295. var diff = max.subtract(min);
  85296. var median = min.add(diff.scale(0.5));
  85297. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85298. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85299. .multiply(boundingBox.getWorldMatrix());
  85300. // VBOs
  85301. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85302. if (this.showBackLines) {
  85303. // Back
  85304. engine.setDepthFunctionToGreaterOrEqual();
  85305. this._scene.resetCachedMaterial();
  85306. this._colorShader.setColor4("color", this.backColor.toColor4());
  85307. this._colorShader.bind(worldMatrix);
  85308. // Draw order
  85309. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85310. }
  85311. // Front
  85312. engine.setDepthFunctionToLess();
  85313. this._scene.resetCachedMaterial();
  85314. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85315. this._colorShader.bind(worldMatrix);
  85316. // Draw order
  85317. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85318. }
  85319. this._colorShader.unbind();
  85320. engine.setDepthFunctionToLessOrEqual();
  85321. engine.setDepthWrite(true);
  85322. };
  85323. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85324. this._prepareRessources();
  85325. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85326. return;
  85327. }
  85328. var engine = this._scene.getEngine();
  85329. engine.setDepthWrite(false);
  85330. engine.setColorWrite(false);
  85331. this._colorShader._preBind();
  85332. var boundingBox = mesh._boundingInfo.boundingBox;
  85333. var min = boundingBox.minimum;
  85334. var max = boundingBox.maximum;
  85335. var diff = max.subtract(min);
  85336. var median = min.add(diff.scale(0.5));
  85337. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85338. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85339. .multiply(boundingBox.getWorldMatrix());
  85340. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85341. engine.setDepthFunctionToLess();
  85342. this._scene.resetCachedMaterial();
  85343. this._colorShader.bind(worldMatrix);
  85344. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85345. this._colorShader.unbind();
  85346. engine.setDepthFunctionToLessOrEqual();
  85347. engine.setDepthWrite(true);
  85348. engine.setColorWrite(true);
  85349. };
  85350. BoundingBoxRenderer.prototype.dispose = function () {
  85351. if (!this._colorShader) {
  85352. return;
  85353. }
  85354. this.renderList.dispose();
  85355. this._colorShader.dispose();
  85356. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85357. if (buffer) {
  85358. buffer.dispose();
  85359. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85360. }
  85361. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85362. };
  85363. return BoundingBoxRenderer;
  85364. }());
  85365. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85366. })(BABYLON || (BABYLON = {}));
  85367. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85368. var BABYLON;
  85369. (function (BABYLON) {
  85370. /**
  85371. * Defines a target to use with MorphTargetManager
  85372. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85373. */
  85374. var MorphTarget = /** @class */ (function () {
  85375. /**
  85376. * Creates a new MorphTarget
  85377. * @param name defines the name of the target
  85378. * @param influence defines the influence to use
  85379. */
  85380. function MorphTarget(
  85381. /** defines the name of the target */
  85382. name, influence) {
  85383. if (influence === void 0) { influence = 0; }
  85384. this.name = name;
  85385. /**
  85386. * Gets or sets the list of animations
  85387. */
  85388. this.animations = new Array();
  85389. this._positions = null;
  85390. this._normals = null;
  85391. this._tangents = null;
  85392. /**
  85393. * Observable raised when the influence changes
  85394. */
  85395. this.onInfluenceChanged = new BABYLON.Observable();
  85396. this.influence = influence;
  85397. }
  85398. Object.defineProperty(MorphTarget.prototype, "influence", {
  85399. /**
  85400. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85401. */
  85402. get: function () {
  85403. return this._influence;
  85404. },
  85405. set: function (influence) {
  85406. if (this._influence === influence) {
  85407. return;
  85408. }
  85409. var previous = this._influence;
  85410. this._influence = influence;
  85411. if (this.onInfluenceChanged.hasObservers) {
  85412. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85413. }
  85414. },
  85415. enumerable: true,
  85416. configurable: true
  85417. });
  85418. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85419. /**
  85420. * Gets a boolean defining if the target contains position data
  85421. */
  85422. get: function () {
  85423. return !!this._positions;
  85424. },
  85425. enumerable: true,
  85426. configurable: true
  85427. });
  85428. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85429. /**
  85430. * Gets a boolean defining if the target contains normal data
  85431. */
  85432. get: function () {
  85433. return !!this._normals;
  85434. },
  85435. enumerable: true,
  85436. configurable: true
  85437. });
  85438. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85439. /**
  85440. * Gets a boolean defining if the target contains tangent data
  85441. */
  85442. get: function () {
  85443. return !!this._tangents;
  85444. },
  85445. enumerable: true,
  85446. configurable: true
  85447. });
  85448. /**
  85449. * Affects position data to this target
  85450. * @param data defines the position data to use
  85451. */
  85452. MorphTarget.prototype.setPositions = function (data) {
  85453. this._positions = data;
  85454. };
  85455. /**
  85456. * Gets the position data stored in this target
  85457. * @returns a FloatArray containing the position data (or null if not present)
  85458. */
  85459. MorphTarget.prototype.getPositions = function () {
  85460. return this._positions;
  85461. };
  85462. /**
  85463. * Affects normal data to this target
  85464. * @param data defines the normal data to use
  85465. */
  85466. MorphTarget.prototype.setNormals = function (data) {
  85467. this._normals = data;
  85468. };
  85469. /**
  85470. * Gets the normal data stored in this target
  85471. * @returns a FloatArray containing the normal data (or null if not present)
  85472. */
  85473. MorphTarget.prototype.getNormals = function () {
  85474. return this._normals;
  85475. };
  85476. /**
  85477. * Affects tangent data to this target
  85478. * @param data defines the tangent data to use
  85479. */
  85480. MorphTarget.prototype.setTangents = function (data) {
  85481. this._tangents = data;
  85482. };
  85483. /**
  85484. * Gets the tangent data stored in this target
  85485. * @returns a FloatArray containing the tangent data (or null if not present)
  85486. */
  85487. MorphTarget.prototype.getTangents = function () {
  85488. return this._tangents;
  85489. };
  85490. /**
  85491. * Serializes the current target into a Serialization object
  85492. * @returns the serialized object
  85493. */
  85494. MorphTarget.prototype.serialize = function () {
  85495. var serializationObject = {};
  85496. serializationObject.name = this.name;
  85497. serializationObject.influence = this.influence;
  85498. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85499. if (this.hasNormals) {
  85500. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85501. }
  85502. if (this.hasTangents) {
  85503. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85504. }
  85505. // Animations
  85506. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85507. return serializationObject;
  85508. };
  85509. // Statics
  85510. /**
  85511. * Creates a new target from serialized data
  85512. * @param serializationObject defines the serialized data to use
  85513. * @returns a new MorphTarget
  85514. */
  85515. MorphTarget.Parse = function (serializationObject) {
  85516. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85517. result.setPositions(serializationObject.positions);
  85518. if (serializationObject.normals) {
  85519. result.setNormals(serializationObject.normals);
  85520. }
  85521. if (serializationObject.tangents) {
  85522. result.setTangents(serializationObject.tangents);
  85523. }
  85524. // Animations
  85525. if (serializationObject.animations) {
  85526. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85527. var parsedAnimation = serializationObject.animations[animationIndex];
  85528. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85529. }
  85530. }
  85531. return result;
  85532. };
  85533. /**
  85534. * Creates a MorphTarget from mesh data
  85535. * @param mesh defines the source mesh
  85536. * @param name defines the name to use for the new target
  85537. * @param influence defines the influence to attach to the target
  85538. * @returns a new MorphTarget
  85539. */
  85540. MorphTarget.FromMesh = function (mesh, name, influence) {
  85541. if (!name) {
  85542. name = mesh.name;
  85543. }
  85544. var result = new MorphTarget(name, influence);
  85545. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85546. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85547. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85548. }
  85549. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85550. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85551. }
  85552. return result;
  85553. };
  85554. return MorphTarget;
  85555. }());
  85556. BABYLON.MorphTarget = MorphTarget;
  85557. })(BABYLON || (BABYLON = {}));
  85558. //# sourceMappingURL=babylon.morphTarget.js.map
  85559. var BABYLON;
  85560. (function (BABYLON) {
  85561. /**
  85562. * This class is used to deform meshes using morphing between different targets
  85563. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85564. */
  85565. var MorphTargetManager = /** @class */ (function () {
  85566. /**
  85567. * Creates a new MorphTargetManager
  85568. * @param scene defines the current scene
  85569. */
  85570. function MorphTargetManager(scene) {
  85571. if (scene === void 0) { scene = null; }
  85572. this._targets = new Array();
  85573. this._targetObservable = new Array();
  85574. this._activeTargets = new BABYLON.SmartArray(16);
  85575. this._supportsNormals = false;
  85576. this._supportsTangents = false;
  85577. this._vertexCount = 0;
  85578. this._uniqueId = 0;
  85579. this._tempInfluences = new Array();
  85580. if (!scene) {
  85581. scene = BABYLON.Engine.LastCreatedScene;
  85582. }
  85583. this._scene = scene;
  85584. if (this._scene) {
  85585. this._scene.morphTargetManagers.push(this);
  85586. this._uniqueId = this._scene.getUniqueId();
  85587. }
  85588. }
  85589. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85590. /**
  85591. * Gets the unique ID of this manager
  85592. */
  85593. get: function () {
  85594. return this._uniqueId;
  85595. },
  85596. enumerable: true,
  85597. configurable: true
  85598. });
  85599. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85600. /**
  85601. * Gets the number of vertices handled by this manager
  85602. */
  85603. get: function () {
  85604. return this._vertexCount;
  85605. },
  85606. enumerable: true,
  85607. configurable: true
  85608. });
  85609. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85610. /**
  85611. * Gets a boolean indicating if this manager supports morphing of normals
  85612. */
  85613. get: function () {
  85614. return this._supportsNormals;
  85615. },
  85616. enumerable: true,
  85617. configurable: true
  85618. });
  85619. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85620. /**
  85621. * Gets a boolean indicating if this manager supports morphing of tangents
  85622. */
  85623. get: function () {
  85624. return this._supportsTangents;
  85625. },
  85626. enumerable: true,
  85627. configurable: true
  85628. });
  85629. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85630. /**
  85631. * Gets the number of targets stored in this manager
  85632. */
  85633. get: function () {
  85634. return this._targets.length;
  85635. },
  85636. enumerable: true,
  85637. configurable: true
  85638. });
  85639. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85640. /**
  85641. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85642. */
  85643. get: function () {
  85644. return this._activeTargets.length;
  85645. },
  85646. enumerable: true,
  85647. configurable: true
  85648. });
  85649. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85650. /**
  85651. * Gets the list of influences (one per target)
  85652. */
  85653. get: function () {
  85654. return this._influences;
  85655. },
  85656. enumerable: true,
  85657. configurable: true
  85658. });
  85659. /**
  85660. * Gets the active target at specified index. An active target is a target with an influence > 0
  85661. * @param index defines the index to check
  85662. * @returns the requested target
  85663. */
  85664. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85665. return this._activeTargets.data[index];
  85666. };
  85667. /**
  85668. * Gets the target at specified index
  85669. * @param index defines the index to check
  85670. * @returns the requested target
  85671. */
  85672. MorphTargetManager.prototype.getTarget = function (index) {
  85673. return this._targets[index];
  85674. };
  85675. /**
  85676. * Add a new target to this manager
  85677. * @param target defines the target to add
  85678. */
  85679. MorphTargetManager.prototype.addTarget = function (target) {
  85680. var _this = this;
  85681. this._targets.push(target);
  85682. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85683. _this._syncActiveTargets(needUpdate);
  85684. }));
  85685. this._syncActiveTargets(true);
  85686. };
  85687. /**
  85688. * Removes a target from the manager
  85689. * @param target defines the target to remove
  85690. */
  85691. MorphTargetManager.prototype.removeTarget = function (target) {
  85692. var index = this._targets.indexOf(target);
  85693. if (index >= 0) {
  85694. this._targets.splice(index, 1);
  85695. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85696. this._syncActiveTargets(true);
  85697. }
  85698. };
  85699. /**
  85700. * Serializes the current manager into a Serialization object
  85701. * @returns the serialized object
  85702. */
  85703. MorphTargetManager.prototype.serialize = function () {
  85704. var serializationObject = {};
  85705. serializationObject.id = this.uniqueId;
  85706. serializationObject.targets = [];
  85707. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85708. var target = _a[_i];
  85709. serializationObject.targets.push(target.serialize());
  85710. }
  85711. return serializationObject;
  85712. };
  85713. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85714. var influenceCount = 0;
  85715. this._activeTargets.reset();
  85716. this._supportsNormals = true;
  85717. this._supportsTangents = true;
  85718. this._vertexCount = 0;
  85719. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85720. var target = _a[_i];
  85721. this._activeTargets.push(target);
  85722. this._tempInfluences[influenceCount++] = target.influence;
  85723. var positions = target.getPositions();
  85724. if (positions) {
  85725. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85726. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85727. var vertexCount = positions.length / 3;
  85728. if (this._vertexCount === 0) {
  85729. this._vertexCount = vertexCount;
  85730. }
  85731. else if (this._vertexCount !== vertexCount) {
  85732. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85733. return;
  85734. }
  85735. }
  85736. }
  85737. if (!this._influences || this._influences.length !== influenceCount) {
  85738. this._influences = new Float32Array(influenceCount);
  85739. }
  85740. for (var index = 0; index < influenceCount; index++) {
  85741. this._influences[index] = this._tempInfluences[index];
  85742. }
  85743. if (needUpdate) {
  85744. this.synchronize();
  85745. }
  85746. };
  85747. /**
  85748. * Syncrhonize the targets with all the meshes using this morph target manager
  85749. */
  85750. MorphTargetManager.prototype.synchronize = function () {
  85751. if (!this._scene) {
  85752. return;
  85753. }
  85754. // Flag meshes as dirty to resync with the active targets
  85755. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85756. var mesh = _a[_i];
  85757. if (mesh.morphTargetManager === this) {
  85758. mesh._syncGeometryWithMorphTargetManager();
  85759. }
  85760. }
  85761. };
  85762. // Statics
  85763. /**
  85764. * Creates a new MorphTargetManager from serialized data
  85765. * @param serializationObject defines the serialized data
  85766. * @param scene defines the hosting scene
  85767. * @returns the new MorphTargetManager
  85768. */
  85769. MorphTargetManager.Parse = function (serializationObject, scene) {
  85770. var result = new MorphTargetManager(scene);
  85771. result._uniqueId = serializationObject.id;
  85772. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85773. var targetData = _a[_i];
  85774. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85775. }
  85776. return result;
  85777. };
  85778. return MorphTargetManager;
  85779. }());
  85780. BABYLON.MorphTargetManager = MorphTargetManager;
  85781. })(BABYLON || (BABYLON = {}));
  85782. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85783. var BABYLON;
  85784. (function (BABYLON) {
  85785. var Octree = /** @class */ (function () {
  85786. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85787. if (maxDepth === void 0) { maxDepth = 2; }
  85788. this.maxDepth = maxDepth;
  85789. this.dynamicContent = new Array();
  85790. this._maxBlockCapacity = maxBlockCapacity || 64;
  85791. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85792. this._creationFunc = creationFunc;
  85793. }
  85794. // Methods
  85795. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85796. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85797. };
  85798. Octree.prototype.addMesh = function (entry) {
  85799. for (var index = 0; index < this.blocks.length; index++) {
  85800. var block = this.blocks[index];
  85801. block.addEntry(entry);
  85802. }
  85803. };
  85804. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85805. this._selectionContent.reset();
  85806. for (var index = 0; index < this.blocks.length; index++) {
  85807. var block = this.blocks[index];
  85808. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85809. }
  85810. if (allowDuplicate) {
  85811. this._selectionContent.concat(this.dynamicContent);
  85812. }
  85813. else {
  85814. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85815. }
  85816. return this._selectionContent;
  85817. };
  85818. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85819. this._selectionContent.reset();
  85820. for (var index = 0; index < this.blocks.length; index++) {
  85821. var block = this.blocks[index];
  85822. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85823. }
  85824. if (allowDuplicate) {
  85825. this._selectionContent.concat(this.dynamicContent);
  85826. }
  85827. else {
  85828. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85829. }
  85830. return this._selectionContent;
  85831. };
  85832. Octree.prototype.intersectsRay = function (ray) {
  85833. this._selectionContent.reset();
  85834. for (var index = 0; index < this.blocks.length; index++) {
  85835. var block = this.blocks[index];
  85836. block.intersectsRay(ray, this._selectionContent);
  85837. }
  85838. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85839. return this._selectionContent;
  85840. };
  85841. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85842. target.blocks = new Array();
  85843. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85844. // Segmenting space
  85845. for (var x = 0; x < 2; x++) {
  85846. for (var y = 0; y < 2; y++) {
  85847. for (var z = 0; z < 2; z++) {
  85848. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85849. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85850. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85851. block.addEntries(entries);
  85852. target.blocks.push(block);
  85853. }
  85854. }
  85855. }
  85856. };
  85857. Octree.CreationFuncForMeshes = function (entry, block) {
  85858. var boundingInfo = entry.getBoundingInfo();
  85859. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85860. block.entries.push(entry);
  85861. }
  85862. };
  85863. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85864. var boundingInfo = entry.getBoundingInfo();
  85865. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85866. block.entries.push(entry);
  85867. }
  85868. };
  85869. return Octree;
  85870. }());
  85871. BABYLON.Octree = Octree;
  85872. })(BABYLON || (BABYLON = {}));
  85873. //# sourceMappingURL=babylon.octree.js.map
  85874. var BABYLON;
  85875. (function (BABYLON) {
  85876. var OctreeBlock = /** @class */ (function () {
  85877. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  85878. this.entries = new Array();
  85879. this._boundingVectors = new Array();
  85880. this._capacity = capacity;
  85881. this._depth = depth;
  85882. this._maxDepth = maxDepth;
  85883. this._creationFunc = creationFunc;
  85884. this._minPoint = minPoint;
  85885. this._maxPoint = maxPoint;
  85886. this._boundingVectors.push(minPoint.clone());
  85887. this._boundingVectors.push(maxPoint.clone());
  85888. this._boundingVectors.push(minPoint.clone());
  85889. this._boundingVectors[2].x = maxPoint.x;
  85890. this._boundingVectors.push(minPoint.clone());
  85891. this._boundingVectors[3].y = maxPoint.y;
  85892. this._boundingVectors.push(minPoint.clone());
  85893. this._boundingVectors[4].z = maxPoint.z;
  85894. this._boundingVectors.push(maxPoint.clone());
  85895. this._boundingVectors[5].z = minPoint.z;
  85896. this._boundingVectors.push(maxPoint.clone());
  85897. this._boundingVectors[6].x = minPoint.x;
  85898. this._boundingVectors.push(maxPoint.clone());
  85899. this._boundingVectors[7].y = minPoint.y;
  85900. }
  85901. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  85902. // Property
  85903. get: function () {
  85904. return this._capacity;
  85905. },
  85906. enumerable: true,
  85907. configurable: true
  85908. });
  85909. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  85910. get: function () {
  85911. return this._minPoint;
  85912. },
  85913. enumerable: true,
  85914. configurable: true
  85915. });
  85916. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  85917. get: function () {
  85918. return this._maxPoint;
  85919. },
  85920. enumerable: true,
  85921. configurable: true
  85922. });
  85923. // Methods
  85924. OctreeBlock.prototype.addEntry = function (entry) {
  85925. if (this.blocks) {
  85926. for (var index = 0; index < this.blocks.length; index++) {
  85927. var block = this.blocks[index];
  85928. block.addEntry(entry);
  85929. }
  85930. return;
  85931. }
  85932. this._creationFunc(entry, this);
  85933. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  85934. this.createInnerBlocks();
  85935. }
  85936. };
  85937. OctreeBlock.prototype.addEntries = function (entries) {
  85938. for (var index = 0; index < entries.length; index++) {
  85939. var mesh = entries[index];
  85940. this.addEntry(mesh);
  85941. }
  85942. };
  85943. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  85944. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  85945. if (this.blocks) {
  85946. for (var index = 0; index < this.blocks.length; index++) {
  85947. var block = this.blocks[index];
  85948. block.select(frustumPlanes, selection, allowDuplicate);
  85949. }
  85950. return;
  85951. }
  85952. if (allowDuplicate) {
  85953. selection.concat(this.entries);
  85954. }
  85955. else {
  85956. selection.concatWithNoDuplicate(this.entries);
  85957. }
  85958. }
  85959. };
  85960. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  85961. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  85962. if (this.blocks) {
  85963. for (var index = 0; index < this.blocks.length; index++) {
  85964. var block = this.blocks[index];
  85965. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  85966. }
  85967. return;
  85968. }
  85969. if (allowDuplicate) {
  85970. selection.concat(this.entries);
  85971. }
  85972. else {
  85973. selection.concatWithNoDuplicate(this.entries);
  85974. }
  85975. }
  85976. };
  85977. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  85978. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  85979. if (this.blocks) {
  85980. for (var index = 0; index < this.blocks.length; index++) {
  85981. var block = this.blocks[index];
  85982. block.intersectsRay(ray, selection);
  85983. }
  85984. return;
  85985. }
  85986. selection.concatWithNoDuplicate(this.entries);
  85987. }
  85988. };
  85989. OctreeBlock.prototype.createInnerBlocks = function () {
  85990. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  85991. };
  85992. return OctreeBlock;
  85993. }());
  85994. BABYLON.OctreeBlock = OctreeBlock;
  85995. })(BABYLON || (BABYLON = {}));
  85996. //# sourceMappingURL=babylon.octreeBlock.js.map
  85997. var BABYLON;
  85998. (function (BABYLON) {
  85999. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86000. __extends(VRDistortionCorrectionPostProcess, _super);
  86001. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86002. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86003. 'LensCenter',
  86004. 'Scale',
  86005. 'ScaleIn',
  86006. 'HmdWarpParam'
  86007. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86008. _this._isRightEye = isRightEye;
  86009. _this._distortionFactors = vrMetrics.distortionK;
  86010. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86011. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86012. _this.adaptScaleToCurrentViewport = true;
  86013. _this.onSizeChangedObservable.add(function () {
  86014. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86015. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86016. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86017. });
  86018. _this.onApplyObservable.add(function (effect) {
  86019. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86020. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86021. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86022. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86023. });
  86024. return _this;
  86025. }
  86026. return VRDistortionCorrectionPostProcess;
  86027. }(BABYLON.PostProcess));
  86028. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86029. })(BABYLON || (BABYLON = {}));
  86030. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86031. var BABYLON;
  86032. (function (BABYLON) {
  86033. /**
  86034. * Postprocess used to generate anaglyphic rendering
  86035. */
  86036. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86037. __extends(AnaglyphPostProcess, _super);
  86038. /**
  86039. * Creates a new AnaglyphPostProcess
  86040. * @param name defines postprocess name
  86041. * @param options defines creation options or target ratio scale
  86042. * @param rigCameras defines cameras using this postprocess
  86043. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86044. * @param engine defines hosting engine
  86045. * @param reusable defines if the postprocess will be reused multiple times per frame
  86046. */
  86047. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86048. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86049. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86050. _this.onApplyObservable.add(function (effect) {
  86051. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86052. });
  86053. return _this;
  86054. }
  86055. return AnaglyphPostProcess;
  86056. }(BABYLON.PostProcess));
  86057. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86058. })(BABYLON || (BABYLON = {}));
  86059. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86060. var BABYLON;
  86061. (function (BABYLON) {
  86062. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86063. __extends(StereoscopicInterlacePostProcess, _super);
  86064. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86065. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86066. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86067. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86068. _this.onSizeChangedObservable.add(function () {
  86069. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86070. });
  86071. _this.onApplyObservable.add(function (effect) {
  86072. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86073. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86074. });
  86075. return _this;
  86076. }
  86077. return StereoscopicInterlacePostProcess;
  86078. }(BABYLON.PostProcess));
  86079. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86080. })(BABYLON || (BABYLON = {}));
  86081. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86082. var BABYLON;
  86083. (function (BABYLON) {
  86084. /**
  86085. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86086. * Screen rotation is taken into account.
  86087. */
  86088. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86089. function FreeCameraDeviceOrientationInput() {
  86090. var _this = this;
  86091. this._screenOrientationAngle = 0;
  86092. this._screenQuaternion = new BABYLON.Quaternion();
  86093. this._alpha = 0;
  86094. this._beta = 0;
  86095. this._gamma = 0;
  86096. this._orientationChanged = function () {
  86097. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86098. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86099. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86100. };
  86101. this._deviceOrientation = function (evt) {
  86102. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86103. _this._beta = evt.beta !== null ? evt.beta : 0;
  86104. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86105. };
  86106. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86107. this._orientationChanged();
  86108. }
  86109. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86110. get: function () {
  86111. return this._camera;
  86112. },
  86113. set: function (camera) {
  86114. this._camera = camera;
  86115. if (this._camera != null && !this._camera.rotationQuaternion) {
  86116. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86117. }
  86118. },
  86119. enumerable: true,
  86120. configurable: true
  86121. });
  86122. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86123. window.addEventListener("orientationchange", this._orientationChanged);
  86124. window.addEventListener("deviceorientation", this._deviceOrientation);
  86125. //In certain cases, the attach control is called AFTER orientation was changed,
  86126. //So this is needed.
  86127. this._orientationChanged();
  86128. };
  86129. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86130. window.removeEventListener("orientationchange", this._orientationChanged);
  86131. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86132. };
  86133. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86134. //if no device orientation provided, don't update the rotation.
  86135. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86136. if (!this._alpha)
  86137. return;
  86138. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86139. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86140. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86141. //Mirror on XY Plane
  86142. this._camera.rotationQuaternion.z *= -1;
  86143. this._camera.rotationQuaternion.w *= -1;
  86144. };
  86145. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86146. return "FreeCameraDeviceOrientationInput";
  86147. };
  86148. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86149. return "deviceOrientation";
  86150. };
  86151. return FreeCameraDeviceOrientationInput;
  86152. }());
  86153. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86154. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86155. })(BABYLON || (BABYLON = {}));
  86156. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86157. var BABYLON;
  86158. (function (BABYLON) {
  86159. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86160. function ArcRotateCameraVRDeviceOrientationInput() {
  86161. this.alphaCorrection = 1;
  86162. this.betaCorrection = 1;
  86163. this.gammaCorrection = 1;
  86164. this._alpha = 0;
  86165. this._gamma = 0;
  86166. this._dirty = false;
  86167. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86168. }
  86169. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86170. this.camera.attachControl(element, noPreventDefault);
  86171. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86172. };
  86173. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86174. if (evt.alpha !== null) {
  86175. this._alpha = +evt.alpha | 0;
  86176. }
  86177. if (evt.gamma !== null) {
  86178. this._gamma = +evt.gamma | 0;
  86179. }
  86180. this._dirty = true;
  86181. };
  86182. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86183. if (this._dirty) {
  86184. this._dirty = false;
  86185. if (this._gamma < 0) {
  86186. this._gamma = 180 + this._gamma;
  86187. }
  86188. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86189. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86190. }
  86191. };
  86192. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86193. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86194. };
  86195. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86196. return "ArcRotateCameraVRDeviceOrientationInput";
  86197. };
  86198. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86199. return "VRDeviceOrientation";
  86200. };
  86201. return ArcRotateCameraVRDeviceOrientationInput;
  86202. }());
  86203. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86204. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86205. })(BABYLON || (BABYLON = {}));
  86206. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86207. var BABYLON;
  86208. (function (BABYLON) {
  86209. var VRCameraMetrics = /** @class */ (function () {
  86210. function VRCameraMetrics() {
  86211. this.compensateDistortion = true;
  86212. }
  86213. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86214. get: function () {
  86215. return this.hResolution / (2 * this.vResolution);
  86216. },
  86217. enumerable: true,
  86218. configurable: true
  86219. });
  86220. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86221. get: function () {
  86222. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86223. },
  86224. enumerable: true,
  86225. configurable: true
  86226. });
  86227. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86228. get: function () {
  86229. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86230. var h = (4 * meters) / this.hScreenSize;
  86231. return BABYLON.Matrix.Translation(h, 0, 0);
  86232. },
  86233. enumerable: true,
  86234. configurable: true
  86235. });
  86236. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86237. get: function () {
  86238. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86239. var h = (4 * meters) / this.hScreenSize;
  86240. return BABYLON.Matrix.Translation(-h, 0, 0);
  86241. },
  86242. enumerable: true,
  86243. configurable: true
  86244. });
  86245. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86246. get: function () {
  86247. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86248. },
  86249. enumerable: true,
  86250. configurable: true
  86251. });
  86252. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86253. get: function () {
  86254. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86255. },
  86256. enumerable: true,
  86257. configurable: true
  86258. });
  86259. VRCameraMetrics.GetDefault = function () {
  86260. var result = new VRCameraMetrics();
  86261. result.hResolution = 1280;
  86262. result.vResolution = 800;
  86263. result.hScreenSize = 0.149759993;
  86264. result.vScreenSize = 0.0935999975;
  86265. result.vScreenCenter = 0.0467999987;
  86266. result.eyeToScreenDistance = 0.0410000011;
  86267. result.lensSeparationDistance = 0.0635000020;
  86268. result.interpupillaryDistance = 0.0640000030;
  86269. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86270. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86271. result.postProcessScaleFactor = 1.714605507808412;
  86272. result.lensCenterOffset = 0.151976421;
  86273. return result;
  86274. };
  86275. return VRCameraMetrics;
  86276. }());
  86277. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86278. })(BABYLON || (BABYLON = {}));
  86279. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86280. var BABYLON;
  86281. (function (BABYLON) {
  86282. /**
  86283. * This represents a WebVR camera.
  86284. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86285. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86286. */
  86287. var WebVRFreeCamera = /** @class */ (function (_super) {
  86288. __extends(WebVRFreeCamera, _super);
  86289. /**
  86290. * Instantiates a WebVRFreeCamera.
  86291. * @param name The name of the WebVRFreeCamera
  86292. * @param position The starting anchor position for the camera
  86293. * @param scene The scene the camera belongs to
  86294. * @param webVROptions a set of customizable options for the webVRCamera
  86295. */
  86296. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86297. if (webVROptions === void 0) { webVROptions = {}; }
  86298. var _this = _super.call(this, name, position, scene) || this;
  86299. _this.webVROptions = webVROptions;
  86300. /**
  86301. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86302. */
  86303. _this._vrDevice = null;
  86304. /**
  86305. * The rawPose of the vrDevice.
  86306. */
  86307. _this.rawPose = null;
  86308. _this._specsVersion = "1.1";
  86309. _this._attached = false;
  86310. _this._descendants = [];
  86311. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86312. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86313. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86314. _this._standingMatrix = null;
  86315. /**
  86316. * Represents device position in babylon space.
  86317. */
  86318. _this.devicePosition = BABYLON.Vector3.Zero();
  86319. /**
  86320. * Represents device rotation in babylon space.
  86321. */
  86322. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86323. /**
  86324. * The scale of the device to be used when translating from device space to babylon space.
  86325. */
  86326. _this.deviceScaleFactor = 1;
  86327. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86328. _this._worldToDevice = BABYLON.Matrix.Identity();
  86329. /**
  86330. * References to the webVR controllers for the vrDevice.
  86331. */
  86332. _this.controllers = [];
  86333. /**
  86334. * Emits an event when a controller is attached.
  86335. */
  86336. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86337. /**
  86338. * Emits an event when a controller's mesh has been loaded;
  86339. */
  86340. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86341. /**
  86342. * If the rig cameras be used as parent instead of this camera.
  86343. */
  86344. _this.rigParenting = true;
  86345. _this._defaultHeight = undefined;
  86346. _this._workingVector = BABYLON.Vector3.Zero();
  86347. _this._oneVector = BABYLON.Vector3.One();
  86348. _this._workingMatrix = BABYLON.Matrix.Identity();
  86349. _this._cache.position = BABYLON.Vector3.Zero();
  86350. if (webVROptions.defaultHeight) {
  86351. _this._defaultHeight = webVROptions.defaultHeight;
  86352. _this.position.y = _this._defaultHeight;
  86353. }
  86354. _this.minZ = 0.1;
  86355. //legacy support - the compensation boolean was removed.
  86356. if (arguments.length === 5) {
  86357. _this.webVROptions = arguments[4];
  86358. }
  86359. // default webVR options
  86360. if (_this.webVROptions.trackPosition == undefined) {
  86361. _this.webVROptions.trackPosition = true;
  86362. }
  86363. if (_this.webVROptions.controllerMeshes == undefined) {
  86364. _this.webVROptions.controllerMeshes = true;
  86365. }
  86366. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86367. _this.webVROptions.defaultLightingOnControllers = true;
  86368. }
  86369. _this.rotationQuaternion = new BABYLON.Quaternion();
  86370. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86371. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86372. }
  86373. //enable VR
  86374. var engine = _this.getEngine();
  86375. _this._onVREnabled = function (success) { if (success) {
  86376. _this.initControllers();
  86377. } };
  86378. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86379. engine.initWebVR().add(function (event) {
  86380. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86381. return;
  86382. }
  86383. _this._vrDevice = event.vrDisplay;
  86384. //reset the rig parameters.
  86385. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86386. if (_this._attached) {
  86387. _this.getEngine().enableVR();
  86388. }
  86389. });
  86390. if (typeof (VRFrameData) !== "undefined")
  86391. _this._frameData = new VRFrameData();
  86392. /**
  86393. * The idea behind the following lines:
  86394. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86395. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86396. * the second will not show it correctly.
  86397. *
  86398. * To solve this - each object that has the camera as parent will be added to a protected array.
  86399. * When the rig camera renders, it will take this array and set all of those to be its children.
  86400. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86401. * Amazing!
  86402. */
  86403. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86404. if (camera.parent === _this && _this.rigParenting) {
  86405. _this._descendants = _this.getDescendants(true, function (n) {
  86406. // don't take the cameras or the controllers!
  86407. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86408. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86409. return !isController && !isRigCamera;
  86410. });
  86411. _this._descendants.forEach(function (node) {
  86412. node.parent = camera;
  86413. });
  86414. }
  86415. });
  86416. scene.onAfterCameraRenderObservable.add(function (camera) {
  86417. if (camera.parent === _this && _this.rigParenting) {
  86418. _this._descendants.forEach(function (node) {
  86419. node.parent = _this;
  86420. });
  86421. }
  86422. });
  86423. return _this;
  86424. }
  86425. /**
  86426. * Gets the device distance from the ground in meters.
  86427. * @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.
  86428. */
  86429. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86430. if (this._standingMatrix) {
  86431. // Add standing matrix offset to get real offset from ground in room
  86432. this._standingMatrix.getTranslationToRef(this._workingVector);
  86433. return this._deviceRoomPosition.y + this._workingVector.y;
  86434. }
  86435. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86436. return this._defaultHeight || 0;
  86437. };
  86438. /**
  86439. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86440. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86441. */
  86442. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86443. var _this = this;
  86444. if (callback === void 0) { callback = function (bool) { }; }
  86445. // Use standing matrix if available
  86446. this.getEngine().initWebVRAsync().then(function (result) {
  86447. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86448. callback(false);
  86449. }
  86450. else {
  86451. _this._standingMatrix = new BABYLON.Matrix();
  86452. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86453. if (!_this.getScene().useRightHandedSystem) {
  86454. [2, 6, 8, 9, 14].forEach(function (num) {
  86455. if (_this._standingMatrix) {
  86456. _this._standingMatrix.m[num] *= -1;
  86457. }
  86458. });
  86459. }
  86460. callback(true);
  86461. }
  86462. });
  86463. };
  86464. /**
  86465. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86466. * @returns A promise with a boolean set to if the standing matrix is supported.
  86467. */
  86468. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86469. var _this = this;
  86470. return new Promise(function (res, rej) {
  86471. _this.useStandingMatrix(function (supported) {
  86472. res(supported);
  86473. });
  86474. });
  86475. };
  86476. /**
  86477. * Disposes the camera
  86478. */
  86479. WebVRFreeCamera.prototype.dispose = function () {
  86480. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86481. _super.prototype.dispose.call(this);
  86482. };
  86483. /**
  86484. * Gets a vrController by name.
  86485. * @param name The name of the controller to retreive
  86486. * @returns the controller matching the name specified or null if not found
  86487. */
  86488. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86489. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86490. var gp = _a[_i];
  86491. if (gp.hand === name) {
  86492. return gp;
  86493. }
  86494. }
  86495. return null;
  86496. };
  86497. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86498. /**
  86499. * The controller corrisponding to the users left hand.
  86500. */
  86501. get: function () {
  86502. if (!this._leftController) {
  86503. this._leftController = this.getControllerByName("left");
  86504. }
  86505. return this._leftController;
  86506. },
  86507. enumerable: true,
  86508. configurable: true
  86509. });
  86510. ;
  86511. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86512. /**
  86513. * The controller corrisponding to the users right hand.
  86514. */
  86515. get: function () {
  86516. if (!this._rightController) {
  86517. this._rightController = this.getControllerByName("right");
  86518. }
  86519. return this._rightController;
  86520. },
  86521. enumerable: true,
  86522. configurable: true
  86523. });
  86524. ;
  86525. /**
  86526. * Casts a ray forward from the vrCamera's gaze.
  86527. * @param length Length of the ray (default: 100)
  86528. * @returns the ray corrisponding to the gaze
  86529. */
  86530. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86531. if (length === void 0) { length = 100; }
  86532. if (this.leftCamera) {
  86533. // Use left eye to avoid computation to compute center on every call
  86534. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86535. }
  86536. else {
  86537. return _super.prototype.getForwardRay.call(this, length);
  86538. }
  86539. };
  86540. /**
  86541. * Updates the camera based on device's frame data
  86542. */
  86543. WebVRFreeCamera.prototype._checkInputs = function () {
  86544. if (this._vrDevice && this._vrDevice.isPresenting) {
  86545. this._vrDevice.getFrameData(this._frameData);
  86546. this.updateFromDevice(this._frameData.pose);
  86547. }
  86548. _super.prototype._checkInputs.call(this);
  86549. };
  86550. /**
  86551. * Updates the poseControlled values based on the input device pose.
  86552. * @param poseData Pose coming from the device
  86553. */
  86554. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86555. if (poseData && poseData.orientation) {
  86556. this.rawPose = poseData;
  86557. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86558. if (this.getScene().useRightHandedSystem) {
  86559. this._deviceRoomRotationQuaternion.z *= -1;
  86560. this._deviceRoomRotationQuaternion.w *= -1;
  86561. }
  86562. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86563. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86564. if (this.getScene().useRightHandedSystem) {
  86565. this._deviceRoomPosition.z *= -1;
  86566. }
  86567. }
  86568. }
  86569. };
  86570. /**
  86571. * WebVR's attach control will start broadcasting frames to the device.
  86572. * Note that in certain browsers (chrome for example) this function must be called
  86573. * within a user-interaction callback. Example:
  86574. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86575. *
  86576. * @param element html element to attach the vrDevice to
  86577. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86578. */
  86579. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86580. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86581. this._attached = true;
  86582. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86583. if (this._vrDevice) {
  86584. this.getEngine().enableVR();
  86585. }
  86586. };
  86587. /**
  86588. * Detaches the camera from the html element and disables VR
  86589. *
  86590. * @param element html element to detach from
  86591. */
  86592. WebVRFreeCamera.prototype.detachControl = function (element) {
  86593. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86594. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86595. _super.prototype.detachControl.call(this, element);
  86596. this._attached = false;
  86597. this.getEngine().disableVR();
  86598. };
  86599. /**
  86600. * @returns the name of this class
  86601. */
  86602. WebVRFreeCamera.prototype.getClassName = function () {
  86603. return "WebVRFreeCamera";
  86604. };
  86605. /**
  86606. * Calls resetPose on the vrDisplay
  86607. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86608. */
  86609. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86610. //uses the vrDisplay's "resetPose()".
  86611. //pitch and roll won't be affected.
  86612. this._vrDevice.resetPose();
  86613. };
  86614. /**
  86615. * Updates the rig cameras (left and right eye)
  86616. */
  86617. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86618. var camLeft = this._rigCameras[0];
  86619. var camRight = this._rigCameras[1];
  86620. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86621. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86622. camLeft.position.copyFrom(this._deviceRoomPosition);
  86623. camRight.position.copyFrom(this._deviceRoomPosition);
  86624. };
  86625. /**
  86626. * Updates the cached values of the camera
  86627. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86628. */
  86629. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86630. var _this = this;
  86631. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86632. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86633. if (!this.updateCacheCalled) {
  86634. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86635. this.updateCacheCalled = true;
  86636. this.update();
  86637. }
  86638. // Set working vector to the device position in room space rotated by the new rotation
  86639. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86640. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86641. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86642. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86643. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86644. // Add translation from anchor position
  86645. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86646. this._workingVector.addInPlace(this.position);
  86647. this._workingVector.subtractInPlace(this._cache.position);
  86648. this._deviceToWorld.setTranslation(this._workingVector);
  86649. // Set an inverted matrix to be used when updating the camera
  86650. this._deviceToWorld.invertToRef(this._worldToDevice);
  86651. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86652. this.controllers.forEach(function (controller) {
  86653. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86654. controller.update();
  86655. });
  86656. }
  86657. if (!ignoreParentClass) {
  86658. _super.prototype._updateCache.call(this);
  86659. }
  86660. this.updateCacheCalled = false;
  86661. };
  86662. /**
  86663. * Updates the current device position and rotation in the babylon world
  86664. */
  86665. WebVRFreeCamera.prototype.update = function () {
  86666. // Get current device position in babylon world
  86667. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86668. // Get current device rotation in babylon world
  86669. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86670. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86671. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86672. _super.prototype.update.call(this);
  86673. };
  86674. /**
  86675. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86676. * @returns an identity matrix
  86677. */
  86678. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86679. return BABYLON.Matrix.Identity();
  86680. };
  86681. /**
  86682. * This function is called by the two RIG cameras.
  86683. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86684. */
  86685. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86686. var _this = this;
  86687. // Update the parent camera prior to using a child camera to avoid desynchronization
  86688. var parentCamera = this._cameraRigParams["parentCamera"];
  86689. parentCamera._updateCache();
  86690. //WebVR 1.1
  86691. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86692. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86693. if (!this.getScene().useRightHandedSystem) {
  86694. [2, 6, 8, 9, 14].forEach(function (num) {
  86695. _this._webvrViewMatrix.m[num] *= -1;
  86696. });
  86697. }
  86698. // update the camera rotation matrix
  86699. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86700. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86701. // Computing target and final matrix
  86702. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86703. // should the view matrix be updated with scale and position offset?
  86704. if (parentCamera.deviceScaleFactor !== 1) {
  86705. this._webvrViewMatrix.invert();
  86706. // scale the position, if set
  86707. if (parentCamera.deviceScaleFactor) {
  86708. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86709. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86710. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86711. }
  86712. this._webvrViewMatrix.invert();
  86713. }
  86714. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86715. // Compute global position
  86716. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  86717. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  86718. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  86719. this._workingMatrix.getTranslationToRef(this._globalPosition);
  86720. this._markSyncedWithParent();
  86721. return this._webvrViewMatrix;
  86722. };
  86723. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86724. var _this = this;
  86725. var parentCamera = this.parent;
  86726. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86727. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86728. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86729. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86730. //babylon compatible matrix
  86731. if (!this.getScene().useRightHandedSystem) {
  86732. [8, 9, 10, 11].forEach(function (num) {
  86733. _this._projectionMatrix.m[num] *= -1;
  86734. });
  86735. }
  86736. return this._projectionMatrix;
  86737. };
  86738. /**
  86739. * Initializes the controllers and their meshes
  86740. */
  86741. WebVRFreeCamera.prototype.initControllers = function () {
  86742. var _this = this;
  86743. this.controllers = [];
  86744. var manager = this.getScene().gamepadManager;
  86745. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86746. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86747. var webVrController = gamepad;
  86748. if (webVrController.defaultModel) {
  86749. webVrController.defaultModel.setEnabled(false);
  86750. }
  86751. if (webVrController.hand === "right") {
  86752. _this._rightController = null;
  86753. }
  86754. if (webVrController.hand === "left") {
  86755. _this._leftController = null;
  86756. }
  86757. var controllerIndex = _this.controllers.indexOf(webVrController);
  86758. if (controllerIndex !== -1) {
  86759. _this.controllers.splice(controllerIndex, 1);
  86760. }
  86761. }
  86762. });
  86763. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86764. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86765. var webVrController_1 = gamepad;
  86766. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86767. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86768. if (_this.webVROptions.controllerMeshes) {
  86769. if (webVrController_1.defaultModel) {
  86770. webVrController_1.defaultModel.setEnabled(true);
  86771. }
  86772. else {
  86773. // Load the meshes
  86774. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86775. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86776. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86777. if (_this.webVROptions.defaultLightingOnControllers) {
  86778. if (!_this._lightOnControllers) {
  86779. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86780. }
  86781. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86782. var children = mesh.getChildren();
  86783. if (children.length !== 0) {
  86784. children.forEach(function (mesh) {
  86785. light.includedOnlyMeshes.push(mesh);
  86786. activateLightOnSubMeshes_1(mesh, light);
  86787. });
  86788. }
  86789. };
  86790. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86791. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86792. }
  86793. });
  86794. }
  86795. }
  86796. webVrController_1.attachToPoseControlledCamera(_this);
  86797. // since this is async - sanity check. Is the controller already stored?
  86798. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86799. //add to the controllers array
  86800. _this.controllers.push(webVrController_1);
  86801. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86802. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86803. // So we're overriding setting left & right manually to be sure
  86804. var firstViveWandDetected = false;
  86805. for (var i = 0; i < _this.controllers.length; i++) {
  86806. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86807. if (!firstViveWandDetected) {
  86808. firstViveWandDetected = true;
  86809. _this.controllers[i].hand = "left";
  86810. }
  86811. else {
  86812. _this.controllers[i].hand = "right";
  86813. }
  86814. }
  86815. }
  86816. //did we find enough controllers? Great! let the developer know.
  86817. if (_this.controllers.length >= 2) {
  86818. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86819. }
  86820. }
  86821. }
  86822. });
  86823. };
  86824. return WebVRFreeCamera;
  86825. }(BABYLON.FreeCamera));
  86826. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86827. })(BABYLON || (BABYLON = {}));
  86828. //# sourceMappingURL=babylon.webVRCamera.js.map
  86829. var BABYLON;
  86830. (function (BABYLON) {
  86831. // We're mainly based on the logic defined into the FreeCamera code
  86832. /**
  86833. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86834. * being tilted forward or back and left or right.
  86835. */
  86836. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86837. __extends(DeviceOrientationCamera, _super);
  86838. /**
  86839. * Creates a new device orientation camera
  86840. * @param name The name of the camera
  86841. * @param position The start position camera
  86842. * @param scene The scene the camera belongs to
  86843. */
  86844. function DeviceOrientationCamera(name, position, scene) {
  86845. var _this = _super.call(this, name, position, scene) || this;
  86846. _this._quaternionCache = new BABYLON.Quaternion();
  86847. _this.inputs.addDeviceOrientation();
  86848. return _this;
  86849. }
  86850. /**
  86851. * Gets the current instance class name ("DeviceOrientationCamera").
  86852. * This helps avoiding instanceof at run time.
  86853. * @returns the class name
  86854. */
  86855. DeviceOrientationCamera.prototype.getClassName = function () {
  86856. return "DeviceOrientationCamera";
  86857. };
  86858. /**
  86859. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86860. */
  86861. DeviceOrientationCamera.prototype._checkInputs = function () {
  86862. _super.prototype._checkInputs.call(this);
  86863. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86864. if (this._initialQuaternion) {
  86865. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86866. }
  86867. };
  86868. /**
  86869. * Reset the camera to its default orientation on the specified axis only.
  86870. * @param axis The axis to reset
  86871. */
  86872. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  86873. var _this = this;
  86874. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  86875. //can only work if this camera has a rotation quaternion already.
  86876. if (!this.rotationQuaternion)
  86877. return;
  86878. if (!this._initialQuaternion) {
  86879. this._initialQuaternion = new BABYLON.Quaternion();
  86880. }
  86881. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  86882. ['x', 'y', 'z'].forEach(function (axisName) {
  86883. if (!axis[axisName]) {
  86884. _this._initialQuaternion[axisName] = 0;
  86885. }
  86886. else {
  86887. _this._initialQuaternion[axisName] *= -1;
  86888. }
  86889. });
  86890. this._initialQuaternion.normalize();
  86891. //force rotation update
  86892. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86893. };
  86894. return DeviceOrientationCamera;
  86895. }(BABYLON.FreeCamera));
  86896. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  86897. })(BABYLON || (BABYLON = {}));
  86898. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  86899. var BABYLON;
  86900. (function (BABYLON) {
  86901. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  86902. __extends(VRDeviceOrientationFreeCamera, _super);
  86903. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86904. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86905. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86906. var _this = _super.call(this, name, position, scene) || this;
  86907. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86908. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86909. return _this;
  86910. }
  86911. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  86912. return "VRDeviceOrientationFreeCamera";
  86913. };
  86914. return VRDeviceOrientationFreeCamera;
  86915. }(BABYLON.DeviceOrientationCamera));
  86916. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  86917. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  86918. __extends(VRDeviceOrientationGamepadCamera, _super);
  86919. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86920. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86921. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86922. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  86923. _this.inputs.addGamepad();
  86924. return _this;
  86925. }
  86926. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  86927. return "VRDeviceOrientationGamepadCamera";
  86928. };
  86929. return VRDeviceOrientationGamepadCamera;
  86930. }(VRDeviceOrientationFreeCamera));
  86931. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  86932. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  86933. __extends(VRDeviceOrientationArcRotateCamera, _super);
  86934. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  86935. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86936. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86937. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86938. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86939. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86940. _this.inputs.addVRDeviceOrientation();
  86941. return _this;
  86942. }
  86943. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  86944. return "VRDeviceOrientationArcRotateCamera";
  86945. };
  86946. return VRDeviceOrientationArcRotateCamera;
  86947. }(BABYLON.ArcRotateCamera));
  86948. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  86949. })(BABYLON || (BABYLON = {}));
  86950. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  86951. var BABYLON;
  86952. (function (BABYLON) {
  86953. /**
  86954. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  86955. */
  86956. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  86957. __extends(AnaglyphFreeCamera, _super);
  86958. /**
  86959. * Creates a new AnaglyphFreeCamera
  86960. * @param name defines camera name
  86961. * @param position defines initial position
  86962. * @param interaxialDistance defines distance between each color axis
  86963. * @param scene defines the hosting scene
  86964. */
  86965. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  86966. var _this = _super.call(this, name, position, scene) || this;
  86967. _this.interaxialDistance = interaxialDistance;
  86968. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86969. return _this;
  86970. }
  86971. /**
  86972. * Gets camera class name
  86973. * @returns AnaglyphFreeCamera
  86974. */
  86975. AnaglyphFreeCamera.prototype.getClassName = function () {
  86976. return "AnaglyphFreeCamera";
  86977. };
  86978. return AnaglyphFreeCamera;
  86979. }(BABYLON.FreeCamera));
  86980. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  86981. /**
  86982. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  86983. */
  86984. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  86985. __extends(AnaglyphArcRotateCamera, _super);
  86986. /**
  86987. * Creates a new AnaglyphArcRotateCamera
  86988. * @param name defines camera name
  86989. * @param alpha defines alpha angle (in radians)
  86990. * @param beta defines beta angle (in radians)
  86991. * @param radius defines radius
  86992. * @param target defines camera target
  86993. * @param interaxialDistance defines distance between each color axis
  86994. * @param scene defines the hosting scene
  86995. */
  86996. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  86997. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86998. _this.interaxialDistance = interaxialDistance;
  86999. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87000. return _this;
  87001. }
  87002. /**
  87003. * Gets camera class name
  87004. * @returns AnaglyphArcRotateCamera
  87005. */
  87006. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87007. return "AnaglyphArcRotateCamera";
  87008. };
  87009. return AnaglyphArcRotateCamera;
  87010. }(BABYLON.ArcRotateCamera));
  87011. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87012. /**
  87013. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87014. */
  87015. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87016. __extends(AnaglyphGamepadCamera, _super);
  87017. /**
  87018. * Creates a new AnaglyphGamepadCamera
  87019. * @param name defines camera name
  87020. * @param position defines initial position
  87021. * @param interaxialDistance defines distance between each color axis
  87022. * @param scene defines the hosting scene
  87023. */
  87024. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87025. var _this = _super.call(this, name, position, scene) || this;
  87026. _this.interaxialDistance = interaxialDistance;
  87027. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87028. return _this;
  87029. }
  87030. /**
  87031. * Gets camera class name
  87032. * @returns AnaglyphGamepadCamera
  87033. */
  87034. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87035. return "AnaglyphGamepadCamera";
  87036. };
  87037. return AnaglyphGamepadCamera;
  87038. }(BABYLON.GamepadCamera));
  87039. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87040. /**
  87041. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87042. */
  87043. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87044. __extends(AnaglyphUniversalCamera, _super);
  87045. /**
  87046. * Creates a new AnaglyphUniversalCamera
  87047. * @param name defines camera name
  87048. * @param position defines initial position
  87049. * @param interaxialDistance defines distance between each color axis
  87050. * @param scene defines the hosting scene
  87051. */
  87052. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87053. var _this = _super.call(this, name, position, scene) || this;
  87054. _this.interaxialDistance = interaxialDistance;
  87055. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87056. return _this;
  87057. }
  87058. /**
  87059. * Gets camera class name
  87060. * @returns AnaglyphUniversalCamera
  87061. */
  87062. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87063. return "AnaglyphUniversalCamera";
  87064. };
  87065. return AnaglyphUniversalCamera;
  87066. }(BABYLON.UniversalCamera));
  87067. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87068. /**
  87069. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87070. */
  87071. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87072. __extends(StereoscopicFreeCamera, _super);
  87073. /**
  87074. * Creates a new StereoscopicFreeCamera
  87075. * @param name defines camera name
  87076. * @param position defines initial position
  87077. * @param interaxialDistance defines distance between each color axis
  87078. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87079. * @param scene defines the hosting scene
  87080. */
  87081. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87082. var _this = _super.call(this, name, position, scene) || this;
  87083. _this.interaxialDistance = interaxialDistance;
  87084. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87085. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87086. return _this;
  87087. }
  87088. /**
  87089. * Gets camera class name
  87090. * @returns StereoscopicFreeCamera
  87091. */
  87092. StereoscopicFreeCamera.prototype.getClassName = function () {
  87093. return "StereoscopicFreeCamera";
  87094. };
  87095. return StereoscopicFreeCamera;
  87096. }(BABYLON.FreeCamera));
  87097. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87098. /**
  87099. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87100. */
  87101. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87102. __extends(StereoscopicArcRotateCamera, _super);
  87103. /**
  87104. * Creates a new StereoscopicArcRotateCamera
  87105. * @param name defines camera name
  87106. * @param alpha defines alpha angle (in radians)
  87107. * @param beta defines beta angle (in radians)
  87108. * @param radius defines radius
  87109. * @param target defines camera target
  87110. * @param interaxialDistance defines distance between each color axis
  87111. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87112. * @param scene defines the hosting scene
  87113. */
  87114. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87115. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87116. _this.interaxialDistance = interaxialDistance;
  87117. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87118. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87119. return _this;
  87120. }
  87121. /**
  87122. * Gets camera class name
  87123. * @returns StereoscopicArcRotateCamera
  87124. */
  87125. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87126. return "StereoscopicArcRotateCamera";
  87127. };
  87128. return StereoscopicArcRotateCamera;
  87129. }(BABYLON.ArcRotateCamera));
  87130. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87131. /**
  87132. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87133. */
  87134. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87135. __extends(StereoscopicGamepadCamera, _super);
  87136. /**
  87137. * Creates a new StereoscopicGamepadCamera
  87138. * @param name defines camera name
  87139. * @param position defines initial position
  87140. * @param interaxialDistance defines distance between each color axis
  87141. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87142. * @param scene defines the hosting scene
  87143. */
  87144. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87145. var _this = _super.call(this, name, position, scene) || this;
  87146. _this.interaxialDistance = interaxialDistance;
  87147. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87148. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87149. return _this;
  87150. }
  87151. /**
  87152. * Gets camera class name
  87153. * @returns StereoscopicGamepadCamera
  87154. */
  87155. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87156. return "StereoscopicGamepadCamera";
  87157. };
  87158. return StereoscopicGamepadCamera;
  87159. }(BABYLON.GamepadCamera));
  87160. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87161. /**
  87162. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87163. */
  87164. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87165. __extends(StereoscopicUniversalCamera, _super);
  87166. /**
  87167. * Creates a new StereoscopicUniversalCamera
  87168. * @param name defines camera name
  87169. * @param position defines initial position
  87170. * @param interaxialDistance defines distance between each color axis
  87171. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87172. * @param scene defines the hosting scene
  87173. */
  87174. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87175. var _this = _super.call(this, name, position, scene) || this;
  87176. _this.interaxialDistance = interaxialDistance;
  87177. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87178. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87179. return _this;
  87180. }
  87181. /**
  87182. * Gets camera class name
  87183. * @returns StereoscopicUniversalCamera
  87184. */
  87185. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87186. return "StereoscopicUniversalCamera";
  87187. };
  87188. return StereoscopicUniversalCamera;
  87189. }(BABYLON.UniversalCamera));
  87190. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87191. })(BABYLON || (BABYLON = {}));
  87192. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87193. var BABYLON;
  87194. (function (BABYLON) {
  87195. var VRExperienceHelperGazer = /** @class */ (function () {
  87196. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87197. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87198. this.scene = scene;
  87199. this._pointerDownOnMeshAsked = false;
  87200. this._isActionableMesh = false;
  87201. this._teleportationRequestInitiated = false;
  87202. this._teleportationBackRequestInitiated = false;
  87203. this._dpadPressed = true;
  87204. this._activePointer = false;
  87205. this._id = VRExperienceHelperGazer._idCounter++;
  87206. // Gaze tracker
  87207. if (!gazeTrackerToClone) {
  87208. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87209. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87210. this._gazeTracker.isPickable = false;
  87211. this._gazeTracker.isVisible = false;
  87212. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87213. targetMat.specularColor = BABYLON.Color3.Black();
  87214. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87215. targetMat.backFaceCulling = false;
  87216. this._gazeTracker.material = targetMat;
  87217. }
  87218. else {
  87219. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87220. }
  87221. }
  87222. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87223. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87224. };
  87225. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87226. this._pointerDownOnMeshAsked = true;
  87227. if (this._currentMeshSelected && this._currentHit) {
  87228. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87229. }
  87230. };
  87231. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87232. if (this._currentMeshSelected && this._currentHit) {
  87233. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87234. }
  87235. this._pointerDownOnMeshAsked = false;
  87236. };
  87237. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87238. this._activePointer = true;
  87239. };
  87240. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87241. this._activePointer = false;
  87242. };
  87243. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87244. };
  87245. VRExperienceHelperGazer.prototype.dispose = function () {
  87246. this._interactionsEnabled = false;
  87247. this._teleportationEnabled = false;
  87248. };
  87249. VRExperienceHelperGazer._idCounter = 0;
  87250. return VRExperienceHelperGazer;
  87251. }());
  87252. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87253. __extends(VRExperienceHelperControllerGazer, _super);
  87254. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87255. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87256. _this.webVRController = webVRController;
  87257. // Laser pointer
  87258. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87259. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87260. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87261. laserPointerMaterial.alpha = 0.6;
  87262. _this._laserPointer.material = laserPointerMaterial;
  87263. _this._laserPointer.rotation.x = Math.PI / 2;
  87264. _this._laserPointer.position.z = -0.5;
  87265. _this._laserPointer.isVisible = false;
  87266. if (!webVRController.mesh) {
  87267. // Create an empty mesh that is used prior to loading the high quality model
  87268. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87269. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87270. preloadPointerPose.rotation.x = -0.7;
  87271. preloadMesh.addChild(preloadPointerPose);
  87272. webVRController.attachToMesh(preloadMesh);
  87273. }
  87274. _this._setLaserPointerParent(webVRController.mesh);
  87275. return _this;
  87276. }
  87277. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87278. return this.webVRController.getForwardRay(length);
  87279. };
  87280. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87281. _super.prototype._activatePointer.call(this);
  87282. this._laserPointer.isVisible = true;
  87283. };
  87284. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87285. _super.prototype._deactivatePointer.call(this);
  87286. this._laserPointer.isVisible = false;
  87287. };
  87288. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87289. this._laserPointer.material.emissiveColor = color;
  87290. };
  87291. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87292. var makeNotPick = function (root) {
  87293. root.name += " laserPointer";
  87294. root.getChildMeshes().forEach(function (c) {
  87295. makeNotPick(c);
  87296. });
  87297. };
  87298. makeNotPick(mesh);
  87299. var childMeshes = mesh.getChildMeshes();
  87300. this.webVRController._pointingPoseNode = null;
  87301. for (var i = 0; i < childMeshes.length; i++) {
  87302. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87303. mesh = childMeshes[i];
  87304. this.webVRController._pointingPoseNode = mesh;
  87305. break;
  87306. }
  87307. }
  87308. this._laserPointer.parent = mesh;
  87309. };
  87310. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87311. this._laserPointer.scaling.y = distance;
  87312. this._laserPointer.position.z = -distance / 2;
  87313. };
  87314. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87315. _super.prototype.dispose.call(this);
  87316. this._laserPointer.dispose();
  87317. };
  87318. return VRExperienceHelperControllerGazer;
  87319. }(VRExperienceHelperGazer));
  87320. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87321. __extends(VRExperienceHelperCameraGazer, _super);
  87322. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87323. var _this = _super.call(this, scene) || this;
  87324. _this.getCamera = getCamera;
  87325. return _this;
  87326. }
  87327. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87328. var camera = this.getCamera();
  87329. if (camera) {
  87330. return camera.getForwardRay(length);
  87331. }
  87332. else {
  87333. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87334. }
  87335. };
  87336. return VRExperienceHelperCameraGazer;
  87337. }(VRExperienceHelperGazer));
  87338. /**
  87339. * Helps to quickly add VR support to an existing scene.
  87340. * See http://doc.babylonjs.com/how_to/webvr_helper
  87341. */
  87342. var VRExperienceHelper = /** @class */ (function () {
  87343. /**
  87344. * Instantiates a VRExperienceHelper.
  87345. * Helps to quickly add VR support to an existing scene.
  87346. * @param scene The scene the VRExperienceHelper belongs to.
  87347. * @param webVROptions Options to modify the vr experience helper's behavior.
  87348. */
  87349. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87350. if (webVROptions === void 0) { webVROptions = {}; }
  87351. var _this = this;
  87352. this.webVROptions = webVROptions;
  87353. // Can the system support WebVR, even if a headset isn't plugged in?
  87354. this._webVRsupported = false;
  87355. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87356. this._webVRready = false;
  87357. // Are we waiting for the requestPresent callback to complete?
  87358. this._webVRrequesting = false;
  87359. // Are we presenting to the headset right now?
  87360. this._webVRpresenting = false;
  87361. // Are we presenting in the fullscreen fallback?
  87362. this._fullscreenVRpresenting = false;
  87363. /**
  87364. * Observable raised when entering VR.
  87365. */
  87366. this.onEnteringVRObservable = new BABYLON.Observable();
  87367. /**
  87368. * Observable raised when exiting VR.
  87369. */
  87370. this.onExitingVRObservable = new BABYLON.Observable();
  87371. /**
  87372. * Observable raised when controller mesh is loaded.
  87373. */
  87374. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87375. this._useCustomVRButton = false;
  87376. this._teleportationRequested = false;
  87377. this._teleportActive = false;
  87378. this._floorMeshesCollection = [];
  87379. this._rotationAllowed = true;
  87380. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87381. this._rotationRightAsked = false;
  87382. this._rotationLeftAsked = false;
  87383. this._isDefaultTeleportationTarget = true;
  87384. this._teleportationFillColor = "#444444";
  87385. this._teleportationBorderColor = "#FFFFFF";
  87386. this._rotationAngle = 0;
  87387. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87388. this._padSensibilityUp = 0.65;
  87389. this._padSensibilityDown = 0.35;
  87390. this.leftController = null;
  87391. this.rightController = null;
  87392. /**
  87393. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87394. */
  87395. this.onNewMeshSelected = new BABYLON.Observable();
  87396. /**
  87397. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87398. */
  87399. this.onNewMeshPicked = new BABYLON.Observable();
  87400. /**
  87401. * Observable raised before camera teleportation
  87402. */
  87403. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87404. /**
  87405. * Observable raised after camera teleportation
  87406. */
  87407. this.onAfterCameraTeleport = new BABYLON.Observable();
  87408. /**
  87409. * Observable raised when current selected mesh gets unselected
  87410. */
  87411. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87412. /**
  87413. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87414. */
  87415. this.teleportationEnabled = true;
  87416. this._teleportationInitialized = false;
  87417. this._interactionsEnabled = false;
  87418. this._interactionsRequested = false;
  87419. this._displayGaze = true;
  87420. this._displayLaserPointer = true;
  87421. this._onResize = function () {
  87422. _this.moveButtonToBottomRight();
  87423. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87424. _this.exitVR();
  87425. }
  87426. };
  87427. this._onFullscreenChange = function () {
  87428. if (document.fullscreen !== undefined) {
  87429. _this._fullscreenVRpresenting = document.fullscreen;
  87430. }
  87431. else if (document.mozFullScreen !== undefined) {
  87432. _this._fullscreenVRpresenting = document.mozFullScreen;
  87433. }
  87434. else if (document.webkitIsFullScreen !== undefined) {
  87435. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87436. }
  87437. else if (document.msIsFullScreen !== undefined) {
  87438. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87439. }
  87440. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87441. _this.exitVR();
  87442. if (!_this._useCustomVRButton) {
  87443. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87444. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87445. }
  87446. }
  87447. };
  87448. this.beforeRender = function () {
  87449. if (_this.leftController && _this.leftController._activePointer) {
  87450. _this._castRayAndSelectObject(_this.leftController);
  87451. }
  87452. if (_this.rightController && _this.rightController._activePointer) {
  87453. _this._castRayAndSelectObject(_this.rightController);
  87454. }
  87455. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87456. _this._castRayAndSelectObject(_this._cameraGazer);
  87457. }
  87458. else {
  87459. _this._cameraGazer._gazeTracker.isVisible = false;
  87460. }
  87461. };
  87462. this._onNewGamepadConnected = function (gamepad) {
  87463. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87464. if (gamepad.leftStick) {
  87465. gamepad.onleftstickchanged(function (stickValues) {
  87466. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87467. // Listening to classic/xbox gamepad only if no VR controller is active
  87468. if ((!_this.leftController && !_this.rightController) ||
  87469. ((_this.leftController && !_this.leftController._activePointer) &&
  87470. (_this.rightController && !_this.rightController._activePointer))) {
  87471. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87472. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87473. }
  87474. }
  87475. });
  87476. }
  87477. if (gamepad.rightStick) {
  87478. gamepad.onrightstickchanged(function (stickValues) {
  87479. if (_this._teleportationInitialized) {
  87480. _this._checkRotate(stickValues, _this._cameraGazer);
  87481. }
  87482. });
  87483. }
  87484. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87485. gamepad.onbuttondown(function (buttonPressed) {
  87486. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87487. _this._cameraGazer._selectionPointerDown();
  87488. }
  87489. });
  87490. gamepad.onbuttonup(function (buttonPressed) {
  87491. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87492. _this._cameraGazer._selectionPointerUp();
  87493. }
  87494. });
  87495. }
  87496. }
  87497. else {
  87498. var webVRController = gamepad;
  87499. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87500. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87501. _this.rightController = controller;
  87502. }
  87503. else {
  87504. _this.leftController = controller;
  87505. }
  87506. _this._tryEnableInteractionOnController(controller);
  87507. }
  87508. };
  87509. // 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
  87510. this._tryEnableInteractionOnController = function (controller) {
  87511. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87512. _this._enableInteractionOnController(controller);
  87513. }
  87514. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87515. _this._enableTeleportationOnController(controller);
  87516. }
  87517. };
  87518. this._onNewGamepadDisconnected = function (gamepad) {
  87519. if (gamepad instanceof BABYLON.WebVRController) {
  87520. if (gamepad.hand === "left" && _this.leftController != null) {
  87521. _this.leftController.dispose();
  87522. _this.leftController = null;
  87523. }
  87524. if (gamepad.hand === "right" && _this.rightController != null) {
  87525. _this.rightController.dispose();
  87526. _this.rightController = null;
  87527. }
  87528. }
  87529. };
  87530. this._workingVector = BABYLON.Vector3.Zero();
  87531. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87532. this._workingMatrix = BABYLON.Matrix.Identity();
  87533. this._scene = scene;
  87534. this._canvas = scene.getEngine().getRenderingCanvas();
  87535. // Parse options
  87536. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87537. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87538. }
  87539. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87540. webVROptions.createDeviceOrientationCamera = true;
  87541. }
  87542. if (webVROptions.defaultHeight === undefined) {
  87543. webVROptions.defaultHeight = 1.7;
  87544. }
  87545. if (webVROptions.useCustomVRButton) {
  87546. this._useCustomVRButton = true;
  87547. if (webVROptions.customVRButton) {
  87548. this._btnVR = webVROptions.customVRButton;
  87549. }
  87550. }
  87551. if (webVROptions.rayLength) {
  87552. this._rayLength = webVROptions.rayLength;
  87553. }
  87554. this._defaultHeight = webVROptions.defaultHeight;
  87555. if (webVROptions.positionScale) {
  87556. this._rayLength *= webVROptions.positionScale;
  87557. this._defaultHeight *= webVROptions.positionScale;
  87558. }
  87559. // Set position
  87560. if (this._scene.activeCamera) {
  87561. this._position = this._scene.activeCamera.position.clone();
  87562. }
  87563. else {
  87564. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87565. }
  87566. // Set non-vr camera
  87567. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87568. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87569. // Copy data from existing camera
  87570. if (this._scene.activeCamera) {
  87571. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87572. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87573. // Set rotation from previous camera
  87574. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87575. var targetCamera = this._scene.activeCamera;
  87576. if (targetCamera.rotationQuaternion) {
  87577. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87578. }
  87579. else {
  87580. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87581. }
  87582. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87583. }
  87584. }
  87585. this._scene.activeCamera = this._deviceOrientationCamera;
  87586. if (this._canvas) {
  87587. this._scene.activeCamera.attachControl(this._canvas);
  87588. }
  87589. }
  87590. else {
  87591. this._existingCamera = this._scene.activeCamera;
  87592. }
  87593. // Create VR cameras
  87594. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87595. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87596. }
  87597. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87598. this._webVRCamera.useStandingMatrix();
  87599. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87600. // Create default button
  87601. if (!this._useCustomVRButton) {
  87602. this._btnVR = document.createElement("BUTTON");
  87603. this._btnVR.className = "babylonVRicon";
  87604. this._btnVR.id = "babylonVRiconbtn";
  87605. this._btnVR.title = "Click to switch to VR";
  87606. 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) }";
  87607. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87608. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87609. // css += ".babylonVRicon.vrdisplaysupported { }";
  87610. // css += ".babylonVRicon.vrdisplayready { }";
  87611. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87612. var style = document.createElement('style');
  87613. style.appendChild(document.createTextNode(css));
  87614. document.getElementsByTagName('head')[0].appendChild(style);
  87615. this.moveButtonToBottomRight();
  87616. }
  87617. // VR button click event
  87618. if (this._btnVR) {
  87619. this._btnVR.addEventListener("click", function () {
  87620. if (!_this.isInVRMode) {
  87621. _this.enterVR();
  87622. }
  87623. else {
  87624. _this.exitVR();
  87625. }
  87626. });
  87627. }
  87628. // Window events
  87629. window.addEventListener("resize", this._onResize);
  87630. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87631. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87632. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87633. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87634. // Display vr button when headset is connected
  87635. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87636. this.displayVRButton();
  87637. }
  87638. else {
  87639. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87640. if (e.vrDisplay) {
  87641. _this.displayVRButton();
  87642. }
  87643. });
  87644. }
  87645. // Exiting VR mode using 'ESC' key on desktop
  87646. this._onKeyDown = function (event) {
  87647. if (event.keyCode === 27 && _this.isInVRMode) {
  87648. _this.exitVR();
  87649. }
  87650. };
  87651. document.addEventListener("keydown", this._onKeyDown);
  87652. // Exiting VR mode double tapping the touch screen
  87653. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87654. if (_this.isInVRMode) {
  87655. _this.exitVR();
  87656. if (_this._fullscreenVRpresenting) {
  87657. _this._scene.getEngine().switchFullscreen(true);
  87658. }
  87659. }
  87660. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87661. // Listen for WebVR display changes
  87662. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87663. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87664. this._onVRRequestPresentStart = function () {
  87665. _this._webVRrequesting = true;
  87666. _this.updateButtonVisibility();
  87667. };
  87668. this._onVRRequestPresentComplete = function (success) {
  87669. _this._webVRrequesting = false;
  87670. _this.updateButtonVisibility();
  87671. };
  87672. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87673. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87674. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87675. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87676. scene.onDisposeObservable.add(function () {
  87677. _this.dispose();
  87678. });
  87679. // Gamepad connection events
  87680. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87681. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87682. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87683. this.updateButtonVisibility();
  87684. //create easing functions
  87685. this._circleEase = new BABYLON.CircleEase();
  87686. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87687. }
  87688. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87689. /** Return this.onEnteringVRObservable
  87690. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87691. */
  87692. get: function () {
  87693. return this.onEnteringVRObservable;
  87694. },
  87695. enumerable: true,
  87696. configurable: true
  87697. });
  87698. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87699. /** Return this.onExitingVRObservable
  87700. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87701. */
  87702. get: function () {
  87703. return this.onExitingVRObservable;
  87704. },
  87705. enumerable: true,
  87706. configurable: true
  87707. });
  87708. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87709. /** Return this.onControllerMeshLoadedObservable
  87710. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87711. */
  87712. get: function () {
  87713. return this.onControllerMeshLoadedObservable;
  87714. },
  87715. enumerable: true,
  87716. configurable: true
  87717. });
  87718. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87719. /**
  87720. * The mesh used to display where the user is going to teleport.
  87721. */
  87722. get: function () {
  87723. return this._teleportationTarget;
  87724. },
  87725. /**
  87726. * Sets the mesh to be used to display where the user is going to teleport.
  87727. */
  87728. set: function (value) {
  87729. if (value) {
  87730. value.name = "teleportationTarget";
  87731. this._isDefaultTeleportationTarget = false;
  87732. this._teleportationTarget = value;
  87733. }
  87734. },
  87735. enumerable: true,
  87736. configurable: true
  87737. });
  87738. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87739. /**
  87740. * The mesh used to display where the user is selecting,
  87741. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87742. * See http://doc.babylonjs.com/resources/baking_transformations
  87743. */
  87744. get: function () {
  87745. return this._cameraGazer._gazeTracker;
  87746. },
  87747. set: function (value) {
  87748. if (value) {
  87749. this._cameraGazer._gazeTracker = value;
  87750. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87751. this._cameraGazer._gazeTracker.isPickable = false;
  87752. this._cameraGazer._gazeTracker.isVisible = false;
  87753. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87754. if (this.leftController) {
  87755. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87756. }
  87757. if (this.rightController) {
  87758. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87759. }
  87760. }
  87761. },
  87762. enumerable: true,
  87763. configurable: true
  87764. });
  87765. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87766. /**
  87767. * If the ray of the gaze should be displayed.
  87768. */
  87769. get: function () {
  87770. return this._displayGaze;
  87771. },
  87772. /**
  87773. * Sets if the ray of the gaze should be displayed.
  87774. */
  87775. set: function (value) {
  87776. this._displayGaze = value;
  87777. if (!value) {
  87778. this._cameraGazer._gazeTracker.isVisible = false;
  87779. if (this.leftController) {
  87780. this.leftController._gazeTracker.isVisible = false;
  87781. }
  87782. if (this.rightController) {
  87783. this.rightController._gazeTracker.isVisible = false;
  87784. }
  87785. }
  87786. },
  87787. enumerable: true,
  87788. configurable: true
  87789. });
  87790. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87791. /**
  87792. * If the ray of the LaserPointer should be displayed.
  87793. */
  87794. get: function () {
  87795. return this._displayLaserPointer;
  87796. },
  87797. /**
  87798. * Sets if the ray of the LaserPointer should be displayed.
  87799. */
  87800. set: function (value) {
  87801. this._displayLaserPointer = value;
  87802. if (!value) {
  87803. if (this.rightController) {
  87804. this.rightController._deactivatePointer();
  87805. this.rightController._gazeTracker.isVisible = false;
  87806. }
  87807. if (this.leftController) {
  87808. this.leftController._deactivatePointer();
  87809. this.leftController._gazeTracker.isVisible = false;
  87810. }
  87811. }
  87812. else {
  87813. if (this.rightController) {
  87814. this.rightController._activatePointer();
  87815. }
  87816. else if (this.leftController) {
  87817. this.leftController._activatePointer();
  87818. }
  87819. }
  87820. },
  87821. enumerable: true,
  87822. configurable: true
  87823. });
  87824. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87825. /**
  87826. * The deviceOrientationCamera used as the camera when not in VR.
  87827. */
  87828. get: function () {
  87829. return this._deviceOrientationCamera;
  87830. },
  87831. enumerable: true,
  87832. configurable: true
  87833. });
  87834. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87835. /**
  87836. * Based on the current WebVR support, returns the current VR camera used.
  87837. */
  87838. get: function () {
  87839. if (this._webVRready) {
  87840. return this._webVRCamera;
  87841. }
  87842. else {
  87843. return this._scene.activeCamera;
  87844. }
  87845. },
  87846. enumerable: true,
  87847. configurable: true
  87848. });
  87849. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87850. /**
  87851. * The webVRCamera which is used when in VR.
  87852. */
  87853. get: function () {
  87854. return this._webVRCamera;
  87855. },
  87856. enumerable: true,
  87857. configurable: true
  87858. });
  87859. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  87860. /**
  87861. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  87862. */
  87863. get: function () {
  87864. return this._vrDeviceOrientationCamera;
  87865. },
  87866. enumerable: true,
  87867. configurable: true
  87868. });
  87869. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  87870. get: function () {
  87871. var result = this._cameraGazer._teleportationRequestInitiated
  87872. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  87873. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  87874. return result;
  87875. },
  87876. enumerable: true,
  87877. configurable: true
  87878. });
  87879. // Raised when one of the controller has loaded successfully its associated default mesh
  87880. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  87881. if (this.leftController && this.leftController.webVRController == webVRController) {
  87882. if (webVRController.mesh) {
  87883. this.leftController._setLaserPointerParent(webVRController.mesh);
  87884. }
  87885. }
  87886. if (this.rightController && this.rightController.webVRController == webVRController) {
  87887. if (webVRController.mesh) {
  87888. this.rightController._setLaserPointerParent(webVRController.mesh);
  87889. }
  87890. }
  87891. try {
  87892. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  87893. }
  87894. catch (err) {
  87895. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  87896. }
  87897. };
  87898. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  87899. /**
  87900. * Gets a value indicating if we are currently in VR mode.
  87901. */
  87902. get: function () {
  87903. return this._webVRpresenting || this._fullscreenVRpresenting;
  87904. },
  87905. enumerable: true,
  87906. configurable: true
  87907. });
  87908. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  87909. var vrDisplay = this._scene.getEngine().getVRDevice();
  87910. if (vrDisplay) {
  87911. var wasPresenting = this._webVRpresenting;
  87912. // A VR display is connected
  87913. this._webVRpresenting = vrDisplay.isPresenting;
  87914. if (wasPresenting && !this._webVRpresenting)
  87915. this.exitVR();
  87916. }
  87917. else {
  87918. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  87919. }
  87920. this.updateButtonVisibility();
  87921. };
  87922. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  87923. this._webVRsupported = eventArgs.vrSupported;
  87924. this._webVRready = !!eventArgs.vrDisplay;
  87925. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  87926. this.updateButtonVisibility();
  87927. };
  87928. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  87929. if (this._canvas && !this._useCustomVRButton) {
  87930. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  87931. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  87932. }
  87933. };
  87934. VRExperienceHelper.prototype.displayVRButton = function () {
  87935. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  87936. document.body.appendChild(this._btnVR);
  87937. this._btnVRDisplayed = true;
  87938. }
  87939. };
  87940. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  87941. if (!this._btnVR || this._useCustomVRButton) {
  87942. return;
  87943. }
  87944. this._btnVR.className = "babylonVRicon";
  87945. if (this.isInVRMode) {
  87946. this._btnVR.className += " vrdisplaypresenting";
  87947. }
  87948. else {
  87949. if (this._webVRready)
  87950. this._btnVR.className += " vrdisplayready";
  87951. if (this._webVRsupported)
  87952. this._btnVR.className += " vrdisplaysupported";
  87953. if (this._webVRrequesting)
  87954. this._btnVR.className += " vrdisplayrequesting";
  87955. }
  87956. };
  87957. /**
  87958. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  87959. * Otherwise, will use the fullscreen API.
  87960. */
  87961. VRExperienceHelper.prototype.enterVR = function () {
  87962. if (this.onEnteringVRObservable) {
  87963. try {
  87964. this.onEnteringVRObservable.notifyObservers(this);
  87965. }
  87966. catch (err) {
  87967. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  87968. }
  87969. }
  87970. if (this._scene.activeCamera) {
  87971. this._position = this._scene.activeCamera.position.clone();
  87972. // make sure that we return to the last active camera
  87973. this._existingCamera = this._scene.activeCamera;
  87974. }
  87975. if (this._webVRrequesting)
  87976. return;
  87977. // If WebVR is supported and a headset is connected
  87978. if (this._webVRready) {
  87979. if (!this._webVRpresenting) {
  87980. this._webVRCamera.position = this._position;
  87981. this._scene.activeCamera = this._webVRCamera;
  87982. }
  87983. }
  87984. else if (this._vrDeviceOrientationCamera) {
  87985. this._vrDeviceOrientationCamera.position = this._position;
  87986. if (this._scene.activeCamera) {
  87987. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87988. }
  87989. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  87990. this._scene.getEngine().switchFullscreen(true);
  87991. this.updateButtonVisibility();
  87992. }
  87993. if (this._scene.activeCamera && this._canvas) {
  87994. this._scene.activeCamera.attachControl(this._canvas);
  87995. }
  87996. if (this._interactionsEnabled) {
  87997. this._scene.registerBeforeRender(this.beforeRender);
  87998. }
  87999. };
  88000. /**
  88001. * Attempt to exit VR, or fullscreen.
  88002. */
  88003. VRExperienceHelper.prototype.exitVR = function () {
  88004. if (this.onExitingVRObservable) {
  88005. try {
  88006. this.onExitingVRObservable.notifyObservers(this);
  88007. }
  88008. catch (err) {
  88009. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88010. }
  88011. }
  88012. if (this._webVRpresenting) {
  88013. this._scene.getEngine().disableVR();
  88014. }
  88015. if (this._scene.activeCamera) {
  88016. this._position = this._scene.activeCamera.position.clone();
  88017. }
  88018. if (this._deviceOrientationCamera) {
  88019. this._deviceOrientationCamera.position = this._position;
  88020. this._scene.activeCamera = this._deviceOrientationCamera;
  88021. if (this._canvas) {
  88022. this._scene.activeCamera.attachControl(this._canvas);
  88023. }
  88024. }
  88025. else if (this._existingCamera) {
  88026. this._existingCamera.position = this._position;
  88027. this._scene.activeCamera = this._existingCamera;
  88028. }
  88029. this.updateButtonVisibility();
  88030. if (this._interactionsEnabled) {
  88031. this._scene.unregisterBeforeRender(this.beforeRender);
  88032. }
  88033. // resize to update width and height when exiting vr exits fullscreen
  88034. this._scene.getEngine().resize();
  88035. };
  88036. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88037. /**
  88038. * The position of the vr experience helper.
  88039. */
  88040. get: function () {
  88041. return this._position;
  88042. },
  88043. /**
  88044. * Sets the position of the vr experience helper.
  88045. */
  88046. set: function (value) {
  88047. this._position = value;
  88048. if (this._scene.activeCamera) {
  88049. this._scene.activeCamera.position = value;
  88050. }
  88051. },
  88052. enumerable: true,
  88053. configurable: true
  88054. });
  88055. /**
  88056. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88057. */
  88058. VRExperienceHelper.prototype.enableInteractions = function () {
  88059. var _this = this;
  88060. if (!this._interactionsEnabled) {
  88061. this._interactionsRequested = true;
  88062. if (this.leftController) {
  88063. this._enableInteractionOnController(this.leftController);
  88064. }
  88065. if (this.rightController) {
  88066. this._enableInteractionOnController(this.rightController);
  88067. }
  88068. this.raySelectionPredicate = function (mesh) {
  88069. return mesh.isVisible;
  88070. };
  88071. this.meshSelectionPredicate = function (mesh) {
  88072. return true;
  88073. };
  88074. this._raySelectionPredicate = function (mesh) {
  88075. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88076. && mesh.name.indexOf("teleportationTarget") === -1
  88077. && mesh.name.indexOf("torusTeleportation") === -1
  88078. && mesh.name.indexOf("laserPointer") === -1)) {
  88079. return _this.raySelectionPredicate(mesh);
  88080. }
  88081. return false;
  88082. };
  88083. this._interactionsEnabled = true;
  88084. }
  88085. };
  88086. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88087. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88088. if (this._floorMeshesCollection[i].id === mesh.id) {
  88089. return true;
  88090. }
  88091. }
  88092. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88093. return true;
  88094. }
  88095. return false;
  88096. };
  88097. /**
  88098. * Adds a floor mesh to be used for teleportation.
  88099. * @param floorMesh the mesh to be used for teleportation.
  88100. */
  88101. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88102. if (!this._floorMeshesCollection) {
  88103. return;
  88104. }
  88105. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88106. return;
  88107. }
  88108. this._floorMeshesCollection.push(floorMesh);
  88109. };
  88110. /**
  88111. * Removes a floor mesh from being used for teleportation.
  88112. * @param floorMesh the mesh to be removed.
  88113. */
  88114. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88115. if (!this._floorMeshesCollection) {
  88116. return;
  88117. }
  88118. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88119. if (meshIndex !== -1) {
  88120. this._floorMeshesCollection.splice(meshIndex, 1);
  88121. }
  88122. };
  88123. /**
  88124. * Enables interactions and teleportation using the VR controllers and gaze.
  88125. * @param vrTeleportationOptions options to modify teleportation behavior.
  88126. */
  88127. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88128. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88129. if (!this._teleportationInitialized) {
  88130. this._teleportationRequested = true;
  88131. this.enableInteractions();
  88132. if (vrTeleportationOptions.floorMeshName) {
  88133. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88134. }
  88135. if (vrTeleportationOptions.floorMeshes) {
  88136. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88137. }
  88138. if (this.leftController != null) {
  88139. this._enableTeleportationOnController(this.leftController);
  88140. }
  88141. if (this.rightController != null) {
  88142. this._enableTeleportationOnController(this.rightController);
  88143. }
  88144. // Creates an image processing post process for the vignette not relying
  88145. // on the main scene configuration for image processing to reduce setup and spaces
  88146. // (gamma/linear) conflicts.
  88147. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88148. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88149. imageProcessingConfiguration.vignetteEnabled = true;
  88150. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88151. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88152. this._teleportationInitialized = true;
  88153. if (this._isDefaultTeleportationTarget) {
  88154. this._createTeleportationCircles();
  88155. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88156. }
  88157. }
  88158. };
  88159. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88160. var _this = this;
  88161. var controllerMesh = controller.webVRController.mesh;
  88162. if (controllerMesh) {
  88163. controller._interactionsEnabled = true;
  88164. controller._activatePointer();
  88165. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88166. // Enabling / disabling laserPointer
  88167. if (_this._displayLaserPointer && stateObject.value === 1) {
  88168. if (controller._activePointer) {
  88169. controller._deactivatePointer();
  88170. }
  88171. else {
  88172. controller._activatePointer();
  88173. }
  88174. if (_this.displayGaze) {
  88175. controller._gazeTracker.isVisible = controller._activePointer;
  88176. }
  88177. }
  88178. });
  88179. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88180. if (!controller._pointerDownOnMeshAsked) {
  88181. if (stateObject.value > _this._padSensibilityUp) {
  88182. controller._selectionPointerDown();
  88183. }
  88184. }
  88185. else if (stateObject.value < _this._padSensibilityDown) {
  88186. controller._selectionPointerUp();
  88187. }
  88188. });
  88189. }
  88190. };
  88191. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88192. // Dont teleport if another gaze already requested teleportation
  88193. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88194. return;
  88195. }
  88196. if (!gazer._teleportationRequestInitiated) {
  88197. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88198. gazer._activatePointer();
  88199. gazer._teleportationRequestInitiated = true;
  88200. }
  88201. }
  88202. else {
  88203. // Listening to the proper controller values changes to confirm teleportation
  88204. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88205. if (this._teleportActive) {
  88206. this._teleportCamera(this._haloCenter);
  88207. }
  88208. gazer._teleportationRequestInitiated = false;
  88209. }
  88210. }
  88211. };
  88212. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88213. // Only rotate when user is not currently selecting a teleportation location
  88214. if (gazer._teleportationRequestInitiated) {
  88215. return;
  88216. }
  88217. if (!this._rotationLeftAsked) {
  88218. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88219. this._rotationLeftAsked = true;
  88220. if (this._rotationAllowed) {
  88221. this._rotateCamera(false);
  88222. }
  88223. }
  88224. }
  88225. else {
  88226. if (stateObject.x > -this._padSensibilityDown) {
  88227. this._rotationLeftAsked = false;
  88228. }
  88229. }
  88230. if (!this._rotationRightAsked) {
  88231. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88232. this._rotationRightAsked = true;
  88233. if (this._rotationAllowed) {
  88234. this._rotateCamera(true);
  88235. }
  88236. }
  88237. }
  88238. else {
  88239. if (stateObject.x < this._padSensibilityDown) {
  88240. this._rotationRightAsked = false;
  88241. }
  88242. }
  88243. };
  88244. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88245. // Only teleport backwards when user is not currently selecting a teleportation location
  88246. if (gazer._teleportationRequestInitiated) {
  88247. return;
  88248. }
  88249. // Teleport backwards
  88250. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88251. if (!gazer._teleportationBackRequestInitiated) {
  88252. if (!this.currentVRCamera) {
  88253. return;
  88254. }
  88255. // Get rotation and position of the current camera
  88256. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88257. var position = this.currentVRCamera.position;
  88258. // If the camera has device position, use that instead
  88259. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88260. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88261. position = this.currentVRCamera.devicePosition;
  88262. }
  88263. // Get matrix with only the y rotation of the device rotation
  88264. rotation.toEulerAnglesToRef(this._workingVector);
  88265. this._workingVector.z = 0;
  88266. this._workingVector.x = 0;
  88267. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88268. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88269. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88270. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88271. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88272. var ray = new BABYLON.Ray(position, this._workingVector);
  88273. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88274. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88275. this._teleportCamera(hit.pickedPoint);
  88276. }
  88277. gazer._teleportationBackRequestInitiated = true;
  88278. }
  88279. }
  88280. else {
  88281. gazer._teleportationBackRequestInitiated = false;
  88282. }
  88283. };
  88284. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88285. var _this = this;
  88286. var controllerMesh = controller.webVRController.mesh;
  88287. if (controllerMesh) {
  88288. if (!controller._interactionsEnabled) {
  88289. this._enableInteractionOnController(controller);
  88290. }
  88291. controller._interactionsEnabled = true;
  88292. controller._teleportationEnabled = true;
  88293. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88294. controller._dpadPressed = false;
  88295. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88296. controller._dpadPressed = stateObject.pressed;
  88297. if (!controller._dpadPressed) {
  88298. _this._rotationLeftAsked = false;
  88299. _this._rotationRightAsked = false;
  88300. controller._teleportationBackRequestInitiated = false;
  88301. }
  88302. });
  88303. }
  88304. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88305. if (_this.teleportationEnabled) {
  88306. _this._checkTeleportBackwards(stateObject, controller);
  88307. _this._checkTeleportWithRay(stateObject, controller);
  88308. }
  88309. _this._checkRotate(stateObject, controller);
  88310. });
  88311. }
  88312. };
  88313. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88314. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88315. this._teleportationTarget.isPickable = false;
  88316. var length = 512;
  88317. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88318. dynamicTexture.hasAlpha = true;
  88319. var context = dynamicTexture.getContext();
  88320. var centerX = length / 2;
  88321. var centerY = length / 2;
  88322. var radius = 200;
  88323. context.beginPath();
  88324. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88325. context.fillStyle = this._teleportationFillColor;
  88326. context.fill();
  88327. context.lineWidth = 10;
  88328. context.strokeStyle = this._teleportationBorderColor;
  88329. context.stroke();
  88330. context.closePath();
  88331. dynamicTexture.update();
  88332. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88333. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88334. this._teleportationTarget.material = teleportationCircleMaterial;
  88335. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88336. torus.isPickable = false;
  88337. torus.parent = this._teleportationTarget;
  88338. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88339. var keys = [];
  88340. keys.push({
  88341. frame: 0,
  88342. value: 0
  88343. });
  88344. keys.push({
  88345. frame: 30,
  88346. value: 0.4
  88347. });
  88348. keys.push({
  88349. frame: 60,
  88350. value: 0
  88351. });
  88352. animationInnerCircle.setKeys(keys);
  88353. var easingFunction = new BABYLON.SineEase();
  88354. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88355. animationInnerCircle.setEasingFunction(easingFunction);
  88356. torus.animations = [];
  88357. torus.animations.push(animationInnerCircle);
  88358. this._scene.beginAnimation(torus, 0, 60, true);
  88359. this._hideTeleportationTarget();
  88360. };
  88361. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88362. this._teleportActive = true;
  88363. if (this._teleportationInitialized) {
  88364. this._teleportationTarget.isVisible = true;
  88365. if (this._isDefaultTeleportationTarget) {
  88366. this._teleportationTarget.getChildren()[0].isVisible = true;
  88367. }
  88368. }
  88369. };
  88370. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88371. this._teleportActive = false;
  88372. if (this._teleportationInitialized) {
  88373. this._teleportationTarget.isVisible = false;
  88374. if (this._isDefaultTeleportationTarget) {
  88375. this._teleportationTarget.getChildren()[0].isVisible = false;
  88376. }
  88377. }
  88378. };
  88379. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88380. var _this = this;
  88381. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88382. return;
  88383. }
  88384. if (right) {
  88385. this._rotationAngle++;
  88386. }
  88387. else {
  88388. this._rotationAngle--;
  88389. }
  88390. this.currentVRCamera.animations = [];
  88391. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88392. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88393. var animationRotationKeys = [];
  88394. animationRotationKeys.push({
  88395. frame: 0,
  88396. value: this.currentVRCamera.rotationQuaternion
  88397. });
  88398. animationRotationKeys.push({
  88399. frame: 6,
  88400. value: target
  88401. });
  88402. animationRotation.setKeys(animationRotationKeys);
  88403. animationRotation.setEasingFunction(this._circleEase);
  88404. this.currentVRCamera.animations.push(animationRotation);
  88405. this._postProcessMove.animations = [];
  88406. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88407. var vignetteWeightKeys = [];
  88408. vignetteWeightKeys.push({
  88409. frame: 0,
  88410. value: 0
  88411. });
  88412. vignetteWeightKeys.push({
  88413. frame: 3,
  88414. value: 4
  88415. });
  88416. vignetteWeightKeys.push({
  88417. frame: 6,
  88418. value: 0
  88419. });
  88420. animationPP.setKeys(vignetteWeightKeys);
  88421. animationPP.setEasingFunction(this._circleEase);
  88422. this._postProcessMove.animations.push(animationPP);
  88423. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88424. var vignetteStretchKeys = [];
  88425. vignetteStretchKeys.push({
  88426. frame: 0,
  88427. value: 0
  88428. });
  88429. vignetteStretchKeys.push({
  88430. frame: 3,
  88431. value: 10
  88432. });
  88433. vignetteStretchKeys.push({
  88434. frame: 6,
  88435. value: 0
  88436. });
  88437. animationPP2.setKeys(vignetteStretchKeys);
  88438. animationPP2.setEasingFunction(this._circleEase);
  88439. this._postProcessMove.animations.push(animationPP2);
  88440. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88441. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88442. this._postProcessMove.samples = 4;
  88443. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88444. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88445. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88446. });
  88447. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88448. };
  88449. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88450. if (hit.pickedPoint) {
  88451. if (gazer._teleportationRequestInitiated) {
  88452. this._displayTeleportationTarget();
  88453. this._haloCenter.copyFrom(hit.pickedPoint);
  88454. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88455. }
  88456. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88457. if (pickNormal) {
  88458. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88459. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88460. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88461. }
  88462. this._teleportationTarget.position.y += 0.1;
  88463. }
  88464. };
  88465. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88466. var _this = this;
  88467. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88468. return;
  88469. }
  88470. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88471. // offset of the headset from the anchor.
  88472. if (this.webVRCamera.leftCamera) {
  88473. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88474. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88475. location.subtractToRef(this._workingVector, this._workingVector);
  88476. }
  88477. else {
  88478. this._workingVector.copyFrom(location);
  88479. }
  88480. // Add height to account for user's height offset
  88481. if (this.isInVRMode) {
  88482. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88483. }
  88484. else {
  88485. this._workingVector.y += this._defaultHeight;
  88486. }
  88487. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88488. // Create animation from the camera's position to the new location
  88489. this.currentVRCamera.animations = [];
  88490. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88491. var animationCameraTeleportationKeys = [{
  88492. frame: 0,
  88493. value: this.currentVRCamera.position
  88494. },
  88495. {
  88496. frame: 11,
  88497. value: this._workingVector
  88498. }
  88499. ];
  88500. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88501. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88502. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88503. this._postProcessMove.animations = [];
  88504. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88505. var vignetteWeightKeys = [];
  88506. vignetteWeightKeys.push({
  88507. frame: 0,
  88508. value: 0
  88509. });
  88510. vignetteWeightKeys.push({
  88511. frame: 5,
  88512. value: 8
  88513. });
  88514. vignetteWeightKeys.push({
  88515. frame: 11,
  88516. value: 0
  88517. });
  88518. animationPP.setKeys(vignetteWeightKeys);
  88519. this._postProcessMove.animations.push(animationPP);
  88520. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88521. var vignetteStretchKeys = [];
  88522. vignetteStretchKeys.push({
  88523. frame: 0,
  88524. value: 0
  88525. });
  88526. vignetteStretchKeys.push({
  88527. frame: 5,
  88528. value: 10
  88529. });
  88530. vignetteStretchKeys.push({
  88531. frame: 11,
  88532. value: 0
  88533. });
  88534. animationPP2.setKeys(vignetteStretchKeys);
  88535. this._postProcessMove.animations.push(animationPP2);
  88536. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88537. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88538. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88539. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88540. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88541. });
  88542. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88543. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88544. });
  88545. this._hideTeleportationTarget();
  88546. };
  88547. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88548. if (normal) {
  88549. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88550. if (angle < Math.PI / 2) {
  88551. normal.scaleInPlace(-1);
  88552. }
  88553. }
  88554. return normal;
  88555. };
  88556. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88557. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88558. return;
  88559. }
  88560. var ray = gazer._getForwardRay(this._rayLength);
  88561. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88562. // Moving the gazeTracker on the mesh face targetted
  88563. if (hit && hit.pickedPoint) {
  88564. if (this._displayGaze) {
  88565. var multiplier = 1;
  88566. gazer._gazeTracker.isVisible = true;
  88567. if (gazer._isActionableMesh) {
  88568. multiplier = 3;
  88569. }
  88570. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88571. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88572. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88573. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88574. // To avoid z-fighting
  88575. var deltaFighting = 0.002;
  88576. if (pickNormal) {
  88577. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88578. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88579. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88580. }
  88581. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88582. if (gazer._gazeTracker.position.x < 0) {
  88583. gazer._gazeTracker.position.x += deltaFighting;
  88584. }
  88585. else {
  88586. gazer._gazeTracker.position.x -= deltaFighting;
  88587. }
  88588. if (gazer._gazeTracker.position.y < 0) {
  88589. gazer._gazeTracker.position.y += deltaFighting;
  88590. }
  88591. else {
  88592. gazer._gazeTracker.position.y -= deltaFighting;
  88593. }
  88594. if (gazer._gazeTracker.position.z < 0) {
  88595. gazer._gazeTracker.position.z += deltaFighting;
  88596. }
  88597. else {
  88598. gazer._gazeTracker.position.z -= deltaFighting;
  88599. }
  88600. }
  88601. // Changing the size of the laser pointer based on the distance from the targetted point
  88602. gazer._updatePointerDistance(hit.distance);
  88603. }
  88604. else {
  88605. gazer._gazeTracker.isVisible = false;
  88606. }
  88607. if (hit && hit.pickedMesh) {
  88608. gazer._currentHit = hit;
  88609. if (gazer._pointerDownOnMeshAsked) {
  88610. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88611. }
  88612. // The object selected is the floor, we're in a teleportation scenario
  88613. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88614. // Moving the teleportation area to this targetted point
  88615. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88616. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88617. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88618. }
  88619. gazer._currentMeshSelected = null;
  88620. if (gazer._teleportationRequestInitiated) {
  88621. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88622. }
  88623. return;
  88624. }
  88625. // If not, we're in a selection scenario
  88626. //this._teleportationAllowed = false;
  88627. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88628. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88629. this.onNewMeshPicked.notifyObservers(hit);
  88630. gazer._currentMeshSelected = hit.pickedMesh;
  88631. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88632. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88633. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88634. gazer._isActionableMesh = true;
  88635. }
  88636. else {
  88637. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88638. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88639. gazer._isActionableMesh = false;
  88640. }
  88641. try {
  88642. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88643. }
  88644. catch (err) {
  88645. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88646. }
  88647. }
  88648. else {
  88649. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88650. gazer._currentMeshSelected = null;
  88651. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88652. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88653. }
  88654. }
  88655. }
  88656. else {
  88657. gazer._currentHit = null;
  88658. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88659. gazer._currentMeshSelected = null;
  88660. //this._teleportationAllowed = false;
  88661. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88662. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88663. }
  88664. };
  88665. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88666. if (mesh) {
  88667. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88668. }
  88669. };
  88670. /**
  88671. * Sets the color of the laser ray from the vr controllers.
  88672. * @param color new color for the ray.
  88673. */
  88674. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88675. if (this.leftController) {
  88676. this.leftController._setLaserPointerColor(color);
  88677. }
  88678. if (this.rightController) {
  88679. this.rightController._setLaserPointerColor(color);
  88680. }
  88681. };
  88682. /**
  88683. * Sets the color of the ray from the vr headsets gaze.
  88684. * @param color new color for the ray.
  88685. */
  88686. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88687. if (!this._cameraGazer._gazeTracker.material) {
  88688. return;
  88689. }
  88690. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88691. if (this.leftController) {
  88692. this.leftController._gazeTracker.material.emissiveColor = color;
  88693. }
  88694. if (this.rightController) {
  88695. this.rightController._gazeTracker.material.emissiveColor = color;
  88696. }
  88697. };
  88698. /**
  88699. * Exits VR and disposes of the vr experience helper
  88700. */
  88701. VRExperienceHelper.prototype.dispose = function () {
  88702. if (this.isInVRMode) {
  88703. this.exitVR();
  88704. }
  88705. if (this._postProcessMove) {
  88706. this._postProcessMove.dispose();
  88707. }
  88708. if (this._webVRCamera) {
  88709. this._webVRCamera.dispose();
  88710. }
  88711. if (this._vrDeviceOrientationCamera) {
  88712. this._vrDeviceOrientationCamera.dispose();
  88713. }
  88714. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88715. document.body.removeChild(this._btnVR);
  88716. }
  88717. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88718. this._deviceOrientationCamera.dispose();
  88719. }
  88720. if (this._cameraGazer) {
  88721. this._cameraGazer.dispose();
  88722. }
  88723. if (this.leftController) {
  88724. this.leftController.dispose();
  88725. }
  88726. if (this.rightController) {
  88727. this.rightController.dispose();
  88728. }
  88729. if (this._teleportationTarget) {
  88730. this._teleportationTarget.dispose();
  88731. }
  88732. this._floorMeshesCollection = [];
  88733. document.removeEventListener("keydown", this._onKeyDown);
  88734. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88735. window.removeEventListener("resize", this._onResize);
  88736. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88737. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88738. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88739. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88740. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88741. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88742. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88743. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88744. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88745. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88746. this._scene.unregisterBeforeRender(this.beforeRender);
  88747. };
  88748. /**
  88749. * Gets the name of the VRExperienceHelper class
  88750. * @returns "VRExperienceHelper"
  88751. */
  88752. VRExperienceHelper.prototype.getClassName = function () {
  88753. return "VRExperienceHelper";
  88754. };
  88755. return VRExperienceHelper;
  88756. }());
  88757. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88758. })(BABYLON || (BABYLON = {}));
  88759. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88760. // Mainly based on these 2 articles :
  88761. // 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
  88762. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88763. var BABYLON;
  88764. (function (BABYLON) {
  88765. /**
  88766. * Defines the potential axis of a Joystick
  88767. */
  88768. var JoystickAxis;
  88769. (function (JoystickAxis) {
  88770. /** X axis */
  88771. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88772. /** Y axis */
  88773. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88774. /** Z axis */
  88775. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88776. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88777. /**
  88778. * Class used to define virtual joystick (used in touch mode)
  88779. */
  88780. var VirtualJoystick = /** @class */ (function () {
  88781. /**
  88782. * Creates a new virtual joystick
  88783. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88784. */
  88785. function VirtualJoystick(leftJoystick) {
  88786. var _this = this;
  88787. if (leftJoystick) {
  88788. this._leftJoystick = true;
  88789. }
  88790. else {
  88791. this._leftJoystick = false;
  88792. }
  88793. VirtualJoystick._globalJoystickIndex++;
  88794. // By default left & right arrow keys are moving the X
  88795. // and up & down keys are moving the Y
  88796. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88797. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88798. this.reverseLeftRight = false;
  88799. this.reverseUpDown = false;
  88800. // collections of pointers
  88801. this._touches = new BABYLON.StringDictionary();
  88802. this.deltaPosition = BABYLON.Vector3.Zero();
  88803. this._joystickSensibility = 25;
  88804. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88805. this._onResize = function (evt) {
  88806. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88807. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88808. if (VirtualJoystick.vjCanvas) {
  88809. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88810. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88811. }
  88812. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88813. };
  88814. // injecting a canvas element on top of the canvas 3D game
  88815. if (!VirtualJoystick.vjCanvas) {
  88816. window.addEventListener("resize", this._onResize, false);
  88817. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88818. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88819. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88820. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88821. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88822. VirtualJoystick.vjCanvas.style.width = "100%";
  88823. VirtualJoystick.vjCanvas.style.height = "100%";
  88824. VirtualJoystick.vjCanvas.style.position = "absolute";
  88825. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88826. VirtualJoystick.vjCanvas.style.top = "0px";
  88827. VirtualJoystick.vjCanvas.style.left = "0px";
  88828. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88829. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88830. // Support for jQuery PEP polyfill
  88831. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88832. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88833. if (!context) {
  88834. throw new Error("Unable to create canvas for virtual joystick");
  88835. }
  88836. VirtualJoystick.vjCanvasContext = context;
  88837. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88838. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88839. document.body.appendChild(VirtualJoystick.vjCanvas);
  88840. }
  88841. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88842. this.pressed = false;
  88843. // default joystick color
  88844. this._joystickColor = "cyan";
  88845. this._joystickPointerID = -1;
  88846. // current joystick position
  88847. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88848. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88849. // origin joystick position
  88850. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88851. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88852. this._onPointerDownHandlerRef = function (evt) {
  88853. _this._onPointerDown(evt);
  88854. };
  88855. this._onPointerMoveHandlerRef = function (evt) {
  88856. _this._onPointerMove(evt);
  88857. };
  88858. this._onPointerUpHandlerRef = function (evt) {
  88859. _this._onPointerUp(evt);
  88860. };
  88861. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  88862. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  88863. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  88864. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  88865. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  88866. evt.preventDefault(); // Disables system menu
  88867. }, false);
  88868. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88869. }
  88870. /**
  88871. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  88872. * @param newJoystickSensibility defines the new sensibility
  88873. */
  88874. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  88875. this._joystickSensibility = newJoystickSensibility;
  88876. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88877. };
  88878. VirtualJoystick.prototype._onPointerDown = function (e) {
  88879. var positionOnScreenCondition;
  88880. e.preventDefault();
  88881. if (this._leftJoystick === true) {
  88882. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  88883. }
  88884. else {
  88885. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  88886. }
  88887. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  88888. // First contact will be dedicated to the virtual joystick
  88889. this._joystickPointerID = e.pointerId;
  88890. this._joystickPointerStartPos.x = e.clientX;
  88891. this._joystickPointerStartPos.y = e.clientY;
  88892. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  88893. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  88894. this._deltaJoystickVector.x = 0;
  88895. this._deltaJoystickVector.y = 0;
  88896. this.pressed = true;
  88897. this._touches.add(e.pointerId.toString(), e);
  88898. }
  88899. else {
  88900. // You can only trigger the action buttons with a joystick declared
  88901. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  88902. this._action();
  88903. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  88904. }
  88905. }
  88906. };
  88907. VirtualJoystick.prototype._onPointerMove = function (e) {
  88908. // If the current pointer is the one associated to the joystick (first touch contact)
  88909. if (this._joystickPointerID == e.pointerId) {
  88910. this._joystickPointerPos.x = e.clientX;
  88911. this._joystickPointerPos.y = e.clientY;
  88912. this._deltaJoystickVector = this._joystickPointerPos.clone();
  88913. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  88914. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  88915. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  88916. switch (this._axisTargetedByLeftAndRight) {
  88917. case JoystickAxis.X:
  88918. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  88919. break;
  88920. case JoystickAxis.Y:
  88921. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  88922. break;
  88923. case JoystickAxis.Z:
  88924. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  88925. break;
  88926. }
  88927. var directionUpDown = this.reverseUpDown ? 1 : -1;
  88928. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  88929. switch (this._axisTargetedByUpAndDown) {
  88930. case JoystickAxis.X:
  88931. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  88932. break;
  88933. case JoystickAxis.Y:
  88934. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  88935. break;
  88936. case JoystickAxis.Z:
  88937. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  88938. break;
  88939. }
  88940. }
  88941. else {
  88942. var data = this._touches.get(e.pointerId.toString());
  88943. if (data) {
  88944. data.x = e.clientX;
  88945. data.y = e.clientY;
  88946. }
  88947. }
  88948. };
  88949. VirtualJoystick.prototype._onPointerUp = function (e) {
  88950. if (this._joystickPointerID == e.pointerId) {
  88951. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  88952. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  88953. this._joystickPointerID = -1;
  88954. this.pressed = false;
  88955. }
  88956. else {
  88957. var touch = this._touches.get(e.pointerId.toString());
  88958. if (touch) {
  88959. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88960. }
  88961. }
  88962. this._deltaJoystickVector.x = 0;
  88963. this._deltaJoystickVector.y = 0;
  88964. this._touches.remove(e.pointerId.toString());
  88965. };
  88966. /**
  88967. * Change the color of the virtual joystick
  88968. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  88969. */
  88970. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  88971. this._joystickColor = newColor;
  88972. };
  88973. /**
  88974. * Defines a callback to call when the joystick is touched
  88975. * @param action defines the callback
  88976. */
  88977. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  88978. this._action = action;
  88979. };
  88980. /**
  88981. * Defines which axis you'd like to control for left & right
  88982. * @param axis defines the axis to use
  88983. */
  88984. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  88985. switch (axis) {
  88986. case JoystickAxis.X:
  88987. case JoystickAxis.Y:
  88988. case JoystickAxis.Z:
  88989. this._axisTargetedByLeftAndRight = axis;
  88990. break;
  88991. default:
  88992. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88993. break;
  88994. }
  88995. };
  88996. /**
  88997. * Defines which axis you'd like to control for up & down
  88998. * @param axis defines the axis to use
  88999. */
  89000. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89001. switch (axis) {
  89002. case JoystickAxis.X:
  89003. case JoystickAxis.Y:
  89004. case JoystickAxis.Z:
  89005. this._axisTargetedByUpAndDown = axis;
  89006. break;
  89007. default:
  89008. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89009. break;
  89010. }
  89011. };
  89012. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89013. var _this = this;
  89014. if (this.pressed) {
  89015. this._touches.forEach(function (key, touch) {
  89016. if (touch.pointerId === _this._joystickPointerID) {
  89017. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89018. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89019. VirtualJoystick.vjCanvasContext.beginPath();
  89020. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89021. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89022. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89023. VirtualJoystick.vjCanvasContext.stroke();
  89024. VirtualJoystick.vjCanvasContext.closePath();
  89025. VirtualJoystick.vjCanvasContext.beginPath();
  89026. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89027. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89028. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89029. VirtualJoystick.vjCanvasContext.stroke();
  89030. VirtualJoystick.vjCanvasContext.closePath();
  89031. VirtualJoystick.vjCanvasContext.beginPath();
  89032. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89033. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89034. VirtualJoystick.vjCanvasContext.stroke();
  89035. VirtualJoystick.vjCanvasContext.closePath();
  89036. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89037. }
  89038. else {
  89039. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89040. VirtualJoystick.vjCanvasContext.beginPath();
  89041. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89042. VirtualJoystick.vjCanvasContext.beginPath();
  89043. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89044. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89045. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89046. VirtualJoystick.vjCanvasContext.stroke();
  89047. VirtualJoystick.vjCanvasContext.closePath();
  89048. touch.prevX = touch.x;
  89049. touch.prevY = touch.y;
  89050. }
  89051. ;
  89052. });
  89053. }
  89054. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89055. };
  89056. /**
  89057. * Release internal HTML canvas
  89058. */
  89059. VirtualJoystick.prototype.releaseCanvas = function () {
  89060. if (VirtualJoystick.vjCanvas) {
  89061. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89062. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89063. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89064. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89065. window.removeEventListener("resize", this._onResize);
  89066. document.body.removeChild(VirtualJoystick.vjCanvas);
  89067. VirtualJoystick.vjCanvas = null;
  89068. }
  89069. };
  89070. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89071. VirtualJoystick._globalJoystickIndex = 0;
  89072. return VirtualJoystick;
  89073. }());
  89074. BABYLON.VirtualJoystick = VirtualJoystick;
  89075. })(BABYLON || (BABYLON = {}));
  89076. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89077. var BABYLON;
  89078. (function (BABYLON) {
  89079. // We're mainly based on the logic defined into the FreeCamera code
  89080. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89081. __extends(VirtualJoysticksCamera, _super);
  89082. function VirtualJoysticksCamera(name, position, scene) {
  89083. var _this = _super.call(this, name, position, scene) || this;
  89084. _this.inputs.addVirtualJoystick();
  89085. return _this;
  89086. }
  89087. VirtualJoysticksCamera.prototype.getClassName = function () {
  89088. return "VirtualJoysticksCamera";
  89089. };
  89090. return VirtualJoysticksCamera;
  89091. }(BABYLON.FreeCamera));
  89092. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89093. })(BABYLON || (BABYLON = {}));
  89094. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89095. var BABYLON;
  89096. (function (BABYLON) {
  89097. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89098. function FreeCameraVirtualJoystickInput() {
  89099. }
  89100. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89101. return this._leftjoystick;
  89102. };
  89103. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89104. return this._rightjoystick;
  89105. };
  89106. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89107. if (this._leftjoystick) {
  89108. var camera = this.camera;
  89109. var speed = camera._computeLocalCameraSpeed() * 50;
  89110. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89111. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89112. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89113. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89114. if (!this._leftjoystick.pressed) {
  89115. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89116. }
  89117. if (!this._rightjoystick.pressed) {
  89118. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89119. }
  89120. }
  89121. };
  89122. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89123. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89124. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89125. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89126. this._leftjoystick.setJoystickSensibility(0.15);
  89127. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89128. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89129. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89130. this._rightjoystick.reverseUpDown = true;
  89131. this._rightjoystick.setJoystickSensibility(0.05);
  89132. this._rightjoystick.setJoystickColor("yellow");
  89133. };
  89134. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89135. this._leftjoystick.releaseCanvas();
  89136. this._rightjoystick.releaseCanvas();
  89137. };
  89138. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89139. return "FreeCameraVirtualJoystickInput";
  89140. };
  89141. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89142. return "virtualJoystick";
  89143. };
  89144. return FreeCameraVirtualJoystickInput;
  89145. }());
  89146. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89147. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89148. })(BABYLON || (BABYLON = {}));
  89149. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89150. var BABYLON;
  89151. (function (BABYLON) {
  89152. var SimplificationSettings = /** @class */ (function () {
  89153. function SimplificationSettings(quality, distance, optimizeMesh) {
  89154. this.quality = quality;
  89155. this.distance = distance;
  89156. this.optimizeMesh = optimizeMesh;
  89157. }
  89158. return SimplificationSettings;
  89159. }());
  89160. BABYLON.SimplificationSettings = SimplificationSettings;
  89161. var SimplificationQueue = /** @class */ (function () {
  89162. function SimplificationQueue() {
  89163. this.running = false;
  89164. this._simplificationArray = [];
  89165. }
  89166. SimplificationQueue.prototype.addTask = function (task) {
  89167. this._simplificationArray.push(task);
  89168. };
  89169. SimplificationQueue.prototype.executeNext = function () {
  89170. var task = this._simplificationArray.pop();
  89171. if (task) {
  89172. this.running = true;
  89173. this.runSimplification(task);
  89174. }
  89175. else {
  89176. this.running = false;
  89177. }
  89178. };
  89179. SimplificationQueue.prototype.runSimplification = function (task) {
  89180. var _this = this;
  89181. if (task.parallelProcessing) {
  89182. //parallel simplifier
  89183. task.settings.forEach(function (setting) {
  89184. var simplifier = _this.getSimplifier(task);
  89185. simplifier.simplify(setting, function (newMesh) {
  89186. task.mesh.addLODLevel(setting.distance, newMesh);
  89187. newMesh.isVisible = true;
  89188. //check if it is the last
  89189. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89190. //all done, run the success callback.
  89191. task.successCallback();
  89192. }
  89193. _this.executeNext();
  89194. });
  89195. });
  89196. }
  89197. else {
  89198. //single simplifier.
  89199. var simplifier = this.getSimplifier(task);
  89200. var runDecimation = function (setting, callback) {
  89201. simplifier.simplify(setting, function (newMesh) {
  89202. task.mesh.addLODLevel(setting.distance, newMesh);
  89203. newMesh.isVisible = true;
  89204. //run the next quality level
  89205. callback();
  89206. });
  89207. };
  89208. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89209. runDecimation(task.settings[loop.index], function () {
  89210. loop.executeNext();
  89211. });
  89212. }, function () {
  89213. //execution ended, run the success callback.
  89214. if (task.successCallback) {
  89215. task.successCallback();
  89216. }
  89217. _this.executeNext();
  89218. });
  89219. }
  89220. };
  89221. SimplificationQueue.prototype.getSimplifier = function (task) {
  89222. switch (task.simplificationType) {
  89223. case SimplificationType.QUADRATIC:
  89224. default:
  89225. return new QuadraticErrorSimplification(task.mesh);
  89226. }
  89227. };
  89228. return SimplificationQueue;
  89229. }());
  89230. BABYLON.SimplificationQueue = SimplificationQueue;
  89231. /**
  89232. * The implemented types of simplification
  89233. * At the moment only Quadratic Error Decimation is implemented
  89234. */
  89235. var SimplificationType;
  89236. (function (SimplificationType) {
  89237. /** Quadratic error decimation */
  89238. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89239. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89240. var DecimationTriangle = /** @class */ (function () {
  89241. function DecimationTriangle(vertices) {
  89242. this.vertices = vertices;
  89243. this.error = new Array(4);
  89244. this.deleted = false;
  89245. this.isDirty = false;
  89246. this.deletePending = false;
  89247. this.borderFactor = 0;
  89248. }
  89249. return DecimationTriangle;
  89250. }());
  89251. BABYLON.DecimationTriangle = DecimationTriangle;
  89252. var DecimationVertex = /** @class */ (function () {
  89253. function DecimationVertex(position, id) {
  89254. this.position = position;
  89255. this.id = id;
  89256. this.isBorder = true;
  89257. this.q = new QuadraticMatrix();
  89258. this.triangleCount = 0;
  89259. this.triangleStart = 0;
  89260. this.originalOffsets = [];
  89261. }
  89262. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89263. this.position.copyFrom(newPosition);
  89264. };
  89265. return DecimationVertex;
  89266. }());
  89267. BABYLON.DecimationVertex = DecimationVertex;
  89268. var QuadraticMatrix = /** @class */ (function () {
  89269. function QuadraticMatrix(data) {
  89270. this.data = new Array(10);
  89271. for (var i = 0; i < 10; ++i) {
  89272. if (data && data[i]) {
  89273. this.data[i] = data[i];
  89274. }
  89275. else {
  89276. this.data[i] = 0;
  89277. }
  89278. }
  89279. }
  89280. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89281. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89282. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89283. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89284. return det;
  89285. };
  89286. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89287. for (var i = 0; i < 10; ++i) {
  89288. this.data[i] += matrix.data[i];
  89289. }
  89290. };
  89291. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89292. for (var i = 0; i < 10; ++i) {
  89293. this.data[i] += data[i];
  89294. }
  89295. };
  89296. QuadraticMatrix.prototype.add = function (matrix) {
  89297. var m = new QuadraticMatrix();
  89298. for (var i = 0; i < 10; ++i) {
  89299. m.data[i] = this.data[i] + matrix.data[i];
  89300. }
  89301. return m;
  89302. };
  89303. QuadraticMatrix.FromData = function (a, b, c, d) {
  89304. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89305. };
  89306. //returning an array to avoid garbage collection
  89307. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89308. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89309. };
  89310. return QuadraticMatrix;
  89311. }());
  89312. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89313. var Reference = /** @class */ (function () {
  89314. function Reference(vertexId, triangleId) {
  89315. this.vertexId = vertexId;
  89316. this.triangleId = triangleId;
  89317. }
  89318. return Reference;
  89319. }());
  89320. BABYLON.Reference = Reference;
  89321. /**
  89322. * An implementation of the Quadratic Error simplification algorithm.
  89323. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89324. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89325. * @author RaananW
  89326. */
  89327. var QuadraticErrorSimplification = /** @class */ (function () {
  89328. function QuadraticErrorSimplification(_mesh) {
  89329. this._mesh = _mesh;
  89330. this.syncIterations = 5000;
  89331. this.aggressiveness = 7;
  89332. this.decimationIterations = 100;
  89333. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89334. }
  89335. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89336. var _this = this;
  89337. this.initDecimatedMesh();
  89338. //iterating through the submeshes array, one after the other.
  89339. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89340. _this.initWithMesh(loop.index, function () {
  89341. _this.runDecimation(settings, loop.index, function () {
  89342. loop.executeNext();
  89343. });
  89344. }, settings.optimizeMesh);
  89345. }, function () {
  89346. setTimeout(function () {
  89347. successCallback(_this._reconstructedMesh);
  89348. }, 0);
  89349. });
  89350. };
  89351. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89352. var _this = this;
  89353. var targetCount = ~~(this.triangles.length * settings.quality);
  89354. var deletedTriangles = 0;
  89355. var triangleCount = this.triangles.length;
  89356. var iterationFunction = function (iteration, callback) {
  89357. setTimeout(function () {
  89358. if (iteration % 5 === 0) {
  89359. _this.updateMesh(iteration === 0);
  89360. }
  89361. for (var i = 0; i < _this.triangles.length; ++i) {
  89362. _this.triangles[i].isDirty = false;
  89363. }
  89364. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89365. var trianglesIterator = function (i) {
  89366. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89367. var t = _this.triangles[tIdx];
  89368. if (!t)
  89369. return;
  89370. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89371. return;
  89372. }
  89373. for (var j = 0; j < 3; ++j) {
  89374. if (t.error[j] < threshold) {
  89375. var deleted0 = [];
  89376. var deleted1 = [];
  89377. var v0 = t.vertices[j];
  89378. var v1 = t.vertices[(j + 1) % 3];
  89379. if (v0.isBorder || v1.isBorder)
  89380. continue;
  89381. var p = BABYLON.Vector3.Zero();
  89382. var n = BABYLON.Vector3.Zero();
  89383. var uv = BABYLON.Vector2.Zero();
  89384. var color = new BABYLON.Color4(0, 0, 0, 1);
  89385. _this.calculateError(v0, v1, p, n, uv, color);
  89386. var delTr = new Array();
  89387. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89388. continue;
  89389. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89390. continue;
  89391. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89392. continue;
  89393. var uniqueArray = new Array();
  89394. delTr.forEach(function (deletedT) {
  89395. if (uniqueArray.indexOf(deletedT) === -1) {
  89396. deletedT.deletePending = true;
  89397. uniqueArray.push(deletedT);
  89398. }
  89399. });
  89400. if (uniqueArray.length % 2 !== 0) {
  89401. continue;
  89402. }
  89403. v0.q = v1.q.add(v0.q);
  89404. v0.updatePosition(p);
  89405. var tStart = _this.references.length;
  89406. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89407. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89408. var tCount = _this.references.length - tStart;
  89409. if (tCount <= v0.triangleCount) {
  89410. if (tCount) {
  89411. for (var c = 0; c < tCount; c++) {
  89412. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89413. }
  89414. }
  89415. }
  89416. else {
  89417. v0.triangleStart = tStart;
  89418. }
  89419. v0.triangleCount = tCount;
  89420. break;
  89421. }
  89422. }
  89423. };
  89424. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89425. }, 0);
  89426. };
  89427. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89428. if (triangleCount - deletedTriangles <= targetCount)
  89429. loop.breakLoop();
  89430. else {
  89431. iterationFunction(loop.index, function () {
  89432. loop.executeNext();
  89433. });
  89434. }
  89435. }, function () {
  89436. setTimeout(function () {
  89437. //reconstruct this part of the mesh
  89438. _this.reconstructMesh(submeshIndex);
  89439. successCallback();
  89440. }, 0);
  89441. });
  89442. };
  89443. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89444. var _this = this;
  89445. this.vertices = [];
  89446. this.triangles = [];
  89447. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89448. var indices = this._mesh.getIndices();
  89449. var submesh = this._mesh.subMeshes[submeshIndex];
  89450. var findInVertices = function (positionToSearch) {
  89451. if (optimizeMesh) {
  89452. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89453. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89454. return _this.vertices[ii];
  89455. }
  89456. }
  89457. }
  89458. return null;
  89459. };
  89460. var vertexReferences = [];
  89461. var vertexInit = function (i) {
  89462. if (!positionData) {
  89463. return;
  89464. }
  89465. var offset = i + submesh.verticesStart;
  89466. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89467. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89468. vertex.originalOffsets.push(offset);
  89469. if (vertex.id === _this.vertices.length) {
  89470. _this.vertices.push(vertex);
  89471. }
  89472. vertexReferences.push(vertex.id);
  89473. };
  89474. //var totalVertices = mesh.getTotalVertices();
  89475. var totalVertices = submesh.verticesCount;
  89476. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89477. var indicesInit = function (i) {
  89478. if (!indices) {
  89479. return;
  89480. }
  89481. var offset = (submesh.indexStart / 3) + i;
  89482. var pos = (offset * 3);
  89483. var i0 = indices[pos + 0];
  89484. var i1 = indices[pos + 1];
  89485. var i2 = indices[pos + 2];
  89486. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89487. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89488. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89489. var triangle = new DecimationTriangle([v0, v1, v2]);
  89490. triangle.originalOffset = pos;
  89491. _this.triangles.push(triangle);
  89492. };
  89493. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89494. _this.init(callback);
  89495. });
  89496. });
  89497. };
  89498. QuadraticErrorSimplification.prototype.init = function (callback) {
  89499. var _this = this;
  89500. var triangleInit1 = function (i) {
  89501. var t = _this.triangles[i];
  89502. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89503. for (var j = 0; j < 3; j++) {
  89504. 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))));
  89505. }
  89506. };
  89507. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89508. var triangleInit2 = function (i) {
  89509. var t = _this.triangles[i];
  89510. for (var j = 0; j < 3; ++j) {
  89511. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89512. }
  89513. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89514. };
  89515. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89516. callback();
  89517. });
  89518. });
  89519. };
  89520. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89521. var newTriangles = [];
  89522. var i;
  89523. for (i = 0; i < this.vertices.length; ++i) {
  89524. this.vertices[i].triangleCount = 0;
  89525. }
  89526. var t;
  89527. var j;
  89528. for (i = 0; i < this.triangles.length; ++i) {
  89529. if (!this.triangles[i].deleted) {
  89530. t = this.triangles[i];
  89531. for (j = 0; j < 3; ++j) {
  89532. t.vertices[j].triangleCount = 1;
  89533. }
  89534. newTriangles.push(t);
  89535. }
  89536. }
  89537. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89538. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89539. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89540. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89541. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89542. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89543. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89544. var vertexCount = 0;
  89545. for (i = 0; i < this.vertices.length; ++i) {
  89546. var vertex = this.vertices[i];
  89547. vertex.id = vertexCount;
  89548. if (vertex.triangleCount) {
  89549. vertex.originalOffsets.forEach(function (originalOffset) {
  89550. if (!normalData) {
  89551. return;
  89552. }
  89553. newPositionData.push(vertex.position.x);
  89554. newPositionData.push(vertex.position.y);
  89555. newPositionData.push(vertex.position.z);
  89556. newNormalData.push(normalData[originalOffset * 3]);
  89557. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89558. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89559. if (uvs && uvs.length) {
  89560. newUVsData.push(uvs[(originalOffset * 2)]);
  89561. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89562. }
  89563. else if (colorsData && colorsData.length) {
  89564. newColorsData.push(colorsData[(originalOffset * 4)]);
  89565. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89566. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89567. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89568. }
  89569. ++vertexCount;
  89570. });
  89571. }
  89572. }
  89573. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89574. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89575. var submeshesArray = this._reconstructedMesh.subMeshes;
  89576. this._reconstructedMesh.subMeshes = [];
  89577. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89578. var originalIndices = this._mesh.getIndices();
  89579. for (i = 0; i < newTriangles.length; ++i) {
  89580. t = newTriangles[i]; //now get the new referencing point for each vertex
  89581. [0, 1, 2].forEach(function (idx) {
  89582. var id = originalIndices[t.originalOffset + idx];
  89583. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89584. if (offset < 0)
  89585. offset = 0;
  89586. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89587. });
  89588. }
  89589. //overwriting the old vertex buffers and indices.
  89590. this._reconstructedMesh.setIndices(newIndicesArray);
  89591. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89592. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89593. if (newUVsData.length > 0)
  89594. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89595. if (newColorsData.length > 0)
  89596. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89597. //create submesh
  89598. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89599. if (submeshIndex > 0) {
  89600. this._reconstructedMesh.subMeshes = [];
  89601. submeshesArray.forEach(function (submesh) {
  89602. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89603. });
  89604. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89605. }
  89606. };
  89607. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89608. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89609. this._reconstructedMesh.material = this._mesh.material;
  89610. this._reconstructedMesh.parent = this._mesh.parent;
  89611. this._reconstructedMesh.isVisible = false;
  89612. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89613. };
  89614. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89615. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89616. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89617. if (t.deleted)
  89618. continue;
  89619. var s = this.references[vertex1.triangleStart + i].vertexId;
  89620. var v1 = t.vertices[(s + 1) % 3];
  89621. var v2 = t.vertices[(s + 2) % 3];
  89622. if ((v1 === vertex2 || v2 === vertex2)) {
  89623. deletedArray[i] = true;
  89624. delTr.push(t);
  89625. continue;
  89626. }
  89627. var d1 = v1.position.subtract(point);
  89628. d1 = d1.normalize();
  89629. var d2 = v2.position.subtract(point);
  89630. d2 = d2.normalize();
  89631. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89632. return true;
  89633. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89634. deletedArray[i] = false;
  89635. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89636. return true;
  89637. }
  89638. return false;
  89639. };
  89640. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89641. var newDeleted = deletedTriangles;
  89642. for (var i = 0; i < vertex.triangleCount; ++i) {
  89643. var ref = this.references[vertex.triangleStart + i];
  89644. var t = this.triangles[ref.triangleId];
  89645. if (t.deleted)
  89646. continue;
  89647. if (deletedArray[i] && t.deletePending) {
  89648. t.deleted = true;
  89649. newDeleted++;
  89650. continue;
  89651. }
  89652. t.vertices[ref.vertexId] = origVertex;
  89653. t.isDirty = true;
  89654. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89655. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89656. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89657. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89658. this.references.push(ref);
  89659. }
  89660. return newDeleted;
  89661. };
  89662. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89663. for (var i = 0; i < this.vertices.length; ++i) {
  89664. var vCount = [];
  89665. var vId = [];
  89666. var v = this.vertices[i];
  89667. var j;
  89668. for (j = 0; j < v.triangleCount; ++j) {
  89669. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89670. for (var ii = 0; ii < 3; ii++) {
  89671. var ofs = 0;
  89672. var vv = triangle.vertices[ii];
  89673. while (ofs < vCount.length) {
  89674. if (vId[ofs] === vv.id)
  89675. break;
  89676. ++ofs;
  89677. }
  89678. if (ofs === vCount.length) {
  89679. vCount.push(1);
  89680. vId.push(vv.id);
  89681. }
  89682. else {
  89683. vCount[ofs]++;
  89684. }
  89685. }
  89686. }
  89687. for (j = 0; j < vCount.length; ++j) {
  89688. if (vCount[j] === 1) {
  89689. this.vertices[vId[j]].isBorder = true;
  89690. }
  89691. else {
  89692. this.vertices[vId[j]].isBorder = false;
  89693. }
  89694. }
  89695. }
  89696. };
  89697. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89698. if (identifyBorders === void 0) { identifyBorders = false; }
  89699. var i;
  89700. if (!identifyBorders) {
  89701. var newTrianglesVector = [];
  89702. for (i = 0; i < this.triangles.length; ++i) {
  89703. if (!this.triangles[i].deleted) {
  89704. newTrianglesVector.push(this.triangles[i]);
  89705. }
  89706. }
  89707. this.triangles = newTrianglesVector;
  89708. }
  89709. for (i = 0; i < this.vertices.length; ++i) {
  89710. this.vertices[i].triangleCount = 0;
  89711. this.vertices[i].triangleStart = 0;
  89712. }
  89713. var t;
  89714. var j;
  89715. var v;
  89716. for (i = 0; i < this.triangles.length; ++i) {
  89717. t = this.triangles[i];
  89718. for (j = 0; j < 3; ++j) {
  89719. v = t.vertices[j];
  89720. v.triangleCount++;
  89721. }
  89722. }
  89723. var tStart = 0;
  89724. for (i = 0; i < this.vertices.length; ++i) {
  89725. this.vertices[i].triangleStart = tStart;
  89726. tStart += this.vertices[i].triangleCount;
  89727. this.vertices[i].triangleCount = 0;
  89728. }
  89729. var newReferences = new Array(this.triangles.length * 3);
  89730. for (i = 0; i < this.triangles.length; ++i) {
  89731. t = this.triangles[i];
  89732. for (j = 0; j < 3; ++j) {
  89733. v = t.vertices[j];
  89734. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89735. v.triangleCount++;
  89736. }
  89737. }
  89738. this.references = newReferences;
  89739. if (identifyBorders) {
  89740. this.identifyBorder();
  89741. }
  89742. };
  89743. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89744. var x = point.x;
  89745. var y = point.y;
  89746. var z = point.z;
  89747. 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
  89748. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89749. };
  89750. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89751. var q = vertex1.q.add(vertex2.q);
  89752. var border = vertex1.isBorder && vertex2.isBorder;
  89753. var error = 0;
  89754. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89755. if (qDet !== 0 && !border) {
  89756. if (!pointResult) {
  89757. pointResult = BABYLON.Vector3.Zero();
  89758. }
  89759. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89760. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89761. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89762. error = this.vertexError(q, pointResult);
  89763. }
  89764. else {
  89765. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89766. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89767. var error1 = this.vertexError(q, vertex1.position);
  89768. var error2 = this.vertexError(q, vertex2.position);
  89769. var error3 = this.vertexError(q, p3);
  89770. error = Math.min(error1, error2, error3);
  89771. if (error === error1) {
  89772. if (pointResult) {
  89773. pointResult.copyFrom(vertex1.position);
  89774. }
  89775. }
  89776. else if (error === error2) {
  89777. if (pointResult) {
  89778. pointResult.copyFrom(vertex2.position);
  89779. }
  89780. }
  89781. else {
  89782. if (pointResult) {
  89783. pointResult.copyFrom(p3);
  89784. }
  89785. }
  89786. }
  89787. return error;
  89788. };
  89789. return QuadraticErrorSimplification;
  89790. }());
  89791. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89792. })(BABYLON || (BABYLON = {}));
  89793. //# sourceMappingURL=babylon.meshSimplification.js.map
  89794. var BABYLON;
  89795. (function (BABYLON) {
  89796. var MeshLODLevel = /** @class */ (function () {
  89797. function MeshLODLevel(distance, mesh) {
  89798. this.distance = distance;
  89799. this.mesh = mesh;
  89800. }
  89801. return MeshLODLevel;
  89802. }());
  89803. BABYLON.MeshLODLevel = MeshLODLevel;
  89804. })(BABYLON || (BABYLON = {}));
  89805. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89806. var BABYLON;
  89807. (function (BABYLON) {
  89808. /**
  89809. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89810. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89811. */
  89812. var SceneOptimization = /** @class */ (function () {
  89813. /**
  89814. * Creates the SceneOptimization object
  89815. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89816. * @param desc defines the description associated with the optimization
  89817. */
  89818. function SceneOptimization(
  89819. /**
  89820. * Defines the priority of this optimization (0 by default which means first in the list)
  89821. */
  89822. priority) {
  89823. if (priority === void 0) { priority = 0; }
  89824. this.priority = priority;
  89825. }
  89826. /**
  89827. * Gets a string describing the action executed by the current optimization
  89828. * @returns description string
  89829. */
  89830. SceneOptimization.prototype.getDescription = function () {
  89831. return "";
  89832. };
  89833. /**
  89834. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89835. * @param scene defines the current scene where to apply this optimization
  89836. * @param optimizer defines the current optimizer
  89837. * @returns true if everything that can be done was applied
  89838. */
  89839. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89840. return true;
  89841. };
  89842. ;
  89843. return SceneOptimization;
  89844. }());
  89845. BABYLON.SceneOptimization = SceneOptimization;
  89846. /**
  89847. * Defines an optimization used to reduce the size of render target textures
  89848. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89849. */
  89850. var TextureOptimization = /** @class */ (function (_super) {
  89851. __extends(TextureOptimization, _super);
  89852. /**
  89853. * Creates the TextureOptimization object
  89854. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89855. * @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
  89856. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89857. */
  89858. function TextureOptimization(
  89859. /**
  89860. * Defines the priority of this optimization (0 by default which means first in the list)
  89861. */
  89862. priority,
  89863. /**
  89864. * 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
  89865. */
  89866. maximumSize,
  89867. /**
  89868. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89869. */
  89870. step) {
  89871. if (priority === void 0) { priority = 0; }
  89872. if (maximumSize === void 0) { maximumSize = 1024; }
  89873. if (step === void 0) { step = 0.5; }
  89874. var _this = _super.call(this, priority) || this;
  89875. _this.priority = priority;
  89876. _this.maximumSize = maximumSize;
  89877. _this.step = step;
  89878. return _this;
  89879. }
  89880. /**
  89881. * Gets a string describing the action executed by the current optimization
  89882. * @returns description string
  89883. */
  89884. TextureOptimization.prototype.getDescription = function () {
  89885. return "Reducing render target texture size to " + this.maximumSize;
  89886. };
  89887. /**
  89888. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89889. * @param scene defines the current scene where to apply this optimization
  89890. * @param optimizer defines the current optimizer
  89891. * @returns true if everything that can be done was applied
  89892. */
  89893. TextureOptimization.prototype.apply = function (scene, optimizer) {
  89894. var allDone = true;
  89895. for (var index = 0; index < scene.textures.length; index++) {
  89896. var texture = scene.textures[index];
  89897. if (!texture.canRescale || texture.getContext) {
  89898. continue;
  89899. }
  89900. var currentSize = texture.getSize();
  89901. var maxDimension = Math.max(currentSize.width, currentSize.height);
  89902. if (maxDimension > this.maximumSize) {
  89903. texture.scale(this.step);
  89904. allDone = false;
  89905. }
  89906. }
  89907. return allDone;
  89908. };
  89909. return TextureOptimization;
  89910. }(SceneOptimization));
  89911. BABYLON.TextureOptimization = TextureOptimization;
  89912. /**
  89913. * Defines an optimization used to increase or decrease the rendering resolution
  89914. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89915. */
  89916. var HardwareScalingOptimization = /** @class */ (function (_super) {
  89917. __extends(HardwareScalingOptimization, _super);
  89918. /**
  89919. * Creates the HardwareScalingOptimization object
  89920. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89921. * @param maximumScale defines the maximum scale to use (2 by default)
  89922. * @param step defines the step to use between two passes (0.5 by default)
  89923. */
  89924. function HardwareScalingOptimization(
  89925. /**
  89926. * Defines the priority of this optimization (0 by default which means first in the list)
  89927. */
  89928. priority,
  89929. /**
  89930. * Defines the maximum scale to use (2 by default)
  89931. */
  89932. maximumScale,
  89933. /**
  89934. * Defines the step to use between two passes (0.5 by default)
  89935. */
  89936. step) {
  89937. if (priority === void 0) { priority = 0; }
  89938. if (maximumScale === void 0) { maximumScale = 2; }
  89939. if (step === void 0) { step = 0.25; }
  89940. var _this = _super.call(this, priority) || this;
  89941. _this.priority = priority;
  89942. _this.maximumScale = maximumScale;
  89943. _this.step = step;
  89944. _this._currentScale = -1;
  89945. _this._directionOffset = 1;
  89946. return _this;
  89947. }
  89948. /**
  89949. * Gets a string describing the action executed by the current optimization
  89950. * @return description string
  89951. */
  89952. HardwareScalingOptimization.prototype.getDescription = function () {
  89953. return "Setting hardware scaling level to " + this._currentScale;
  89954. };
  89955. /**
  89956. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89957. * @param scene defines the current scene where to apply this optimization
  89958. * @param optimizer defines the current optimizer
  89959. * @returns true if everything that can be done was applied
  89960. */
  89961. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  89962. if (this._currentScale === -1) {
  89963. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  89964. if (this._currentScale > this.maximumScale) {
  89965. this._directionOffset = -1;
  89966. }
  89967. }
  89968. this._currentScale += this._directionOffset * this.step;
  89969. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  89970. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  89971. };
  89972. ;
  89973. return HardwareScalingOptimization;
  89974. }(SceneOptimization));
  89975. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  89976. /**
  89977. * Defines an optimization used to remove shadows
  89978. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89979. */
  89980. var ShadowsOptimization = /** @class */ (function (_super) {
  89981. __extends(ShadowsOptimization, _super);
  89982. function ShadowsOptimization() {
  89983. return _super !== null && _super.apply(this, arguments) || this;
  89984. }
  89985. /**
  89986. * Gets a string describing the action executed by the current optimization
  89987. * @return description string
  89988. */
  89989. ShadowsOptimization.prototype.getDescription = function () {
  89990. return "Turning shadows on/off";
  89991. };
  89992. /**
  89993. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89994. * @param scene defines the current scene where to apply this optimization
  89995. * @param optimizer defines the current optimizer
  89996. * @returns true if everything that can be done was applied
  89997. */
  89998. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  89999. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90000. return true;
  90001. };
  90002. ;
  90003. return ShadowsOptimization;
  90004. }(SceneOptimization));
  90005. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90006. /**
  90007. * Defines an optimization used to turn post-processes off
  90008. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90009. */
  90010. var PostProcessesOptimization = /** @class */ (function (_super) {
  90011. __extends(PostProcessesOptimization, _super);
  90012. function PostProcessesOptimization() {
  90013. return _super !== null && _super.apply(this, arguments) || this;
  90014. }
  90015. /**
  90016. * Gets a string describing the action executed by the current optimization
  90017. * @return description string
  90018. */
  90019. PostProcessesOptimization.prototype.getDescription = function () {
  90020. return "Turning post-processes on/off";
  90021. };
  90022. /**
  90023. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90024. * @param scene defines the current scene where to apply this optimization
  90025. * @param optimizer defines the current optimizer
  90026. * @returns true if everything that can be done was applied
  90027. */
  90028. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90029. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90030. return true;
  90031. };
  90032. ;
  90033. return PostProcessesOptimization;
  90034. }(SceneOptimization));
  90035. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90036. /**
  90037. * Defines an optimization used to turn lens flares off
  90038. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90039. */
  90040. var LensFlaresOptimization = /** @class */ (function (_super) {
  90041. __extends(LensFlaresOptimization, _super);
  90042. function LensFlaresOptimization() {
  90043. return _super !== null && _super.apply(this, arguments) || this;
  90044. }
  90045. /**
  90046. * Gets a string describing the action executed by the current optimization
  90047. * @return description string
  90048. */
  90049. LensFlaresOptimization.prototype.getDescription = function () {
  90050. return "Turning lens flares on/off";
  90051. };
  90052. /**
  90053. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90054. * @param scene defines the current scene where to apply this optimization
  90055. * @param optimizer defines the current optimizer
  90056. * @returns true if everything that can be done was applied
  90057. */
  90058. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90059. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90060. return true;
  90061. };
  90062. ;
  90063. return LensFlaresOptimization;
  90064. }(SceneOptimization));
  90065. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90066. /**
  90067. * Defines an optimization based on user defined callback.
  90068. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90069. */
  90070. var CustomOptimization = /** @class */ (function (_super) {
  90071. __extends(CustomOptimization, _super);
  90072. function CustomOptimization() {
  90073. return _super !== null && _super.apply(this, arguments) || this;
  90074. }
  90075. /**
  90076. * Gets a string describing the action executed by the current optimization
  90077. * @returns description string
  90078. */
  90079. CustomOptimization.prototype.getDescription = function () {
  90080. if (this.onGetDescription) {
  90081. return this.onGetDescription();
  90082. }
  90083. return "Running user defined callback";
  90084. };
  90085. /**
  90086. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90087. * @param scene defines the current scene where to apply this optimization
  90088. * @param optimizer defines the current optimizer
  90089. * @returns true if everything that can be done was applied
  90090. */
  90091. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90092. if (this.onApply) {
  90093. return this.onApply(scene, optimizer);
  90094. }
  90095. return true;
  90096. };
  90097. ;
  90098. return CustomOptimization;
  90099. }(SceneOptimization));
  90100. BABYLON.CustomOptimization = CustomOptimization;
  90101. /**
  90102. * Defines an optimization used to turn particles off
  90103. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90104. */
  90105. var ParticlesOptimization = /** @class */ (function (_super) {
  90106. __extends(ParticlesOptimization, _super);
  90107. function ParticlesOptimization() {
  90108. return _super !== null && _super.apply(this, arguments) || this;
  90109. }
  90110. /**
  90111. * Gets a string describing the action executed by the current optimization
  90112. * @return description string
  90113. */
  90114. ParticlesOptimization.prototype.getDescription = function () {
  90115. return "Turning particles on/off";
  90116. };
  90117. /**
  90118. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90119. * @param scene defines the current scene where to apply this optimization
  90120. * @param optimizer defines the current optimizer
  90121. * @returns true if everything that can be done was applied
  90122. */
  90123. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90124. scene.particlesEnabled = optimizer.isInImprovementMode;
  90125. return true;
  90126. };
  90127. ;
  90128. return ParticlesOptimization;
  90129. }(SceneOptimization));
  90130. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90131. /**
  90132. * Defines an optimization used to turn render targets off
  90133. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90134. */
  90135. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90136. __extends(RenderTargetsOptimization, _super);
  90137. function RenderTargetsOptimization() {
  90138. return _super !== null && _super.apply(this, arguments) || this;
  90139. }
  90140. /**
  90141. * Gets a string describing the action executed by the current optimization
  90142. * @return description string
  90143. */
  90144. RenderTargetsOptimization.prototype.getDescription = function () {
  90145. return "Turning render targets off";
  90146. };
  90147. /**
  90148. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90149. * @param scene defines the current scene where to apply this optimization
  90150. * @param optimizer defines the current optimizer
  90151. * @returns true if everything that can be done was applied
  90152. */
  90153. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90154. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90155. return true;
  90156. };
  90157. ;
  90158. return RenderTargetsOptimization;
  90159. }(SceneOptimization));
  90160. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90161. /**
  90162. * Defines an optimization used to merge meshes with compatible materials
  90163. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90164. */
  90165. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90166. __extends(MergeMeshesOptimization, _super);
  90167. function MergeMeshesOptimization() {
  90168. var _this = _super !== null && _super.apply(this, arguments) || this;
  90169. _this._canBeMerged = function (abstractMesh) {
  90170. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90171. return false;
  90172. }
  90173. var mesh = abstractMesh;
  90174. if (!mesh.isVisible || !mesh.isEnabled()) {
  90175. return false;
  90176. }
  90177. if (mesh.instances.length > 0) {
  90178. return false;
  90179. }
  90180. if (mesh.skeleton || mesh.hasLODLevels) {
  90181. return false;
  90182. }
  90183. if (mesh.parent) {
  90184. return false;
  90185. }
  90186. return true;
  90187. };
  90188. return _this;
  90189. }
  90190. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90191. /**
  90192. * Gets or sets a boolean which defines if optimization octree has to be updated
  90193. */
  90194. get: function () {
  90195. return MergeMeshesOptimization._UpdateSelectionTree;
  90196. },
  90197. /**
  90198. * Gets or sets a boolean which defines if optimization octree has to be updated
  90199. */
  90200. set: function (value) {
  90201. MergeMeshesOptimization._UpdateSelectionTree = value;
  90202. },
  90203. enumerable: true,
  90204. configurable: true
  90205. });
  90206. /**
  90207. * Gets a string describing the action executed by the current optimization
  90208. * @return description string
  90209. */
  90210. MergeMeshesOptimization.prototype.getDescription = function () {
  90211. return "Merging similar meshes together";
  90212. };
  90213. /**
  90214. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90215. * @param scene defines the current scene where to apply this optimization
  90216. * @param optimizer defines the current optimizer
  90217. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90218. * @returns true if everything that can be done was applied
  90219. */
  90220. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90221. var globalPool = scene.meshes.slice(0);
  90222. var globalLength = globalPool.length;
  90223. for (var index = 0; index < globalLength; index++) {
  90224. var currentPool = new Array();
  90225. var current = globalPool[index];
  90226. // Checks
  90227. if (!this._canBeMerged(current)) {
  90228. continue;
  90229. }
  90230. currentPool.push(current);
  90231. // Find compatible meshes
  90232. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90233. var otherMesh = globalPool[subIndex];
  90234. if (!this._canBeMerged(otherMesh)) {
  90235. continue;
  90236. }
  90237. if (otherMesh.material !== current.material) {
  90238. continue;
  90239. }
  90240. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90241. continue;
  90242. }
  90243. currentPool.push(otherMesh);
  90244. globalLength--;
  90245. globalPool.splice(subIndex, 1);
  90246. subIndex--;
  90247. }
  90248. if (currentPool.length < 2) {
  90249. continue;
  90250. }
  90251. // Merge meshes
  90252. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90253. }
  90254. if (updateSelectionTree != undefined) {
  90255. if (updateSelectionTree) {
  90256. scene.createOrUpdateSelectionOctree();
  90257. }
  90258. }
  90259. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90260. scene.createOrUpdateSelectionOctree();
  90261. }
  90262. return true;
  90263. };
  90264. ;
  90265. MergeMeshesOptimization._UpdateSelectionTree = false;
  90266. return MergeMeshesOptimization;
  90267. }(SceneOptimization));
  90268. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90269. /**
  90270. * Defines a list of options used by SceneOptimizer
  90271. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90272. */
  90273. var SceneOptimizerOptions = /** @class */ (function () {
  90274. /**
  90275. * Creates a new list of options used by SceneOptimizer
  90276. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90277. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90278. */
  90279. function SceneOptimizerOptions(
  90280. /**
  90281. * Defines the target frame rate to reach (60 by default)
  90282. */
  90283. targetFrameRate,
  90284. /**
  90285. * Defines the interval between two checkes (2000ms by default)
  90286. */
  90287. trackerDuration) {
  90288. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90289. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90290. this.targetFrameRate = targetFrameRate;
  90291. this.trackerDuration = trackerDuration;
  90292. /**
  90293. * Gets the list of optimizations to apply
  90294. */
  90295. this.optimizations = new Array();
  90296. }
  90297. /**
  90298. * Add a new optimization
  90299. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90300. * @returns the current SceneOptimizerOptions
  90301. */
  90302. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90303. this.optimizations.push(optimization);
  90304. return this;
  90305. };
  90306. /**
  90307. * Add a new custom optimization
  90308. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90309. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90310. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90311. * @returns the current SceneOptimizerOptions
  90312. */
  90313. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90314. if (priority === void 0) { priority = 0; }
  90315. var optimization = new CustomOptimization(priority);
  90316. optimization.onApply = onApply;
  90317. optimization.onGetDescription = onGetDescription;
  90318. this.optimizations.push(optimization);
  90319. return this;
  90320. };
  90321. /**
  90322. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90323. * @param targetFrameRate defines the target frame rate (60 by default)
  90324. * @returns a SceneOptimizerOptions object
  90325. */
  90326. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90327. var result = new SceneOptimizerOptions(targetFrameRate);
  90328. var priority = 0;
  90329. result.addOptimization(new MergeMeshesOptimization(priority));
  90330. result.addOptimization(new ShadowsOptimization(priority));
  90331. result.addOptimization(new LensFlaresOptimization(priority));
  90332. // Next priority
  90333. priority++;
  90334. result.addOptimization(new PostProcessesOptimization(priority));
  90335. result.addOptimization(new ParticlesOptimization(priority));
  90336. // Next priority
  90337. priority++;
  90338. result.addOptimization(new TextureOptimization(priority, 1024));
  90339. return result;
  90340. };
  90341. /**
  90342. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90343. * @param targetFrameRate defines the target frame rate (60 by default)
  90344. * @returns a SceneOptimizerOptions object
  90345. */
  90346. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90347. var result = new SceneOptimizerOptions(targetFrameRate);
  90348. var priority = 0;
  90349. result.addOptimization(new MergeMeshesOptimization(priority));
  90350. result.addOptimization(new ShadowsOptimization(priority));
  90351. result.addOptimization(new LensFlaresOptimization(priority));
  90352. // Next priority
  90353. priority++;
  90354. result.addOptimization(new PostProcessesOptimization(priority));
  90355. result.addOptimization(new ParticlesOptimization(priority));
  90356. // Next priority
  90357. priority++;
  90358. result.addOptimization(new TextureOptimization(priority, 512));
  90359. // Next priority
  90360. priority++;
  90361. result.addOptimization(new RenderTargetsOptimization(priority));
  90362. // Next priority
  90363. priority++;
  90364. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90365. return result;
  90366. };
  90367. /**
  90368. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90369. * @param targetFrameRate defines the target frame rate (60 by default)
  90370. * @returns a SceneOptimizerOptions object
  90371. */
  90372. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90373. var result = new SceneOptimizerOptions(targetFrameRate);
  90374. var priority = 0;
  90375. result.addOptimization(new MergeMeshesOptimization(priority));
  90376. result.addOptimization(new ShadowsOptimization(priority));
  90377. result.addOptimization(new LensFlaresOptimization(priority));
  90378. // Next priority
  90379. priority++;
  90380. result.addOptimization(new PostProcessesOptimization(priority));
  90381. result.addOptimization(new ParticlesOptimization(priority));
  90382. // Next priority
  90383. priority++;
  90384. result.addOptimization(new TextureOptimization(priority, 256));
  90385. // Next priority
  90386. priority++;
  90387. result.addOptimization(new RenderTargetsOptimization(priority));
  90388. // Next priority
  90389. priority++;
  90390. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90391. return result;
  90392. };
  90393. return SceneOptimizerOptions;
  90394. }());
  90395. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90396. /**
  90397. * Class used to run optimizations in order to reach a target frame rate
  90398. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90399. */
  90400. var SceneOptimizer = /** @class */ (function () {
  90401. /**
  90402. * Creates a new SceneOptimizer
  90403. * @param scene defines the scene to work on
  90404. * @param options defines the options to use with the SceneOptimizer
  90405. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90406. * @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)
  90407. */
  90408. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90409. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90410. if (improvementMode === void 0) { improvementMode = false; }
  90411. var _this = this;
  90412. this._isRunning = false;
  90413. this._currentPriorityLevel = 0;
  90414. this._targetFrameRate = 60;
  90415. this._trackerDuration = 2000;
  90416. this._currentFrameRate = 0;
  90417. this._improvementMode = false;
  90418. /**
  90419. * Defines an observable called when the optimizer reaches the target frame rate
  90420. */
  90421. this.onSuccessObservable = new BABYLON.Observable();
  90422. /**
  90423. * Defines an observable called when the optimizer enables an optimization
  90424. */
  90425. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90426. /**
  90427. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90428. */
  90429. this.onFailureObservable = new BABYLON.Observable();
  90430. if (!options) {
  90431. this._options = new SceneOptimizerOptions();
  90432. }
  90433. else {
  90434. this._options = options;
  90435. }
  90436. if (this._options.targetFrameRate) {
  90437. this._targetFrameRate = this._options.targetFrameRate;
  90438. }
  90439. if (this._options.trackerDuration) {
  90440. this._trackerDuration = this._options.trackerDuration;
  90441. }
  90442. if (autoGeneratePriorities) {
  90443. var priority = 0;
  90444. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90445. var optim = _a[_i];
  90446. optim.priority = priority++;
  90447. }
  90448. }
  90449. this._improvementMode = improvementMode;
  90450. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90451. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90452. _this._sceneDisposeObserver = null;
  90453. _this.dispose();
  90454. });
  90455. }
  90456. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90457. /**
  90458. * Gets a boolean indicating if the optimizer is in improvement mode
  90459. */
  90460. get: function () {
  90461. return this._improvementMode;
  90462. },
  90463. enumerable: true,
  90464. configurable: true
  90465. });
  90466. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90467. /**
  90468. * Gets the current priority level (0 at start)
  90469. */
  90470. get: function () {
  90471. return this._currentPriorityLevel;
  90472. },
  90473. enumerable: true,
  90474. configurable: true
  90475. });
  90476. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90477. /**
  90478. * Gets the current frame rate checked by the SceneOptimizer
  90479. */
  90480. get: function () {
  90481. return this._currentFrameRate;
  90482. },
  90483. enumerable: true,
  90484. configurable: true
  90485. });
  90486. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90487. /**
  90488. * Gets or sets the current target frame rate (60 by default)
  90489. */
  90490. get: function () {
  90491. return this._targetFrameRate;
  90492. },
  90493. /**
  90494. * Gets or sets the current target frame rate (60 by default)
  90495. */
  90496. set: function (value) {
  90497. this._targetFrameRate = value;
  90498. },
  90499. enumerable: true,
  90500. configurable: true
  90501. });
  90502. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90503. /**
  90504. * Gets or sets the current interval between two checks (every 2000ms by default)
  90505. */
  90506. get: function () {
  90507. return this._trackerDuration;
  90508. },
  90509. /**
  90510. * Gets or sets the current interval between two checks (every 2000ms by default)
  90511. */
  90512. set: function (value) {
  90513. this._trackerDuration = value;
  90514. },
  90515. enumerable: true,
  90516. configurable: true
  90517. });
  90518. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90519. /**
  90520. * Gets the list of active optimizations
  90521. */
  90522. get: function () {
  90523. return this._options.optimizations;
  90524. },
  90525. enumerable: true,
  90526. configurable: true
  90527. });
  90528. /**
  90529. * Stops the current optimizer
  90530. */
  90531. SceneOptimizer.prototype.stop = function () {
  90532. this._isRunning = false;
  90533. };
  90534. /**
  90535. * Reset the optimizer to initial step (current priority level = 0)
  90536. */
  90537. SceneOptimizer.prototype.reset = function () {
  90538. this._currentPriorityLevel = 0;
  90539. };
  90540. /**
  90541. * Start the optimizer. By default it will try to reach a specific framerate
  90542. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90543. */
  90544. SceneOptimizer.prototype.start = function () {
  90545. var _this = this;
  90546. if (this._isRunning) {
  90547. return;
  90548. }
  90549. this._isRunning = true;
  90550. // Let's wait for the scene to be ready before running our check
  90551. this._scene.executeWhenReady(function () {
  90552. setTimeout(function () {
  90553. _this._checkCurrentState();
  90554. }, _this._trackerDuration);
  90555. });
  90556. };
  90557. SceneOptimizer.prototype._checkCurrentState = function () {
  90558. var _this = this;
  90559. if (!this._isRunning) {
  90560. return;
  90561. }
  90562. var scene = this._scene;
  90563. var options = this._options;
  90564. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90565. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90566. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90567. this._isRunning = false;
  90568. this.onSuccessObservable.notifyObservers(this);
  90569. return;
  90570. }
  90571. // Apply current level of optimizations
  90572. var allDone = true;
  90573. var noOptimizationApplied = true;
  90574. for (var index = 0; index < options.optimizations.length; index++) {
  90575. var optimization = options.optimizations[index];
  90576. if (optimization.priority === this._currentPriorityLevel) {
  90577. noOptimizationApplied = false;
  90578. allDone = allDone && optimization.apply(scene, this);
  90579. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90580. }
  90581. }
  90582. // If no optimization was applied, this is a failure :(
  90583. if (noOptimizationApplied) {
  90584. this._isRunning = false;
  90585. this.onFailureObservable.notifyObservers(this);
  90586. return;
  90587. }
  90588. // If all optimizations were done, move to next level
  90589. if (allDone) {
  90590. this._currentPriorityLevel++;
  90591. }
  90592. // Let's the system running for a specific amount of time before checking FPS
  90593. scene.executeWhenReady(function () {
  90594. setTimeout(function () {
  90595. _this._checkCurrentState();
  90596. }, _this._trackerDuration);
  90597. });
  90598. };
  90599. /**
  90600. * Release all resources
  90601. */
  90602. SceneOptimizer.prototype.dispose = function () {
  90603. this.stop();
  90604. this.onSuccessObservable.clear();
  90605. this.onFailureObservable.clear();
  90606. this.onNewOptimizationAppliedObservable.clear();
  90607. if (this._sceneDisposeObserver) {
  90608. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90609. }
  90610. };
  90611. /**
  90612. * Helper function to create a SceneOptimizer with one single line of code
  90613. * @param scene defines the scene to work on
  90614. * @param options defines the options to use with the SceneOptimizer
  90615. * @param onSuccess defines a callback to call on success
  90616. * @param onFailure defines a callback to call on failure
  90617. * @returns the new SceneOptimizer object
  90618. */
  90619. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90620. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90621. if (onSuccess) {
  90622. optimizer.onSuccessObservable.add(function () {
  90623. onSuccess();
  90624. });
  90625. }
  90626. if (onFailure) {
  90627. optimizer.onFailureObservable.add(function () {
  90628. onFailure();
  90629. });
  90630. }
  90631. optimizer.start();
  90632. return optimizer;
  90633. };
  90634. return SceneOptimizer;
  90635. }());
  90636. BABYLON.SceneOptimizer = SceneOptimizer;
  90637. })(BABYLON || (BABYLON = {}));
  90638. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90639. var BABYLON;
  90640. (function (BABYLON) {
  90641. var OutlineRenderer = /** @class */ (function () {
  90642. function OutlineRenderer(scene) {
  90643. this.zOffset = 1;
  90644. this._scene = scene;
  90645. }
  90646. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90647. var _this = this;
  90648. if (useOverlay === void 0) { useOverlay = false; }
  90649. var scene = this._scene;
  90650. var engine = this._scene.getEngine();
  90651. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90652. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90653. return;
  90654. }
  90655. var mesh = subMesh.getRenderingMesh();
  90656. var material = subMesh.getMaterial();
  90657. if (!material || !scene.activeCamera) {
  90658. return;
  90659. }
  90660. engine.enableEffect(this._effect);
  90661. // Logarithmic depth
  90662. if (material.useLogarithmicDepth) {
  90663. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90664. }
  90665. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90666. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90667. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90668. // Bones
  90669. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90670. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90671. }
  90672. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90673. // Alpha test
  90674. if (material && material.needAlphaTesting()) {
  90675. var alphaTexture = material.getAlphaTestTexture();
  90676. if (alphaTexture) {
  90677. this._effect.setTexture("diffuseSampler", alphaTexture);
  90678. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90679. }
  90680. }
  90681. engine.setZOffset(-this.zOffset);
  90682. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90683. engine.setZOffset(0);
  90684. };
  90685. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90686. var defines = [];
  90687. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90688. var mesh = subMesh.getMesh();
  90689. var material = subMesh.getMaterial();
  90690. if (material) {
  90691. // Alpha test
  90692. if (material.needAlphaTesting()) {
  90693. defines.push("#define ALPHATEST");
  90694. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90695. attribs.push(BABYLON.VertexBuffer.UVKind);
  90696. defines.push("#define UV1");
  90697. }
  90698. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90699. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90700. defines.push("#define UV2");
  90701. }
  90702. }
  90703. //Logarithmic depth
  90704. if (material.useLogarithmicDepth) {
  90705. defines.push("#define LOGARITHMICDEPTH");
  90706. }
  90707. }
  90708. // Bones
  90709. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90710. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90711. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90712. if (mesh.numBoneInfluencers > 4) {
  90713. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90714. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90715. }
  90716. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90717. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90718. }
  90719. else {
  90720. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90721. }
  90722. // Instances
  90723. if (useInstances) {
  90724. defines.push("#define INSTANCES");
  90725. attribs.push("world0");
  90726. attribs.push("world1");
  90727. attribs.push("world2");
  90728. attribs.push("world3");
  90729. }
  90730. // Get correct effect
  90731. var join = defines.join("\n");
  90732. if (this._cachedDefines !== join) {
  90733. this._cachedDefines = join;
  90734. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90735. }
  90736. return this._effect.isReady();
  90737. };
  90738. return OutlineRenderer;
  90739. }());
  90740. BABYLON.OutlineRenderer = OutlineRenderer;
  90741. })(BABYLON || (BABYLON = {}));
  90742. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90743. var BABYLON;
  90744. (function (BABYLON) {
  90745. var FaceAdjacencies = /** @class */ (function () {
  90746. function FaceAdjacencies() {
  90747. this.edges = new Array();
  90748. this.edgesConnectedCount = 0;
  90749. }
  90750. return FaceAdjacencies;
  90751. }());
  90752. var EdgesRenderer = /** @class */ (function () {
  90753. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90754. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90755. if (epsilon === void 0) { epsilon = 0.95; }
  90756. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90757. this.edgesWidthScalerForOrthographic = 1000.0;
  90758. this.edgesWidthScalerForPerspective = 50.0;
  90759. this._linesPositions = new Array();
  90760. this._linesNormals = new Array();
  90761. this._linesIndices = new Array();
  90762. this._buffers = {};
  90763. this._checkVerticesInsteadOfIndices = false;
  90764. this._source = source;
  90765. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90766. this._epsilon = epsilon;
  90767. this._prepareRessources();
  90768. this._generateEdgesLines();
  90769. }
  90770. EdgesRenderer.prototype._prepareRessources = function () {
  90771. if (this._lineShader) {
  90772. return;
  90773. }
  90774. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90775. attributes: ["position", "normal"],
  90776. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90777. });
  90778. this._lineShader.disableDepthWrite = true;
  90779. this._lineShader.backFaceCulling = false;
  90780. };
  90781. EdgesRenderer.prototype._rebuild = function () {
  90782. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90783. if (buffer) {
  90784. buffer._rebuild();
  90785. }
  90786. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90787. if (buffer) {
  90788. buffer._rebuild();
  90789. }
  90790. var scene = this._source.getScene();
  90791. var engine = scene.getEngine();
  90792. this._ib = engine.createIndexBuffer(this._linesIndices);
  90793. };
  90794. EdgesRenderer.prototype.dispose = function () {
  90795. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90796. if (buffer) {
  90797. buffer.dispose();
  90798. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90799. }
  90800. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90801. if (buffer) {
  90802. buffer.dispose();
  90803. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90804. }
  90805. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90806. this._lineShader.dispose();
  90807. };
  90808. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90809. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90810. return 0;
  90811. }
  90812. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90813. return 1;
  90814. }
  90815. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90816. return 2;
  90817. }
  90818. return -1;
  90819. };
  90820. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90821. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90822. return 0;
  90823. }
  90824. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90825. return 1;
  90826. }
  90827. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90828. return 2;
  90829. }
  90830. return -1;
  90831. };
  90832. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90833. var needToCreateLine;
  90834. if (edge === undefined) {
  90835. needToCreateLine = true;
  90836. }
  90837. else {
  90838. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90839. needToCreateLine = dotProduct < this._epsilon;
  90840. }
  90841. if (needToCreateLine) {
  90842. var offset = this._linesPositions.length / 3;
  90843. var normal = p0.subtract(p1);
  90844. normal.normalize();
  90845. // Positions
  90846. this._linesPositions.push(p0.x);
  90847. this._linesPositions.push(p0.y);
  90848. this._linesPositions.push(p0.z);
  90849. this._linesPositions.push(p0.x);
  90850. this._linesPositions.push(p0.y);
  90851. this._linesPositions.push(p0.z);
  90852. this._linesPositions.push(p1.x);
  90853. this._linesPositions.push(p1.y);
  90854. this._linesPositions.push(p1.z);
  90855. this._linesPositions.push(p1.x);
  90856. this._linesPositions.push(p1.y);
  90857. this._linesPositions.push(p1.z);
  90858. // Normals
  90859. this._linesNormals.push(p1.x);
  90860. this._linesNormals.push(p1.y);
  90861. this._linesNormals.push(p1.z);
  90862. this._linesNormals.push(-1);
  90863. this._linesNormals.push(p1.x);
  90864. this._linesNormals.push(p1.y);
  90865. this._linesNormals.push(p1.z);
  90866. this._linesNormals.push(1);
  90867. this._linesNormals.push(p0.x);
  90868. this._linesNormals.push(p0.y);
  90869. this._linesNormals.push(p0.z);
  90870. this._linesNormals.push(-1);
  90871. this._linesNormals.push(p0.x);
  90872. this._linesNormals.push(p0.y);
  90873. this._linesNormals.push(p0.z);
  90874. this._linesNormals.push(1);
  90875. // Indices
  90876. this._linesIndices.push(offset);
  90877. this._linesIndices.push(offset + 1);
  90878. this._linesIndices.push(offset + 2);
  90879. this._linesIndices.push(offset);
  90880. this._linesIndices.push(offset + 2);
  90881. this._linesIndices.push(offset + 3);
  90882. }
  90883. };
  90884. EdgesRenderer.prototype._generateEdgesLines = function () {
  90885. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90886. var indices = this._source.getIndices();
  90887. if (!indices || !positions) {
  90888. return;
  90889. }
  90890. // First let's find adjacencies
  90891. var adjacencies = new Array();
  90892. var faceNormals = new Array();
  90893. var index;
  90894. var faceAdjacencies;
  90895. // Prepare faces
  90896. for (index = 0; index < indices.length; index += 3) {
  90897. faceAdjacencies = new FaceAdjacencies();
  90898. var p0Index = indices[index];
  90899. var p1Index = indices[index + 1];
  90900. var p2Index = indices[index + 2];
  90901. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  90902. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  90903. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  90904. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  90905. faceNormal.normalize();
  90906. faceNormals.push(faceNormal);
  90907. adjacencies.push(faceAdjacencies);
  90908. }
  90909. // Scan
  90910. for (index = 0; index < adjacencies.length; index++) {
  90911. faceAdjacencies = adjacencies[index];
  90912. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  90913. var otherFaceAdjacencies = adjacencies[otherIndex];
  90914. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  90915. break;
  90916. }
  90917. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  90918. continue;
  90919. }
  90920. var otherP0 = indices[otherIndex * 3];
  90921. var otherP1 = indices[otherIndex * 3 + 1];
  90922. var otherP2 = indices[otherIndex * 3 + 2];
  90923. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  90924. var otherEdgeIndex = 0;
  90925. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  90926. continue;
  90927. }
  90928. switch (edgeIndex) {
  90929. case 0:
  90930. if (this._checkVerticesInsteadOfIndices) {
  90931. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90932. }
  90933. else {
  90934. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  90935. }
  90936. break;
  90937. case 1:
  90938. if (this._checkVerticesInsteadOfIndices) {
  90939. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90940. }
  90941. else {
  90942. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  90943. }
  90944. break;
  90945. case 2:
  90946. if (this._checkVerticesInsteadOfIndices) {
  90947. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90948. }
  90949. else {
  90950. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  90951. }
  90952. break;
  90953. }
  90954. if (otherEdgeIndex === -1) {
  90955. continue;
  90956. }
  90957. faceAdjacencies.edges[edgeIndex] = otherIndex;
  90958. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  90959. faceAdjacencies.edgesConnectedCount++;
  90960. otherFaceAdjacencies.edgesConnectedCount++;
  90961. if (faceAdjacencies.edgesConnectedCount === 3) {
  90962. break;
  90963. }
  90964. }
  90965. }
  90966. }
  90967. // Create lines
  90968. for (index = 0; index < adjacencies.length; index++) {
  90969. // 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
  90970. var current = adjacencies[index];
  90971. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  90972. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  90973. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  90974. }
  90975. // Merge into a single mesh
  90976. var engine = this._source.getScene().getEngine();
  90977. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  90978. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  90979. this._ib = engine.createIndexBuffer(this._linesIndices);
  90980. this._indicesCount = this._linesIndices.length;
  90981. };
  90982. EdgesRenderer.prototype.render = function () {
  90983. var scene = this._source.getScene();
  90984. if (!this._lineShader.isReady() || !scene.activeCamera) {
  90985. return;
  90986. }
  90987. var engine = scene.getEngine();
  90988. this._lineShader._preBind();
  90989. // VBOs
  90990. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  90991. scene.resetCachedMaterial();
  90992. this._lineShader.setColor4("color", this._source.edgesColor);
  90993. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  90994. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  90995. }
  90996. else {
  90997. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  90998. }
  90999. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91000. this._lineShader.bind(this._source.getWorldMatrix());
  91001. // Draw order
  91002. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91003. this._lineShader.unbind();
  91004. engine.setDepthWrite(true);
  91005. };
  91006. return EdgesRenderer;
  91007. }());
  91008. BABYLON.EdgesRenderer = EdgesRenderer;
  91009. })(BABYLON || (BABYLON = {}));
  91010. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91011. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91012. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91013. s = arguments[i];
  91014. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91015. t[p] = s[p];
  91016. }
  91017. return t;
  91018. };
  91019. var BABYLON;
  91020. (function (BABYLON) {
  91021. /**
  91022. * The effect layer Helps adding post process effect blended with the main pass.
  91023. *
  91024. * This can be for instance use to generate glow or higlight effects on the scene.
  91025. *
  91026. * The effect layer class can not be used directly and is intented to inherited from to be
  91027. * customized per effects.
  91028. */
  91029. var EffectLayer = /** @class */ (function () {
  91030. /**
  91031. * Instantiates a new effect Layer and references it in the scene.
  91032. * @param name The name of the layer
  91033. * @param scene The scene to use the layer in
  91034. */
  91035. function EffectLayer(
  91036. /** The Friendly of the effect in the scene */
  91037. name, scene) {
  91038. this._vertexBuffers = {};
  91039. this._maxSize = 0;
  91040. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91041. this._shouldRender = true;
  91042. this._postProcesses = [];
  91043. this._textures = [];
  91044. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91045. /**
  91046. * The clear color of the texture used to generate the glow map.
  91047. */
  91048. this.neutralColor = new BABYLON.Color4();
  91049. /**
  91050. * Specifies wether the highlight layer is enabled or not.
  91051. */
  91052. this.isEnabled = true;
  91053. /**
  91054. * An event triggered when the effect layer has been disposed.
  91055. */
  91056. this.onDisposeObservable = new BABYLON.Observable();
  91057. /**
  91058. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91059. */
  91060. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91061. /**
  91062. * An event triggered when the generated texture is being merged in the scene.
  91063. */
  91064. this.onBeforeComposeObservable = new BABYLON.Observable();
  91065. /**
  91066. * An event triggered when the generated texture has been merged in the scene.
  91067. */
  91068. this.onAfterComposeObservable = new BABYLON.Observable();
  91069. /**
  91070. * An event triggered when the efffect layer changes its size.
  91071. */
  91072. this.onSizeChangedObservable = new BABYLON.Observable();
  91073. this.name = name;
  91074. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91075. this._engine = scene.getEngine();
  91076. this._maxSize = this._engine.getCaps().maxTextureSize;
  91077. this._scene.effectLayers.push(this);
  91078. // Generate Buffers
  91079. this._generateIndexBuffer();
  91080. this._genrateVertexBuffer();
  91081. }
  91082. Object.defineProperty(EffectLayer.prototype, "camera", {
  91083. /**
  91084. * Gets the camera attached to the layer.
  91085. */
  91086. get: function () {
  91087. return this._effectLayerOptions.camera;
  91088. },
  91089. enumerable: true,
  91090. configurable: true
  91091. });
  91092. /**
  91093. * Initializes the effect layer with the required options.
  91094. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91095. */
  91096. EffectLayer.prototype._init = function (options) {
  91097. // Adapt options
  91098. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91099. this._setMainTextureSize();
  91100. this._createMainTexture();
  91101. this._createTextureAndPostProcesses();
  91102. this._mergeEffect = this._createMergeEffect();
  91103. };
  91104. /**
  91105. * Generates the index buffer of the full screen quad blending to the main canvas.
  91106. */
  91107. EffectLayer.prototype._generateIndexBuffer = function () {
  91108. // Indices
  91109. var indices = [];
  91110. indices.push(0);
  91111. indices.push(1);
  91112. indices.push(2);
  91113. indices.push(0);
  91114. indices.push(2);
  91115. indices.push(3);
  91116. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91117. };
  91118. /**
  91119. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91120. */
  91121. EffectLayer.prototype._genrateVertexBuffer = function () {
  91122. // VBO
  91123. var vertices = [];
  91124. vertices.push(1, 1);
  91125. vertices.push(-1, 1);
  91126. vertices.push(-1, -1);
  91127. vertices.push(1, -1);
  91128. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91129. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91130. };
  91131. /**
  91132. * Sets the main texture desired size which is the closest power of two
  91133. * of the engine canvas size.
  91134. */
  91135. EffectLayer.prototype._setMainTextureSize = function () {
  91136. if (this._effectLayerOptions.mainTextureFixedSize) {
  91137. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91138. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91139. }
  91140. else {
  91141. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91142. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91143. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91144. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91145. }
  91146. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91147. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91148. };
  91149. /**
  91150. * Creates the main texture for the effect layer.
  91151. */
  91152. EffectLayer.prototype._createMainTexture = function () {
  91153. var _this = this;
  91154. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91155. width: this._mainTextureDesiredSize.width,
  91156. height: this._mainTextureDesiredSize.height
  91157. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91158. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91159. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91160. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91161. this._mainTexture.anisotropicFilteringLevel = 1;
  91162. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91163. this._mainTexture.renderParticles = false;
  91164. this._mainTexture.renderList = null;
  91165. this._mainTexture.ignoreCameraViewport = true;
  91166. // Custom render function
  91167. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91168. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91169. var index;
  91170. var engine = _this._scene.getEngine();
  91171. if (depthOnlySubMeshes.length) {
  91172. engine.setColorWrite(false);
  91173. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91174. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91175. }
  91176. engine.setColorWrite(true);
  91177. }
  91178. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91179. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91180. }
  91181. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91182. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91183. }
  91184. for (index = 0; index < transparentSubMeshes.length; index++) {
  91185. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91186. }
  91187. };
  91188. this._mainTexture.onClearObservable.add(function (engine) {
  91189. engine.clear(_this.neutralColor, true, true, true);
  91190. });
  91191. };
  91192. /**
  91193. * Checks for the readiness of the element composing the layer.
  91194. * @param subMesh the mesh to check for
  91195. * @param useInstances specify wether or not to use instances to render the mesh
  91196. * @param emissiveTexture the associated emissive texture used to generate the glow
  91197. * @return true if ready otherwise, false
  91198. */
  91199. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91200. var material = subMesh.getMaterial();
  91201. if (!material) {
  91202. return false;
  91203. }
  91204. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91205. return false;
  91206. }
  91207. var defines = [];
  91208. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91209. var mesh = subMesh.getMesh();
  91210. var uv1 = false;
  91211. var uv2 = false;
  91212. // Alpha test
  91213. if (material && material.needAlphaTesting()) {
  91214. var alphaTexture = material.getAlphaTestTexture();
  91215. if (alphaTexture) {
  91216. defines.push("#define ALPHATEST");
  91217. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91218. alphaTexture.coordinatesIndex === 1) {
  91219. defines.push("#define DIFFUSEUV2");
  91220. uv2 = true;
  91221. }
  91222. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91223. defines.push("#define DIFFUSEUV1");
  91224. uv1 = true;
  91225. }
  91226. }
  91227. }
  91228. // Emissive
  91229. if (emissiveTexture) {
  91230. defines.push("#define EMISSIVE");
  91231. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91232. emissiveTexture.coordinatesIndex === 1) {
  91233. defines.push("#define EMISSIVEUV2");
  91234. uv2 = true;
  91235. }
  91236. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91237. defines.push("#define EMISSIVEUV1");
  91238. uv1 = true;
  91239. }
  91240. }
  91241. if (uv1) {
  91242. attribs.push(BABYLON.VertexBuffer.UVKind);
  91243. defines.push("#define UV1");
  91244. }
  91245. if (uv2) {
  91246. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91247. defines.push("#define UV2");
  91248. }
  91249. // Bones
  91250. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91251. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91252. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91253. if (mesh.numBoneInfluencers > 4) {
  91254. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91255. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91256. }
  91257. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91258. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91259. }
  91260. else {
  91261. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91262. }
  91263. // Morph targets
  91264. var manager = mesh.morphTargetManager;
  91265. var morphInfluencers = 0;
  91266. if (manager) {
  91267. if (manager.numInfluencers > 0) {
  91268. defines.push("#define MORPHTARGETS");
  91269. morphInfluencers = manager.numInfluencers;
  91270. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91271. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91272. }
  91273. }
  91274. // Instances
  91275. if (useInstances) {
  91276. defines.push("#define INSTANCES");
  91277. attribs.push("world0");
  91278. attribs.push("world1");
  91279. attribs.push("world2");
  91280. attribs.push("world3");
  91281. }
  91282. // Get correct effect
  91283. var join = defines.join("\n");
  91284. if (this._cachedDefines !== join) {
  91285. this._cachedDefines = join;
  91286. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91287. }
  91288. return this._effectLayerMapGenerationEffect.isReady();
  91289. };
  91290. /**
  91291. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91292. */
  91293. EffectLayer.prototype.render = function () {
  91294. var currentEffect = this._mergeEffect;
  91295. // Check
  91296. if (!currentEffect.isReady())
  91297. return;
  91298. for (var i = 0; i < this._postProcesses.length; i++) {
  91299. if (!this._postProcesses[i].isReady()) {
  91300. return;
  91301. }
  91302. }
  91303. var engine = this._scene.getEngine();
  91304. this.onBeforeComposeObservable.notifyObservers(this);
  91305. // Render
  91306. engine.enableEffect(currentEffect);
  91307. engine.setState(false);
  91308. // VBOs
  91309. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91310. // Cache
  91311. var previousAlphaMode = engine.getAlphaMode();
  91312. // Go Blend.
  91313. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91314. // Blends the map on the main canvas.
  91315. this._internalRender(currentEffect);
  91316. // Restore Alpha
  91317. engine.setAlphaMode(previousAlphaMode);
  91318. this.onAfterComposeObservable.notifyObservers(this);
  91319. // Handle size changes.
  91320. var size = this._mainTexture.getSize();
  91321. this._setMainTextureSize();
  91322. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91323. // Recreate RTT and post processes on size change.
  91324. this.onSizeChangedObservable.notifyObservers(this);
  91325. this._disposeTextureAndPostProcesses();
  91326. this._createMainTexture();
  91327. this._createTextureAndPostProcesses();
  91328. }
  91329. };
  91330. /**
  91331. * Determine if a given mesh will be used in the current effect.
  91332. * @param mesh mesh to test
  91333. * @returns true if the mesh will be used
  91334. */
  91335. EffectLayer.prototype.hasMesh = function (mesh) {
  91336. return true;
  91337. };
  91338. /**
  91339. * Returns true if the layer contains information to display, otherwise false.
  91340. * @returns true if the glow layer should be rendered
  91341. */
  91342. EffectLayer.prototype.shouldRender = function () {
  91343. return this.isEnabled && this._shouldRender;
  91344. };
  91345. /**
  91346. * Returns true if the mesh should render, otherwise false.
  91347. * @param mesh The mesh to render
  91348. * @returns true if it should render otherwise false
  91349. */
  91350. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91351. return true;
  91352. };
  91353. /**
  91354. * Returns true if the mesh should render, otherwise false.
  91355. * @param mesh The mesh to render
  91356. * @returns true if it should render otherwise false
  91357. */
  91358. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91359. return true;
  91360. };
  91361. /**
  91362. * Renders the submesh passed in parameter to the generation map.
  91363. */
  91364. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91365. var _this = this;
  91366. if (!this.shouldRender()) {
  91367. return;
  91368. }
  91369. var material = subMesh.getMaterial();
  91370. var mesh = subMesh.getRenderingMesh();
  91371. var scene = this._scene;
  91372. var engine = scene.getEngine();
  91373. if (!material) {
  91374. return;
  91375. }
  91376. // Do not block in blend mode.
  91377. if (material.needAlphaBlendingForMesh(mesh)) {
  91378. return;
  91379. }
  91380. // Culling
  91381. engine.setState(material.backFaceCulling);
  91382. // Managing instances
  91383. var batch = mesh._getInstancesRenderList(subMesh._id);
  91384. if (batch.mustReturn) {
  91385. return;
  91386. }
  91387. // Early Exit per mesh
  91388. if (!this._shouldRenderMesh(mesh)) {
  91389. return;
  91390. }
  91391. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91392. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91393. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91394. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91395. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91396. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91397. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91398. // Alpha test
  91399. if (material && material.needAlphaTesting()) {
  91400. var alphaTexture = material.getAlphaTestTexture();
  91401. if (alphaTexture) {
  91402. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91403. var textureMatrix = alphaTexture.getTextureMatrix();
  91404. if (textureMatrix) {
  91405. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91406. }
  91407. }
  91408. }
  91409. // Glow emissive only
  91410. if (this._emissiveTextureAndColor.texture) {
  91411. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91412. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91413. }
  91414. // Bones
  91415. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91416. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91417. }
  91418. // Morph targets
  91419. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91420. // Draw
  91421. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91422. }
  91423. else {
  91424. // Need to reset refresh rate of the shadowMap
  91425. this._mainTexture.resetRefreshCounter();
  91426. }
  91427. };
  91428. /**
  91429. * Rebuild the required buffers.
  91430. * @hidden Internal use only.
  91431. */
  91432. EffectLayer.prototype._rebuild = function () {
  91433. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91434. if (vb) {
  91435. vb._rebuild();
  91436. }
  91437. this._generateIndexBuffer();
  91438. };
  91439. /**
  91440. * Dispose only the render target textures and post process.
  91441. */
  91442. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91443. this._mainTexture.dispose();
  91444. for (var i = 0; i < this._postProcesses.length; i++) {
  91445. if (this._postProcesses[i]) {
  91446. this._postProcesses[i].dispose();
  91447. }
  91448. }
  91449. this._postProcesses = [];
  91450. for (var i = 0; i < this._textures.length; i++) {
  91451. if (this._textures[i]) {
  91452. this._textures[i].dispose();
  91453. }
  91454. }
  91455. this._textures = [];
  91456. };
  91457. /**
  91458. * Dispose the highlight layer and free resources.
  91459. */
  91460. EffectLayer.prototype.dispose = function () {
  91461. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91462. if (vertexBuffer) {
  91463. vertexBuffer.dispose();
  91464. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91465. }
  91466. if (this._indexBuffer) {
  91467. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91468. this._indexBuffer = null;
  91469. }
  91470. // Clean textures and post processes
  91471. this._disposeTextureAndPostProcesses();
  91472. // Remove from scene
  91473. var index = this._scene.effectLayers.indexOf(this, 0);
  91474. if (index > -1) {
  91475. this._scene.effectLayers.splice(index, 1);
  91476. }
  91477. // Callback
  91478. this.onDisposeObservable.notifyObservers(this);
  91479. this.onDisposeObservable.clear();
  91480. this.onBeforeRenderMainTextureObservable.clear();
  91481. this.onBeforeComposeObservable.clear();
  91482. this.onAfterComposeObservable.clear();
  91483. this.onSizeChangedObservable.clear();
  91484. };
  91485. /**
  91486. * Gets the class name of the effect layer
  91487. * @returns the string with the class name of the effect layer
  91488. */
  91489. EffectLayer.prototype.getClassName = function () {
  91490. return "EffectLayer";
  91491. };
  91492. /**
  91493. * Creates an effect layer from parsed effect layer data
  91494. * @param parsedEffectLayer defines effect layer data
  91495. * @param scene defines the current scene
  91496. * @param rootUrl defines the root URL containing the effect layer information
  91497. * @returns a parsed effect Layer
  91498. */
  91499. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91500. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91501. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91502. };
  91503. __decorate([
  91504. BABYLON.serialize()
  91505. ], EffectLayer.prototype, "name", void 0);
  91506. __decorate([
  91507. BABYLON.serializeAsColor4()
  91508. ], EffectLayer.prototype, "neutralColor", void 0);
  91509. __decorate([
  91510. BABYLON.serialize()
  91511. ], EffectLayer.prototype, "isEnabled", void 0);
  91512. __decorate([
  91513. BABYLON.serializeAsCameraReference()
  91514. ], EffectLayer.prototype, "camera", null);
  91515. return EffectLayer;
  91516. }());
  91517. BABYLON.EffectLayer = EffectLayer;
  91518. })(BABYLON || (BABYLON = {}));
  91519. //# sourceMappingURL=babylon.effectLayer.js.map
  91520. var BABYLON;
  91521. (function (BABYLON) {
  91522. /**
  91523. * Special Glow Blur post process only blurring the alpha channel
  91524. * It enforces keeping the most luminous color in the color channel.
  91525. */
  91526. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91527. __extends(GlowBlurPostProcess, _super);
  91528. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91530. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91531. _this.direction = direction;
  91532. _this.kernel = kernel;
  91533. _this.onApplyObservable.add(function (effect) {
  91534. effect.setFloat2("screenSize", _this.width, _this.height);
  91535. effect.setVector2("direction", _this.direction);
  91536. effect.setFloat("blurWidth", _this.kernel);
  91537. });
  91538. return _this;
  91539. }
  91540. return GlowBlurPostProcess;
  91541. }(BABYLON.PostProcess));
  91542. /**
  91543. * The highlight layer Helps adding a glow effect around a mesh.
  91544. *
  91545. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91546. * glowy meshes to your scene.
  91547. *
  91548. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91549. */
  91550. var HighlightLayer = /** @class */ (function (_super) {
  91551. __extends(HighlightLayer, _super);
  91552. /**
  91553. * Instantiates a new highlight Layer and references it to the scene..
  91554. * @param name The name of the layer
  91555. * @param scene The scene to use the layer in
  91556. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91557. */
  91558. function HighlightLayer(name, scene, options) {
  91559. var _this = _super.call(this, name, scene) || this;
  91560. _this.name = name;
  91561. /**
  91562. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91563. */
  91564. _this.innerGlow = true;
  91565. /**
  91566. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91567. */
  91568. _this.outerGlow = true;
  91569. /**
  91570. * An event triggered when the highlight layer is being blurred.
  91571. */
  91572. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91573. /**
  91574. * An event triggered when the highlight layer has been blurred.
  91575. */
  91576. _this.onAfterBlurObservable = new BABYLON.Observable();
  91577. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91578. _this._meshes = {};
  91579. _this._excludedMeshes = {};
  91580. _this.neutralColor = HighlightLayer.NeutralColor;
  91581. // Warn on stencil
  91582. if (!_this._engine.isStencilEnable) {
  91583. 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 }");
  91584. }
  91585. // Adapt options
  91586. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91587. // Initialize the layer
  91588. _this._init({
  91589. alphaBlendingMode: _this._options.alphaBlendingMode,
  91590. camera: _this._options.camera,
  91591. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91592. mainTextureRatio: _this._options.mainTextureRatio
  91593. });
  91594. // Do not render as long as no meshes have been added
  91595. _this._shouldRender = false;
  91596. return _this;
  91597. }
  91598. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91599. /**
  91600. * Gets the horizontal size of the blur.
  91601. */
  91602. get: function () {
  91603. return this._horizontalBlurPostprocess.kernel;
  91604. },
  91605. /**
  91606. * Specifies the horizontal size of the blur.
  91607. */
  91608. set: function (value) {
  91609. this._horizontalBlurPostprocess.kernel = value;
  91610. },
  91611. enumerable: true,
  91612. configurable: true
  91613. });
  91614. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91615. /**
  91616. * Gets the vertical size of the blur.
  91617. */
  91618. get: function () {
  91619. return this._verticalBlurPostprocess.kernel;
  91620. },
  91621. /**
  91622. * Specifies the vertical size of the blur.
  91623. */
  91624. set: function (value) {
  91625. this._verticalBlurPostprocess.kernel = value;
  91626. },
  91627. enumerable: true,
  91628. configurable: true
  91629. });
  91630. /**
  91631. * Get the effect name of the layer.
  91632. * @return The effect name
  91633. */
  91634. HighlightLayer.prototype.getEffectName = function () {
  91635. return HighlightLayer.EffectName;
  91636. };
  91637. /**
  91638. * Create the merge effect. This is the shader use to blit the information back
  91639. * to the main canvas at the end of the scene rendering.
  91640. */
  91641. HighlightLayer.prototype._createMergeEffect = function () {
  91642. // Effect
  91643. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91644. };
  91645. /**
  91646. * Creates the render target textures and post processes used in the highlight layer.
  91647. */
  91648. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91649. var _this = this;
  91650. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91651. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91652. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91653. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91654. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91655. width: blurTextureWidth,
  91656. height: blurTextureHeight
  91657. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91658. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91659. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91660. this._blurTexture.anisotropicFilteringLevel = 16;
  91661. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91662. this._blurTexture.renderParticles = false;
  91663. this._blurTexture.ignoreCameraViewport = true;
  91664. this._textures = [this._blurTexture];
  91665. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91666. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91667. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91668. effect.setTexture("textureSampler", _this._mainTexture);
  91669. });
  91670. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91671. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91672. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91673. });
  91674. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91675. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91676. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91677. });
  91678. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91679. }
  91680. else {
  91681. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91682. width: blurTextureWidth,
  91683. height: blurTextureHeight
  91684. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91685. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91686. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91687. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91688. effect.setTexture("textureSampler", _this._mainTexture);
  91689. });
  91690. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91691. width: blurTextureWidth,
  91692. height: blurTextureHeight
  91693. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91694. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91695. }
  91696. this._mainTexture.onAfterUnbindObservable.add(function () {
  91697. _this.onBeforeBlurObservable.notifyObservers(_this);
  91698. var internalTexture = _this._blurTexture.getInternalTexture();
  91699. if (internalTexture) {
  91700. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91701. }
  91702. _this.onAfterBlurObservable.notifyObservers(_this);
  91703. });
  91704. // Prevent autoClear.
  91705. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91706. };
  91707. /**
  91708. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91709. */
  91710. HighlightLayer.prototype.needStencil = function () {
  91711. return true;
  91712. };
  91713. /**
  91714. * Checks for the readiness of the element composing the layer.
  91715. * @param subMesh the mesh to check for
  91716. * @param useInstances specify wether or not to use instances to render the mesh
  91717. * @param emissiveTexture the associated emissive texture used to generate the glow
  91718. * @return true if ready otherwise, false
  91719. */
  91720. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91721. var material = subMesh.getMaterial();
  91722. var mesh = subMesh.getRenderingMesh();
  91723. if (!material || !mesh || !this._meshes) {
  91724. return false;
  91725. }
  91726. var emissiveTexture = null;
  91727. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91728. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91729. emissiveTexture = material.emissiveTexture;
  91730. }
  91731. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91732. };
  91733. /**
  91734. * Implementation specific of rendering the generating effect on the main canvas.
  91735. * @param effect The effect used to render through
  91736. */
  91737. HighlightLayer.prototype._internalRender = function (effect) {
  91738. // Texture
  91739. effect.setTexture("textureSampler", this._blurTexture);
  91740. // Cache
  91741. var engine = this._engine;
  91742. var previousStencilBuffer = engine.getStencilBuffer();
  91743. var previousStencilFunction = engine.getStencilFunction();
  91744. var previousStencilMask = engine.getStencilMask();
  91745. var previousStencilOperationPass = engine.getStencilOperationPass();
  91746. var previousStencilOperationFail = engine.getStencilOperationFail();
  91747. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91748. var previousStencilReference = engine.getStencilFunctionReference();
  91749. // Stencil operations
  91750. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91751. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91752. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91753. // Draw order
  91754. engine.setStencilMask(0x00);
  91755. engine.setStencilBuffer(true);
  91756. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91757. // 2 passes inner outer
  91758. if (this.outerGlow) {
  91759. effect.setFloat("offset", 0);
  91760. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91761. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91762. }
  91763. if (this.innerGlow) {
  91764. effect.setFloat("offset", 1);
  91765. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91766. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91767. }
  91768. // Restore Cache
  91769. engine.setStencilFunction(previousStencilFunction);
  91770. engine.setStencilMask(previousStencilMask);
  91771. engine.setStencilBuffer(previousStencilBuffer);
  91772. engine.setStencilOperationPass(previousStencilOperationPass);
  91773. engine.setStencilOperationFail(previousStencilOperationFail);
  91774. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91775. engine.setStencilFunctionReference(previousStencilReference);
  91776. };
  91777. /**
  91778. * Returns true if the layer contains information to display, otherwise false.
  91779. */
  91780. HighlightLayer.prototype.shouldRender = function () {
  91781. if (_super.prototype.shouldRender.call(this)) {
  91782. return this._meshes ? true : false;
  91783. }
  91784. return false;
  91785. };
  91786. /**
  91787. * Returns true if the mesh should render, otherwise false.
  91788. * @param mesh The mesh to render
  91789. * @returns true if it should render otherwise false
  91790. */
  91791. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91792. // Excluded Mesh
  91793. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91794. return false;
  91795. }
  91796. ;
  91797. return true;
  91798. };
  91799. /**
  91800. * Sets the required values for both the emissive texture and and the main color.
  91801. */
  91802. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91803. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91804. if (highlightLayerMesh) {
  91805. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91806. }
  91807. else {
  91808. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91809. }
  91810. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91811. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91812. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91813. }
  91814. else {
  91815. this._emissiveTextureAndColor.texture = null;
  91816. }
  91817. };
  91818. /**
  91819. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91820. * @param mesh The mesh to exclude from the highlight layer
  91821. */
  91822. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91823. if (!this._excludedMeshes) {
  91824. return;
  91825. }
  91826. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91827. if (!meshExcluded) {
  91828. this._excludedMeshes[mesh.uniqueId] = {
  91829. mesh: mesh,
  91830. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91831. mesh.getEngine().setStencilBuffer(false);
  91832. }),
  91833. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91834. mesh.getEngine().setStencilBuffer(true);
  91835. }),
  91836. };
  91837. }
  91838. };
  91839. /**
  91840. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91841. * @param mesh The mesh to highlight
  91842. */
  91843. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91844. if (!this._excludedMeshes) {
  91845. return;
  91846. }
  91847. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91848. if (meshExcluded) {
  91849. if (meshExcluded.beforeRender) {
  91850. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91851. }
  91852. if (meshExcluded.afterRender) {
  91853. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91854. }
  91855. }
  91856. this._excludedMeshes[mesh.uniqueId] = null;
  91857. };
  91858. /**
  91859. * Determine if a given mesh will be highlighted by the current HighlightLayer
  91860. * @param mesh mesh to test
  91861. * @returns true if the mesh will be highlighted by the current HighlightLayer
  91862. */
  91863. HighlightLayer.prototype.hasMesh = function (mesh) {
  91864. if (!this._meshes) {
  91865. return false;
  91866. }
  91867. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  91868. };
  91869. /**
  91870. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  91871. * @param mesh The mesh to highlight
  91872. * @param color The color of the highlight
  91873. * @param glowEmissiveOnly Extract the glow from the emissive texture
  91874. */
  91875. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  91876. var _this = this;
  91877. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  91878. if (!this._meshes) {
  91879. return;
  91880. }
  91881. var meshHighlight = this._meshes[mesh.uniqueId];
  91882. if (meshHighlight) {
  91883. meshHighlight.color = color;
  91884. }
  91885. else {
  91886. this._meshes[mesh.uniqueId] = {
  91887. mesh: mesh,
  91888. color: color,
  91889. // Lambda required for capture due to Observable this context
  91890. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  91891. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  91892. _this._defaultStencilReference(mesh);
  91893. }
  91894. else {
  91895. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  91896. }
  91897. }),
  91898. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  91899. glowEmissiveOnly: glowEmissiveOnly
  91900. };
  91901. }
  91902. this._shouldRender = true;
  91903. };
  91904. /**
  91905. * Remove a mesh from the highlight layer in order to make it stop glowing.
  91906. * @param mesh The mesh to highlight
  91907. */
  91908. HighlightLayer.prototype.removeMesh = function (mesh) {
  91909. if (!this._meshes) {
  91910. return;
  91911. }
  91912. var meshHighlight = this._meshes[mesh.uniqueId];
  91913. if (meshHighlight) {
  91914. if (meshHighlight.observerHighlight) {
  91915. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91916. }
  91917. if (meshHighlight.observerDefault) {
  91918. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91919. }
  91920. delete this._meshes[mesh.uniqueId];
  91921. }
  91922. this._shouldRender = false;
  91923. for (var meshHighlightToCheck in this._meshes) {
  91924. if (this._meshes[meshHighlightToCheck]) {
  91925. this._shouldRender = true;
  91926. break;
  91927. }
  91928. }
  91929. };
  91930. /**
  91931. * Force the stencil to the normal expected value for none glowing parts
  91932. */
  91933. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  91934. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  91935. };
  91936. /**
  91937. * Free any resources and references associated to a mesh.
  91938. * Internal use
  91939. * @param mesh The mesh to free.
  91940. */
  91941. HighlightLayer.prototype._disposeMesh = function (mesh) {
  91942. this.removeMesh(mesh);
  91943. this.removeExcludedMesh(mesh);
  91944. };
  91945. /**
  91946. * Dispose the highlight layer and free resources.
  91947. */
  91948. HighlightLayer.prototype.dispose = function () {
  91949. if (this._meshes) {
  91950. // Clean mesh references
  91951. for (var id in this._meshes) {
  91952. var meshHighlight = this._meshes[id];
  91953. if (meshHighlight && meshHighlight.mesh) {
  91954. if (meshHighlight.observerHighlight) {
  91955. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91956. }
  91957. if (meshHighlight.observerDefault) {
  91958. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91959. }
  91960. }
  91961. }
  91962. this._meshes = null;
  91963. }
  91964. if (this._excludedMeshes) {
  91965. for (var id in this._excludedMeshes) {
  91966. var meshHighlight = this._excludedMeshes[id];
  91967. if (meshHighlight) {
  91968. if (meshHighlight.beforeRender) {
  91969. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  91970. }
  91971. if (meshHighlight.afterRender) {
  91972. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  91973. }
  91974. }
  91975. }
  91976. this._excludedMeshes = null;
  91977. }
  91978. _super.prototype.dispose.call(this);
  91979. };
  91980. /**
  91981. * Gets the class name of the effect layer
  91982. * @returns the string with the class name of the effect layer
  91983. */
  91984. HighlightLayer.prototype.getClassName = function () {
  91985. return "HighlightLayer";
  91986. };
  91987. /**
  91988. * Serializes this Highlight layer
  91989. * @returns a serialized Highlight layer object
  91990. */
  91991. HighlightLayer.prototype.serialize = function () {
  91992. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91993. serializationObject.customType = "BABYLON.HighlightLayer";
  91994. // Highlighted meshes
  91995. serializationObject.meshes = [];
  91996. if (this._meshes) {
  91997. for (var m in this._meshes) {
  91998. var mesh = this._meshes[m];
  91999. if (mesh) {
  92000. serializationObject.meshes.push({
  92001. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92002. color: mesh.color.asArray(),
  92003. meshId: mesh.mesh.id
  92004. });
  92005. }
  92006. }
  92007. }
  92008. // Excluded meshes
  92009. serializationObject.excludedMeshes = [];
  92010. if (this._excludedMeshes) {
  92011. for (var e in this._excludedMeshes) {
  92012. var excludedMesh = this._excludedMeshes[e];
  92013. if (excludedMesh) {
  92014. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92015. }
  92016. }
  92017. }
  92018. return serializationObject;
  92019. };
  92020. /**
  92021. * Creates a Highlight layer from parsed Highlight layer data
  92022. * @param parsedHightlightLayer defines the Highlight layer data
  92023. * @param scene defines the current scene
  92024. * @param rootUrl defines the root URL containing the Highlight layer information
  92025. * @returns a parsed Highlight layer
  92026. */
  92027. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92028. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92029. var index;
  92030. // Excluded meshes
  92031. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92032. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92033. if (mesh) {
  92034. hl.addExcludedMesh(mesh);
  92035. }
  92036. }
  92037. // Included meshes
  92038. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92039. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92040. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92041. if (mesh) {
  92042. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92043. }
  92044. }
  92045. return hl;
  92046. };
  92047. /**
  92048. * Effect Name of the highlight layer.
  92049. */
  92050. HighlightLayer.EffectName = "HighlightLayer";
  92051. /**
  92052. * The neutral color used during the preparation of the glow effect.
  92053. * This is black by default as the blend operation is a blend operation.
  92054. */
  92055. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92056. /**
  92057. * Stencil value used for glowing meshes.
  92058. */
  92059. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92060. /**
  92061. * Stencil value used for the other meshes in the scene.
  92062. */
  92063. HighlightLayer.NormalMeshStencilReference = 0x01;
  92064. __decorate([
  92065. BABYLON.serialize()
  92066. ], HighlightLayer.prototype, "innerGlow", void 0);
  92067. __decorate([
  92068. BABYLON.serialize()
  92069. ], HighlightLayer.prototype, "outerGlow", void 0);
  92070. __decorate([
  92071. BABYLON.serialize()
  92072. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92073. __decorate([
  92074. BABYLON.serialize()
  92075. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92076. __decorate([
  92077. BABYLON.serialize("options")
  92078. ], HighlightLayer.prototype, "_options", void 0);
  92079. return HighlightLayer;
  92080. }(BABYLON.EffectLayer));
  92081. BABYLON.HighlightLayer = HighlightLayer;
  92082. })(BABYLON || (BABYLON = {}));
  92083. //# sourceMappingURL=babylon.highlightLayer.js.map
  92084. var BABYLON;
  92085. (function (BABYLON) {
  92086. /**
  92087. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92088. *
  92089. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92090. * glowy meshes to your scene.
  92091. *
  92092. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92093. */
  92094. var GlowLayer = /** @class */ (function (_super) {
  92095. __extends(GlowLayer, _super);
  92096. /**
  92097. * Instantiates a new glow Layer and references it to the scene.
  92098. * @param name The name of the layer
  92099. * @param scene The scene to use the layer in
  92100. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92101. */
  92102. function GlowLayer(name, scene, options) {
  92103. var _this = _super.call(this, name, scene) || this;
  92104. _this._intensity = 1.0;
  92105. _this._includedOnlyMeshes = [];
  92106. _this._excludedMeshes = [];
  92107. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92108. // Adapt options
  92109. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92110. // Initialize the layer
  92111. _this._init({
  92112. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92113. camera: _this._options.camera,
  92114. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92115. mainTextureRatio: _this._options.mainTextureRatio
  92116. });
  92117. return _this;
  92118. }
  92119. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92120. /**
  92121. * Gets the kernel size of the blur.
  92122. */
  92123. get: function () {
  92124. return this._horizontalBlurPostprocess1.kernel;
  92125. },
  92126. /**
  92127. * Sets the kernel size of the blur.
  92128. */
  92129. set: function (value) {
  92130. this._horizontalBlurPostprocess1.kernel = value;
  92131. this._verticalBlurPostprocess1.kernel = value;
  92132. this._horizontalBlurPostprocess2.kernel = value;
  92133. this._verticalBlurPostprocess2.kernel = value;
  92134. },
  92135. enumerable: true,
  92136. configurable: true
  92137. });
  92138. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92139. /**
  92140. * Gets the glow intensity.
  92141. */
  92142. get: function () {
  92143. return this._intensity;
  92144. },
  92145. /**
  92146. * Sets the glow intensity.
  92147. */
  92148. set: function (value) {
  92149. this._intensity = value;
  92150. },
  92151. enumerable: true,
  92152. configurable: true
  92153. });
  92154. /**
  92155. * Get the effect name of the layer.
  92156. * @return The effect name
  92157. */
  92158. GlowLayer.prototype.getEffectName = function () {
  92159. return GlowLayer.EffectName;
  92160. };
  92161. /**
  92162. * Create the merge effect. This is the shader use to blit the information back
  92163. * to the main canvas at the end of the scene rendering.
  92164. */
  92165. GlowLayer.prototype._createMergeEffect = function () {
  92166. // Effect
  92167. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92168. };
  92169. /**
  92170. * Creates the render target textures and post processes used in the glow layer.
  92171. */
  92172. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92173. var _this = this;
  92174. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92175. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92176. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92177. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92178. var textureType = 0;
  92179. if (this._engine.getCaps().textureHalfFloatRender) {
  92180. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92181. }
  92182. else {
  92183. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92184. }
  92185. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92186. width: blurTextureWidth,
  92187. height: blurTextureHeight
  92188. }, this._scene, false, true, textureType);
  92189. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92190. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92191. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92192. this._blurTexture1.renderParticles = false;
  92193. this._blurTexture1.ignoreCameraViewport = true;
  92194. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92195. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92196. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92197. width: blurTextureWidth2,
  92198. height: blurTextureHeight2
  92199. }, this._scene, false, true, textureType);
  92200. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92201. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92202. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92203. this._blurTexture2.renderParticles = false;
  92204. this._blurTexture2.ignoreCameraViewport = true;
  92205. this._textures = [this._blurTexture1, this._blurTexture2];
  92206. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92207. width: blurTextureWidth,
  92208. height: blurTextureHeight
  92209. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92210. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92211. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92212. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92213. effect.setTexture("textureSampler", _this._mainTexture);
  92214. });
  92215. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92216. width: blurTextureWidth,
  92217. height: blurTextureHeight
  92218. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92219. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92220. width: blurTextureWidth2,
  92221. height: blurTextureHeight2
  92222. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92223. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92224. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92225. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92226. effect.setTexture("textureSampler", _this._blurTexture1);
  92227. });
  92228. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92229. width: blurTextureWidth2,
  92230. height: blurTextureHeight2
  92231. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92232. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92233. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92234. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92235. this._mainTexture.samples = this._options.mainTextureSamples;
  92236. this._mainTexture.onAfterUnbindObservable.add(function () {
  92237. var internalTexture = _this._blurTexture1.getInternalTexture();
  92238. if (internalTexture) {
  92239. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92240. internalTexture = _this._blurTexture2.getInternalTexture();
  92241. if (internalTexture) {
  92242. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92243. }
  92244. }
  92245. });
  92246. // Prevent autoClear.
  92247. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92248. };
  92249. /**
  92250. * Checks for the readiness of the element composing the layer.
  92251. * @param subMesh the mesh to check for
  92252. * @param useInstances specify wether or not to use instances to render the mesh
  92253. * @param emissiveTexture the associated emissive texture used to generate the glow
  92254. * @return true if ready otherwise, false
  92255. */
  92256. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92257. var material = subMesh.getMaterial();
  92258. var mesh = subMesh.getRenderingMesh();
  92259. if (!material || !mesh) {
  92260. return false;
  92261. }
  92262. var emissiveTexture = material.emissiveTexture;
  92263. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92264. };
  92265. /**
  92266. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92267. */
  92268. GlowLayer.prototype.needStencil = function () {
  92269. return false;
  92270. };
  92271. /**
  92272. * Implementation specific of rendering the generating effect on the main canvas.
  92273. * @param effect The effect used to render through
  92274. */
  92275. GlowLayer.prototype._internalRender = function (effect) {
  92276. // Texture
  92277. effect.setTexture("textureSampler", this._blurTexture1);
  92278. effect.setTexture("textureSampler2", this._blurTexture2);
  92279. effect.setFloat("offset", this._intensity);
  92280. // Cache
  92281. var engine = this._engine;
  92282. var previousStencilBuffer = engine.getStencilBuffer();
  92283. // Draw order
  92284. engine.setStencilBuffer(false);
  92285. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92286. // Draw order
  92287. engine.setStencilBuffer(previousStencilBuffer);
  92288. };
  92289. /**
  92290. * Sets the required values for both the emissive texture and and the main color.
  92291. */
  92292. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92293. var textureLevel = 1.0;
  92294. if (this.customEmissiveTextureSelector) {
  92295. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92296. }
  92297. else {
  92298. if (material) {
  92299. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92300. if (this._emissiveTextureAndColor.texture) {
  92301. textureLevel = this._emissiveTextureAndColor.texture.level;
  92302. }
  92303. }
  92304. else {
  92305. this._emissiveTextureAndColor.texture = null;
  92306. }
  92307. }
  92308. if (this.customEmissiveColorSelector) {
  92309. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92310. }
  92311. else {
  92312. if (material.emissiveColor) {
  92313. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92314. }
  92315. else {
  92316. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92317. }
  92318. }
  92319. };
  92320. /**
  92321. * Returns true if the mesh should render, otherwise false.
  92322. * @param mesh The mesh to render
  92323. * @returns true if it should render otherwise false
  92324. */
  92325. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92326. return this.hasMesh(mesh);
  92327. };
  92328. /**
  92329. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92330. * @param mesh The mesh to exclude from the glow layer
  92331. */
  92332. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92333. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92334. this._excludedMeshes.push(mesh.uniqueId);
  92335. }
  92336. };
  92337. /**
  92338. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92339. * @param mesh The mesh to remove
  92340. */
  92341. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92342. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92343. if (index !== -1) {
  92344. this._excludedMeshes.splice(index, 1);
  92345. }
  92346. };
  92347. /**
  92348. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92349. * @param mesh The mesh to include in the glow layer
  92350. */
  92351. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92352. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92353. this._includedOnlyMeshes.push(mesh.uniqueId);
  92354. }
  92355. };
  92356. /**
  92357. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92358. * @param mesh The mesh to remove
  92359. */
  92360. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92361. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92362. if (index !== -1) {
  92363. this._includedOnlyMeshes.splice(index, 1);
  92364. }
  92365. };
  92366. /**
  92367. * Determine if a given mesh will be used in the glow layer
  92368. * @param mesh The mesh to test
  92369. * @returns true if the mesh will be highlighted by the current glow layer
  92370. */
  92371. GlowLayer.prototype.hasMesh = function (mesh) {
  92372. // Included Mesh
  92373. if (this._includedOnlyMeshes.length) {
  92374. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92375. }
  92376. ;
  92377. // Excluded Mesh
  92378. if (this._excludedMeshes.length) {
  92379. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92380. }
  92381. ;
  92382. return true;
  92383. };
  92384. /**
  92385. * Free any resources and references associated to a mesh.
  92386. * Internal use
  92387. * @param mesh The mesh to free.
  92388. */
  92389. GlowLayer.prototype._disposeMesh = function (mesh) {
  92390. this.removeIncludedOnlyMesh(mesh);
  92391. this.removeExcludedMesh(mesh);
  92392. };
  92393. /**
  92394. * Gets the class name of the effect layer
  92395. * @returns the string with the class name of the effect layer
  92396. */
  92397. GlowLayer.prototype.getClassName = function () {
  92398. return "GlowLayer";
  92399. };
  92400. /**
  92401. * Serializes this glow layer
  92402. * @returns a serialized glow layer object
  92403. */
  92404. GlowLayer.prototype.serialize = function () {
  92405. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92406. serializationObject.customType = "BABYLON.GlowLayer";
  92407. var index;
  92408. // Included meshes
  92409. serializationObject.includedMeshes = [];
  92410. if (this._includedOnlyMeshes.length) {
  92411. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92412. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92413. if (mesh) {
  92414. serializationObject.includedMeshes.push(mesh.id);
  92415. }
  92416. }
  92417. }
  92418. // Excluded meshes
  92419. serializationObject.excludedMeshes = [];
  92420. if (this._excludedMeshes.length) {
  92421. for (index = 0; index < this._excludedMeshes.length; index++) {
  92422. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92423. if (mesh) {
  92424. serializationObject.excludedMeshes.push(mesh.id);
  92425. }
  92426. }
  92427. }
  92428. return serializationObject;
  92429. };
  92430. /**
  92431. * Creates a Glow Layer from parsed glow layer data
  92432. * @param parsedGlowLayer defines glow layer data
  92433. * @param scene defines the current scene
  92434. * @param rootUrl defines the root URL containing the glow layer information
  92435. * @returns a parsed Glow Layer
  92436. */
  92437. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92438. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92439. var index;
  92440. // Excluded meshes
  92441. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92442. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92443. if (mesh) {
  92444. gl.addExcludedMesh(mesh);
  92445. }
  92446. }
  92447. // Included meshes
  92448. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92449. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92450. if (mesh) {
  92451. gl.addIncludedOnlyMesh(mesh);
  92452. }
  92453. }
  92454. return gl;
  92455. };
  92456. /**
  92457. * Effect Name of the layer.
  92458. */
  92459. GlowLayer.EffectName = "GlowLayer";
  92460. /**
  92461. * The default blur kernel size used for the glow.
  92462. */
  92463. GlowLayer.DefaultBlurKernelSize = 32;
  92464. /**
  92465. * The default texture size ratio used for the glow.
  92466. */
  92467. GlowLayer.DefaultTextureRatio = 0.5;
  92468. __decorate([
  92469. BABYLON.serialize()
  92470. ], GlowLayer.prototype, "blurKernelSize", null);
  92471. __decorate([
  92472. BABYLON.serialize()
  92473. ], GlowLayer.prototype, "intensity", null);
  92474. __decorate([
  92475. BABYLON.serialize("options")
  92476. ], GlowLayer.prototype, "_options", void 0);
  92477. return GlowLayer;
  92478. }(BABYLON.EffectLayer));
  92479. BABYLON.GlowLayer = GlowLayer;
  92480. })(BABYLON || (BABYLON = {}));
  92481. //# sourceMappingURL=babylon.glowLayer.js.map
  92482. var BABYLON;
  92483. (function (BABYLON) {
  92484. /**
  92485. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92486. */
  92487. var AssetTaskState;
  92488. (function (AssetTaskState) {
  92489. /**
  92490. * Initialization
  92491. */
  92492. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92493. /**
  92494. * Running
  92495. */
  92496. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92497. /**
  92498. * Done
  92499. */
  92500. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92501. /**
  92502. * Error
  92503. */
  92504. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92505. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92506. /**
  92507. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92508. */
  92509. var AbstractAssetTask = /** @class */ (function () {
  92510. /**
  92511. * Creates a new {BABYLON.AssetsManager}
  92512. * @param name defines the name of the task
  92513. */
  92514. function AbstractAssetTask(
  92515. /**
  92516. * Task name
  92517. */ name) {
  92518. this.name = name;
  92519. this._isCompleted = false;
  92520. this._taskState = AssetTaskState.INIT;
  92521. }
  92522. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92523. /**
  92524. * Get if the task is completed
  92525. */
  92526. get: function () {
  92527. return this._isCompleted;
  92528. },
  92529. enumerable: true,
  92530. configurable: true
  92531. });
  92532. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92533. /**
  92534. * Gets the current state of the task
  92535. */
  92536. get: function () {
  92537. return this._taskState;
  92538. },
  92539. enumerable: true,
  92540. configurable: true
  92541. });
  92542. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92543. /**
  92544. * Gets the current error object (if task is in error)
  92545. */
  92546. get: function () {
  92547. return this._errorObject;
  92548. },
  92549. enumerable: true,
  92550. configurable: true
  92551. });
  92552. /**
  92553. * Internal only
  92554. * @hidden
  92555. */
  92556. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92557. if (this._errorObject) {
  92558. return;
  92559. }
  92560. this._errorObject = {
  92561. message: message,
  92562. exception: exception
  92563. };
  92564. };
  92565. /**
  92566. * Execute the current task
  92567. * @param scene defines the scene where you want your assets to be loaded
  92568. * @param onSuccess is a callback called when the task is successfully executed
  92569. * @param onError is a callback called if an error occurs
  92570. */
  92571. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92572. var _this = this;
  92573. this._taskState = AssetTaskState.RUNNING;
  92574. this.runTask(scene, function () {
  92575. _this.onDoneCallback(onSuccess, onError);
  92576. }, function (msg, exception) {
  92577. _this.onErrorCallback(onError, msg, exception);
  92578. });
  92579. };
  92580. /**
  92581. * Execute the current task
  92582. * @param scene defines the scene where you want your assets to be loaded
  92583. * @param onSuccess is a callback called when the task is successfully executed
  92584. * @param onError is a callback called if an error occurs
  92585. */
  92586. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92587. throw new Error("runTask is not implemented");
  92588. };
  92589. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92590. this._taskState = AssetTaskState.ERROR;
  92591. this._errorObject = {
  92592. message: message,
  92593. exception: exception
  92594. };
  92595. if (this.onError) {
  92596. this.onError(this, message, exception);
  92597. }
  92598. onError();
  92599. };
  92600. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92601. try {
  92602. this._taskState = AssetTaskState.DONE;
  92603. this._isCompleted = true;
  92604. if (this.onSuccess) {
  92605. this.onSuccess(this);
  92606. }
  92607. onSuccess();
  92608. }
  92609. catch (e) {
  92610. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92611. }
  92612. };
  92613. return AbstractAssetTask;
  92614. }());
  92615. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92616. /**
  92617. * Class used to share progress information about assets loading
  92618. */
  92619. var AssetsProgressEvent = /** @class */ (function () {
  92620. /**
  92621. * Creates a {BABYLON.AssetsProgressEvent}
  92622. * @param remainingCount defines the number of remaining tasks to process
  92623. * @param totalCount defines the total number of tasks
  92624. * @param task defines the task that was just processed
  92625. */
  92626. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92627. this.remainingCount = remainingCount;
  92628. this.totalCount = totalCount;
  92629. this.task = task;
  92630. }
  92631. return AssetsProgressEvent;
  92632. }());
  92633. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92634. /**
  92635. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92636. */
  92637. var MeshAssetTask = /** @class */ (function (_super) {
  92638. __extends(MeshAssetTask, _super);
  92639. /**
  92640. * Creates a new {BABYLON.MeshAssetTask}
  92641. * @param name defines the name of the task
  92642. * @param meshesNames defines the list of mesh's names you want to load
  92643. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92644. * @param sceneFilename defines the filename of the scene to load from
  92645. */
  92646. function MeshAssetTask(
  92647. /**
  92648. * Defines the name of the task
  92649. */
  92650. name,
  92651. /**
  92652. * Defines the list of mesh's names you want to load
  92653. */
  92654. meshesNames,
  92655. /**
  92656. * Defines the root url to use as a base to load your meshes and associated resources
  92657. */
  92658. rootUrl,
  92659. /**
  92660. * Defines the filename of the scene to load from
  92661. */
  92662. sceneFilename) {
  92663. var _this = _super.call(this, name) || this;
  92664. _this.name = name;
  92665. _this.meshesNames = meshesNames;
  92666. _this.rootUrl = rootUrl;
  92667. _this.sceneFilename = sceneFilename;
  92668. return _this;
  92669. }
  92670. /**
  92671. * Execute the current task
  92672. * @param scene defines the scene where you want your assets to be loaded
  92673. * @param onSuccess is a callback called when the task is successfully executed
  92674. * @param onError is a callback called if an error occurs
  92675. */
  92676. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92677. var _this = this;
  92678. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92679. _this.loadedMeshes = meshes;
  92680. _this.loadedParticleSystems = particleSystems;
  92681. _this.loadedSkeletons = skeletons;
  92682. onSuccess();
  92683. }, null, function (scene, message, exception) {
  92684. onError(message, exception);
  92685. });
  92686. };
  92687. return MeshAssetTask;
  92688. }(AbstractAssetTask));
  92689. BABYLON.MeshAssetTask = MeshAssetTask;
  92690. /**
  92691. * Define a task used by {BABYLON.AssetsManager} to load text content
  92692. */
  92693. var TextFileAssetTask = /** @class */ (function (_super) {
  92694. __extends(TextFileAssetTask, _super);
  92695. /**
  92696. * Creates a new TextFileAssetTask object
  92697. * @param name defines the name of the task
  92698. * @param url defines the location of the file to load
  92699. */
  92700. function TextFileAssetTask(
  92701. /**
  92702. * Defines the name of the task
  92703. */
  92704. name,
  92705. /**
  92706. * Defines the location of the file to load
  92707. */
  92708. url) {
  92709. var _this = _super.call(this, name) || this;
  92710. _this.name = name;
  92711. _this.url = url;
  92712. return _this;
  92713. }
  92714. /**
  92715. * Execute the current task
  92716. * @param scene defines the scene where you want your assets to be loaded
  92717. * @param onSuccess is a callback called when the task is successfully executed
  92718. * @param onError is a callback called if an error occurs
  92719. */
  92720. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92721. var _this = this;
  92722. scene._loadFile(this.url, function (data) {
  92723. _this.text = data;
  92724. onSuccess();
  92725. }, undefined, false, false, function (request, exception) {
  92726. if (request) {
  92727. onError(request.status + " " + request.statusText, exception);
  92728. }
  92729. });
  92730. };
  92731. return TextFileAssetTask;
  92732. }(AbstractAssetTask));
  92733. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92734. /**
  92735. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92736. */
  92737. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92738. __extends(BinaryFileAssetTask, _super);
  92739. /**
  92740. * Creates a new BinaryFileAssetTask object
  92741. * @param name defines the name of the new task
  92742. * @param url defines the location of the file to load
  92743. */
  92744. function BinaryFileAssetTask(
  92745. /**
  92746. * Defines the name of the task
  92747. */
  92748. name,
  92749. /**
  92750. * Defines the location of the file to load
  92751. */
  92752. url) {
  92753. var _this = _super.call(this, name) || this;
  92754. _this.name = name;
  92755. _this.url = url;
  92756. return _this;
  92757. }
  92758. /**
  92759. * Execute the current task
  92760. * @param scene defines the scene where you want your assets to be loaded
  92761. * @param onSuccess is a callback called when the task is successfully executed
  92762. * @param onError is a callback called if an error occurs
  92763. */
  92764. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92765. var _this = this;
  92766. scene._loadFile(this.url, function (data) {
  92767. _this.data = data;
  92768. onSuccess();
  92769. }, undefined, true, true, function (request, exception) {
  92770. if (request) {
  92771. onError(request.status + " " + request.statusText, exception);
  92772. }
  92773. });
  92774. };
  92775. return BinaryFileAssetTask;
  92776. }(AbstractAssetTask));
  92777. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92778. /**
  92779. * Define a task used by {BABYLON.AssetsManager} to load images
  92780. */
  92781. var ImageAssetTask = /** @class */ (function (_super) {
  92782. __extends(ImageAssetTask, _super);
  92783. /**
  92784. * Creates a new ImageAssetTask
  92785. * @param name defines the name of the task
  92786. * @param url defines the location of the image to load
  92787. */
  92788. function ImageAssetTask(
  92789. /**
  92790. * Defines the name of the task
  92791. */
  92792. name,
  92793. /**
  92794. * Defines the location of the image to load
  92795. */
  92796. url) {
  92797. var _this = _super.call(this, name) || this;
  92798. _this.name = name;
  92799. _this.url = url;
  92800. return _this;
  92801. }
  92802. /**
  92803. * Execute the current task
  92804. * @param scene defines the scene where you want your assets to be loaded
  92805. * @param onSuccess is a callback called when the task is successfully executed
  92806. * @param onError is a callback called if an error occurs
  92807. */
  92808. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92809. var _this = this;
  92810. var img = new Image();
  92811. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92812. img.onload = function () {
  92813. _this.image = img;
  92814. onSuccess();
  92815. };
  92816. img.onerror = function (err) {
  92817. onError("Error loading image", err);
  92818. };
  92819. img.src = this.url;
  92820. };
  92821. return ImageAssetTask;
  92822. }(AbstractAssetTask));
  92823. BABYLON.ImageAssetTask = ImageAssetTask;
  92824. /**
  92825. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92826. */
  92827. var TextureAssetTask = /** @class */ (function (_super) {
  92828. __extends(TextureAssetTask, _super);
  92829. /**
  92830. * Creates a new TextureAssetTask object
  92831. * @param name defines the name of the task
  92832. * @param url defines the location of the file to load
  92833. * @param noMipmap defines if mipmap should not be generated (default is false)
  92834. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92835. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92836. */
  92837. function TextureAssetTask(
  92838. /**
  92839. * Defines the name of the task
  92840. */
  92841. name,
  92842. /**
  92843. * Defines the location of the file to load
  92844. */
  92845. url,
  92846. /**
  92847. * Defines if mipmap should not be generated (default is false)
  92848. */
  92849. noMipmap,
  92850. /**
  92851. * Defines if texture must be inverted on Y axis (default is false)
  92852. */
  92853. invertY,
  92854. /**
  92855. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92856. */
  92857. samplingMode) {
  92858. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92859. var _this = _super.call(this, name) || this;
  92860. _this.name = name;
  92861. _this.url = url;
  92862. _this.noMipmap = noMipmap;
  92863. _this.invertY = invertY;
  92864. _this.samplingMode = samplingMode;
  92865. return _this;
  92866. }
  92867. /**
  92868. * Execute the current task
  92869. * @param scene defines the scene where you want your assets to be loaded
  92870. * @param onSuccess is a callback called when the task is successfully executed
  92871. * @param onError is a callback called if an error occurs
  92872. */
  92873. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92874. var onload = function () {
  92875. onSuccess();
  92876. };
  92877. var onerror = function (message, exception) {
  92878. onError(message, exception);
  92879. };
  92880. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  92881. };
  92882. return TextureAssetTask;
  92883. }(AbstractAssetTask));
  92884. BABYLON.TextureAssetTask = TextureAssetTask;
  92885. /**
  92886. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  92887. */
  92888. var CubeTextureAssetTask = /** @class */ (function (_super) {
  92889. __extends(CubeTextureAssetTask, _super);
  92890. /**
  92891. * Creates a new CubeTextureAssetTask
  92892. * @param name defines the name of the task
  92893. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92894. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92895. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92896. * @param files defines the explicit list of files (undefined by default)
  92897. */
  92898. function CubeTextureAssetTask(
  92899. /**
  92900. * Defines the name of the task
  92901. */
  92902. name,
  92903. /**
  92904. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92905. */
  92906. url,
  92907. /**
  92908. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92909. */
  92910. extensions,
  92911. /**
  92912. * Defines if mipmaps should not be generated (default is false)
  92913. */
  92914. noMipmap,
  92915. /**
  92916. * Defines the explicit list of files (undefined by default)
  92917. */
  92918. files) {
  92919. var _this = _super.call(this, name) || this;
  92920. _this.name = name;
  92921. _this.url = url;
  92922. _this.extensions = extensions;
  92923. _this.noMipmap = noMipmap;
  92924. _this.files = files;
  92925. return _this;
  92926. }
  92927. /**
  92928. * Execute the current task
  92929. * @param scene defines the scene where you want your assets to be loaded
  92930. * @param onSuccess is a callback called when the task is successfully executed
  92931. * @param onError is a callback called if an error occurs
  92932. */
  92933. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92934. var onload = function () {
  92935. onSuccess();
  92936. };
  92937. var onerror = function (message, exception) {
  92938. onError(message, exception);
  92939. };
  92940. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  92941. };
  92942. return CubeTextureAssetTask;
  92943. }(AbstractAssetTask));
  92944. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  92945. /**
  92946. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  92947. */
  92948. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  92949. __extends(HDRCubeTextureAssetTask, _super);
  92950. /**
  92951. * Creates a new HDRCubeTextureAssetTask object
  92952. * @param name defines the name of the task
  92953. * @param url defines the location of the file to load
  92954. * @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.
  92955. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92956. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92957. * @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)
  92958. * @param reserved Internal use only
  92959. */
  92960. function HDRCubeTextureAssetTask(
  92961. /**
  92962. * Defines the name of the task
  92963. */
  92964. name,
  92965. /**
  92966. * Defines the location of the file to load
  92967. */
  92968. url,
  92969. /**
  92970. * Defines the desired size (the more it increases the longer the generation will be)
  92971. */
  92972. size,
  92973. /**
  92974. * Defines if mipmaps should not be generated (default is false)
  92975. */
  92976. noMipmap,
  92977. /**
  92978. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92979. */
  92980. generateHarmonics,
  92981. /**
  92982. * 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)
  92983. */
  92984. gammaSpace,
  92985. /**
  92986. * Internal Use Only
  92987. */
  92988. reserved) {
  92989. if (noMipmap === void 0) { noMipmap = false; }
  92990. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92991. if (gammaSpace === void 0) { gammaSpace = false; }
  92992. if (reserved === void 0) { reserved = false; }
  92993. var _this = _super.call(this, name) || this;
  92994. _this.name = name;
  92995. _this.url = url;
  92996. _this.size = size;
  92997. _this.noMipmap = noMipmap;
  92998. _this.generateHarmonics = generateHarmonics;
  92999. _this.gammaSpace = gammaSpace;
  93000. _this.reserved = reserved;
  93001. return _this;
  93002. }
  93003. /**
  93004. * Execute the current task
  93005. * @param scene defines the scene where you want your assets to be loaded
  93006. * @param onSuccess is a callback called when the task is successfully executed
  93007. * @param onError is a callback called if an error occurs
  93008. */
  93009. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93010. var onload = function () {
  93011. onSuccess();
  93012. };
  93013. var onerror = function (message, exception) {
  93014. onError(message, exception);
  93015. };
  93016. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93017. };
  93018. return HDRCubeTextureAssetTask;
  93019. }(AbstractAssetTask));
  93020. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93021. /**
  93022. * This class can be used to easily import assets into a scene
  93023. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93024. */
  93025. var AssetsManager = /** @class */ (function () {
  93026. /**
  93027. * Creates a new AssetsManager
  93028. * @param scene defines the scene to work on
  93029. */
  93030. function AssetsManager(scene) {
  93031. this._isLoading = false;
  93032. this._tasks = new Array();
  93033. this._waitingTasksCount = 0;
  93034. this._totalTasksCount = 0;
  93035. /**
  93036. * Observable called when all tasks are processed
  93037. */
  93038. this.onTaskSuccessObservable = new BABYLON.Observable();
  93039. /**
  93040. * Observable called when a task had an error
  93041. */
  93042. this.onTaskErrorObservable = new BABYLON.Observable();
  93043. /**
  93044. * Observable called when a task is successful
  93045. */
  93046. this.onTasksDoneObservable = new BABYLON.Observable();
  93047. /**
  93048. * Observable called when a task is done (whatever the result is)
  93049. */
  93050. this.onProgressObservable = new BABYLON.Observable();
  93051. /**
  93052. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93053. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93054. */
  93055. this.useDefaultLoadingScreen = true;
  93056. this._scene = scene;
  93057. }
  93058. /**
  93059. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93060. * @param taskName defines the name of the new task
  93061. * @param meshesNames defines the name of meshes to load
  93062. * @param rootUrl defines the root url to use to locate files
  93063. * @param sceneFilename defines the filename of the scene file
  93064. * @returns a new {BABYLON.MeshAssetTask} object
  93065. */
  93066. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93067. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93068. this._tasks.push(task);
  93069. return task;
  93070. };
  93071. /**
  93072. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93073. * @param taskName defines the name of the new task
  93074. * @param url defines the url of the file to load
  93075. * @returns a new {BABYLON.TextFileAssetTask} object
  93076. */
  93077. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93078. var task = new TextFileAssetTask(taskName, url);
  93079. this._tasks.push(task);
  93080. return task;
  93081. };
  93082. /**
  93083. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93084. * @param taskName defines the name of the new task
  93085. * @param url defines the url of the file to load
  93086. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93087. */
  93088. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93089. var task = new BinaryFileAssetTask(taskName, url);
  93090. this._tasks.push(task);
  93091. return task;
  93092. };
  93093. /**
  93094. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93095. * @param taskName defines the name of the new task
  93096. * @param url defines the url of the file to load
  93097. * @returns a new {BABYLON.ImageAssetTask} object
  93098. */
  93099. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93100. var task = new ImageAssetTask(taskName, url);
  93101. this._tasks.push(task);
  93102. return task;
  93103. };
  93104. /**
  93105. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93106. * @param taskName defines the name of the new task
  93107. * @param url defines the url of the file to load
  93108. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93109. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93110. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93111. * @returns a new {BABYLON.TextureAssetTask} object
  93112. */
  93113. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93115. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93116. this._tasks.push(task);
  93117. return task;
  93118. };
  93119. /**
  93120. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93121. * @param taskName defines the name of the new task
  93122. * @param url defines the url of the file to load
  93123. * @param extensions defines the extension to use to load the cube map (can be null)
  93124. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93125. * @param files defines the list of files to load (can be null)
  93126. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93127. */
  93128. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93129. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93130. this._tasks.push(task);
  93131. return task;
  93132. };
  93133. /**
  93134. *
  93135. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93136. * @param taskName defines the name of the new task
  93137. * @param url defines the url of the file to load
  93138. * @param size defines the size you want for the cubemap (can be null)
  93139. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93140. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93141. * @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)
  93142. * @param reserved Internal use only
  93143. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93144. */
  93145. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93146. if (noMipmap === void 0) { noMipmap = false; }
  93147. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93148. if (gammaSpace === void 0) { gammaSpace = false; }
  93149. if (reserved === void 0) { reserved = false; }
  93150. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93151. this._tasks.push(task);
  93152. return task;
  93153. };
  93154. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93155. var _this = this;
  93156. this._waitingTasksCount--;
  93157. try {
  93158. if (task.taskState === AssetTaskState.DONE) {
  93159. // Let's remove successfull tasks
  93160. BABYLON.Tools.SetImmediate(function () {
  93161. var index = _this._tasks.indexOf(task);
  93162. if (index > -1) {
  93163. _this._tasks.splice(index, 1);
  93164. }
  93165. });
  93166. }
  93167. if (this.onProgress) {
  93168. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93169. }
  93170. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93171. }
  93172. catch (e) {
  93173. BABYLON.Tools.Error("Error running progress callbacks.");
  93174. console.log(e);
  93175. }
  93176. if (this._waitingTasksCount === 0) {
  93177. try {
  93178. if (this.onFinish) {
  93179. this.onFinish(this._tasks);
  93180. }
  93181. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93182. }
  93183. catch (e) {
  93184. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93185. console.log(e);
  93186. }
  93187. this._isLoading = false;
  93188. this._scene.getEngine().hideLoadingUI();
  93189. }
  93190. };
  93191. AssetsManager.prototype._runTask = function (task) {
  93192. var _this = this;
  93193. var done = function () {
  93194. try {
  93195. if (_this.onTaskSuccess) {
  93196. _this.onTaskSuccess(task);
  93197. }
  93198. _this.onTaskSuccessObservable.notifyObservers(task);
  93199. _this._decreaseWaitingTasksCount(task);
  93200. }
  93201. catch (e) {
  93202. error("Error executing task success callbacks", e);
  93203. }
  93204. };
  93205. var error = function (message, exception) {
  93206. task._setErrorObject(message, exception);
  93207. if (_this.onTaskError) {
  93208. _this.onTaskError(task);
  93209. }
  93210. _this.onTaskErrorObservable.notifyObservers(task);
  93211. _this._decreaseWaitingTasksCount(task);
  93212. };
  93213. task.run(this._scene, done, error);
  93214. };
  93215. /**
  93216. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93217. * @return the current instance of the {BABYLON.AssetsManager}
  93218. */
  93219. AssetsManager.prototype.reset = function () {
  93220. this._isLoading = false;
  93221. this._tasks = new Array();
  93222. return this;
  93223. };
  93224. /**
  93225. * Start the loading process
  93226. * @return the current instance of the {BABYLON.AssetsManager}
  93227. */
  93228. AssetsManager.prototype.load = function () {
  93229. if (this._isLoading) {
  93230. return this;
  93231. }
  93232. this._isLoading = true;
  93233. this._waitingTasksCount = this._tasks.length;
  93234. this._totalTasksCount = this._tasks.length;
  93235. if (this._waitingTasksCount === 0) {
  93236. this._isLoading = false;
  93237. if (this.onFinish) {
  93238. this.onFinish(this._tasks);
  93239. }
  93240. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93241. return this;
  93242. }
  93243. if (this.useDefaultLoadingScreen) {
  93244. this._scene.getEngine().displayLoadingUI();
  93245. }
  93246. for (var index = 0; index < this._tasks.length; index++) {
  93247. var task = this._tasks[index];
  93248. this._runTask(task);
  93249. }
  93250. return this;
  93251. };
  93252. return AssetsManager;
  93253. }());
  93254. BABYLON.AssetsManager = AssetsManager;
  93255. })(BABYLON || (BABYLON = {}));
  93256. //# sourceMappingURL=babylon.assetsManager.js.map
  93257. var BABYLON;
  93258. (function (BABYLON) {
  93259. var serializedGeometries = [];
  93260. var serializeGeometry = function (geometry, serializationGeometries) {
  93261. if (serializedGeometries[geometry.id]) {
  93262. return;
  93263. }
  93264. if (geometry.doNotSerialize) {
  93265. return;
  93266. }
  93267. if (geometry instanceof BABYLON.BoxGeometry) {
  93268. serializationGeometries.boxes.push(geometry.serialize());
  93269. }
  93270. else if (geometry instanceof BABYLON.SphereGeometry) {
  93271. serializationGeometries.spheres.push(geometry.serialize());
  93272. }
  93273. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93274. serializationGeometries.cylinders.push(geometry.serialize());
  93275. }
  93276. else if (geometry instanceof BABYLON.TorusGeometry) {
  93277. serializationGeometries.toruses.push(geometry.serialize());
  93278. }
  93279. else if (geometry instanceof BABYLON.GroundGeometry) {
  93280. serializationGeometries.grounds.push(geometry.serialize());
  93281. }
  93282. else if (geometry instanceof BABYLON.Plane) {
  93283. serializationGeometries.planes.push(geometry.serialize());
  93284. }
  93285. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93286. serializationGeometries.torusKnots.push(geometry.serialize());
  93287. }
  93288. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93289. throw new Error("Unknown primitive type");
  93290. }
  93291. else {
  93292. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93293. }
  93294. serializedGeometries[geometry.id] = true;
  93295. };
  93296. var serializeMesh = function (mesh, serializationScene) {
  93297. var serializationObject = {};
  93298. // Geometry
  93299. var geometry = mesh._geometry;
  93300. if (geometry) {
  93301. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93302. // 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
  93303. serializeGeometry(geometry, serializationScene.geometries);
  93304. }
  93305. }
  93306. // Custom
  93307. if (mesh.serialize) {
  93308. mesh.serialize(serializationObject);
  93309. }
  93310. return serializationObject;
  93311. };
  93312. var finalizeSingleMesh = function (mesh, serializationObject) {
  93313. //only works if the mesh is already loaded
  93314. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93315. //serialize material
  93316. if (mesh.material) {
  93317. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93318. serializationObject.materials = serializationObject.materials || [];
  93319. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93320. serializationObject.materials.push(mesh.material.serialize());
  93321. }
  93322. }
  93323. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93324. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93325. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93326. serializationObject.multiMaterials.push(mesh.material.serialize());
  93327. }
  93328. }
  93329. }
  93330. //serialize geometry
  93331. var geometry = mesh._geometry;
  93332. if (geometry) {
  93333. if (!serializationObject.geometries) {
  93334. serializationObject.geometries = {};
  93335. serializationObject.geometries.boxes = [];
  93336. serializationObject.geometries.spheres = [];
  93337. serializationObject.geometries.cylinders = [];
  93338. serializationObject.geometries.toruses = [];
  93339. serializationObject.geometries.grounds = [];
  93340. serializationObject.geometries.planes = [];
  93341. serializationObject.geometries.torusKnots = [];
  93342. serializationObject.geometries.vertexData = [];
  93343. }
  93344. serializeGeometry(geometry, serializationObject.geometries);
  93345. }
  93346. // Skeletons
  93347. if (mesh.skeleton) {
  93348. serializationObject.skeletons = serializationObject.skeletons || [];
  93349. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93350. }
  93351. //serialize the actual mesh
  93352. serializationObject.meshes = serializationObject.meshes || [];
  93353. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93354. }
  93355. };
  93356. var SceneSerializer = /** @class */ (function () {
  93357. function SceneSerializer() {
  93358. }
  93359. SceneSerializer.ClearCache = function () {
  93360. serializedGeometries = [];
  93361. };
  93362. SceneSerializer.Serialize = function (scene) {
  93363. var serializationObject = {};
  93364. SceneSerializer.ClearCache();
  93365. // Scene
  93366. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93367. serializationObject.autoClear = scene.autoClear;
  93368. serializationObject.clearColor = scene.clearColor.asArray();
  93369. serializationObject.ambientColor = scene.ambientColor.asArray();
  93370. serializationObject.gravity = scene.gravity.asArray();
  93371. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93372. serializationObject.workerCollisions = scene.workerCollisions;
  93373. // Fog
  93374. if (scene.fogMode && scene.fogMode !== 0) {
  93375. serializationObject.fogMode = scene.fogMode;
  93376. serializationObject.fogColor = scene.fogColor.asArray();
  93377. serializationObject.fogStart = scene.fogStart;
  93378. serializationObject.fogEnd = scene.fogEnd;
  93379. serializationObject.fogDensity = scene.fogDensity;
  93380. }
  93381. //Physics
  93382. if (scene.isPhysicsEnabled()) {
  93383. var physicEngine = scene.getPhysicsEngine();
  93384. if (physicEngine) {
  93385. serializationObject.physicsEnabled = true;
  93386. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93387. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93388. }
  93389. }
  93390. // Metadata
  93391. if (scene.metadata) {
  93392. serializationObject.metadata = scene.metadata;
  93393. }
  93394. // Morph targets
  93395. serializationObject.morphTargetManagers = [];
  93396. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93397. var abstractMesh = _a[_i];
  93398. var manager = abstractMesh.morphTargetManager;
  93399. if (manager) {
  93400. serializationObject.morphTargetManagers.push(manager.serialize());
  93401. }
  93402. }
  93403. // Lights
  93404. serializationObject.lights = [];
  93405. var index;
  93406. var light;
  93407. for (index = 0; index < scene.lights.length; index++) {
  93408. light = scene.lights[index];
  93409. if (!light.doNotSerialize) {
  93410. serializationObject.lights.push(light.serialize());
  93411. }
  93412. }
  93413. // Cameras
  93414. serializationObject.cameras = [];
  93415. for (index = 0; index < scene.cameras.length; index++) {
  93416. var camera = scene.cameras[index];
  93417. if (!camera.doNotSerialize) {
  93418. serializationObject.cameras.push(camera.serialize());
  93419. }
  93420. }
  93421. if (scene.activeCamera) {
  93422. serializationObject.activeCameraID = scene.activeCamera.id;
  93423. }
  93424. // Animations
  93425. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93426. // Materials
  93427. serializationObject.materials = [];
  93428. serializationObject.multiMaterials = [];
  93429. var material;
  93430. for (index = 0; index < scene.materials.length; index++) {
  93431. material = scene.materials[index];
  93432. if (!material.doNotSerialize) {
  93433. serializationObject.materials.push(material.serialize());
  93434. }
  93435. }
  93436. // MultiMaterials
  93437. serializationObject.multiMaterials = [];
  93438. for (index = 0; index < scene.multiMaterials.length; index++) {
  93439. var multiMaterial = scene.multiMaterials[index];
  93440. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93441. }
  93442. // Environment texture
  93443. if (scene.environmentTexture) {
  93444. serializationObject.environmentTexture = scene.environmentTexture.name;
  93445. }
  93446. // Skeletons
  93447. serializationObject.skeletons = [];
  93448. for (index = 0; index < scene.skeletons.length; index++) {
  93449. var skeleton = scene.skeletons[index];
  93450. if (!skeleton.doNotSerialize) {
  93451. serializationObject.skeletons.push(skeleton.serialize());
  93452. }
  93453. }
  93454. // Transform nodes
  93455. serializationObject.transformNodes = [];
  93456. for (index = 0; index < scene.transformNodes.length; index++) {
  93457. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93458. }
  93459. // Geometries
  93460. serializationObject.geometries = {};
  93461. serializationObject.geometries.boxes = [];
  93462. serializationObject.geometries.spheres = [];
  93463. serializationObject.geometries.cylinders = [];
  93464. serializationObject.geometries.toruses = [];
  93465. serializationObject.geometries.grounds = [];
  93466. serializationObject.geometries.planes = [];
  93467. serializationObject.geometries.torusKnots = [];
  93468. serializationObject.geometries.vertexData = [];
  93469. serializedGeometries = [];
  93470. var geometries = scene.getGeometries();
  93471. for (index = 0; index < geometries.length; index++) {
  93472. var geometry = geometries[index];
  93473. if (geometry.isReady()) {
  93474. serializeGeometry(geometry, serializationObject.geometries);
  93475. }
  93476. }
  93477. // Meshes
  93478. serializationObject.meshes = [];
  93479. for (index = 0; index < scene.meshes.length; index++) {
  93480. var abstractMesh = scene.meshes[index];
  93481. if (abstractMesh instanceof BABYLON.Mesh) {
  93482. var mesh = abstractMesh;
  93483. if (!mesh.doNotSerialize) {
  93484. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93485. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93486. }
  93487. }
  93488. }
  93489. }
  93490. // Particles Systems
  93491. serializationObject.particleSystems = [];
  93492. for (index = 0; index < scene.particleSystems.length; index++) {
  93493. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93494. }
  93495. // Lens flares
  93496. serializationObject.lensFlareSystems = [];
  93497. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93498. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93499. }
  93500. // Shadows
  93501. serializationObject.shadowGenerators = [];
  93502. for (index = 0; index < scene.lights.length; index++) {
  93503. light = scene.lights[index];
  93504. var shadowGenerator = light.getShadowGenerator();
  93505. if (shadowGenerator) {
  93506. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93507. }
  93508. }
  93509. // Action Manager
  93510. if (scene.actionManager) {
  93511. serializationObject.actions = scene.actionManager.serialize("scene");
  93512. }
  93513. // Audio
  93514. serializationObject.sounds = [];
  93515. for (index = 0; index < scene.soundTracks.length; index++) {
  93516. var soundtrack = scene.soundTracks[index];
  93517. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93518. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93519. }
  93520. }
  93521. // Effect layers
  93522. serializationObject.effectLayers = [];
  93523. for (index = 0; index < scene.effectLayers.length; index++) {
  93524. var layer = scene.effectLayers[index];
  93525. if (layer.serialize) {
  93526. serializationObject.effectLayers.push(layer.serialize());
  93527. }
  93528. }
  93529. return serializationObject;
  93530. };
  93531. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93532. if (withParents === void 0) { withParents = false; }
  93533. if (withChildren === void 0) { withChildren = false; }
  93534. var serializationObject = {};
  93535. SceneSerializer.ClearCache();
  93536. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93537. if (withParents || withChildren) {
  93538. //deliberate for loop! not for each, appended should be processed as well.
  93539. for (var i = 0; i < toSerialize.length; ++i) {
  93540. if (withChildren) {
  93541. toSerialize[i].getDescendants().forEach(function (node) {
  93542. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93543. toSerialize.push(node);
  93544. }
  93545. });
  93546. }
  93547. //make sure the array doesn't contain the object already
  93548. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93549. toSerialize.push(toSerialize[i].parent);
  93550. }
  93551. }
  93552. }
  93553. toSerialize.forEach(function (mesh) {
  93554. finalizeSingleMesh(mesh, serializationObject);
  93555. });
  93556. return serializationObject;
  93557. };
  93558. return SceneSerializer;
  93559. }());
  93560. BABYLON.SceneSerializer = SceneSerializer;
  93561. })(BABYLON || (BABYLON = {}));
  93562. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93563. var BABYLON;
  93564. (function (BABYLON) {
  93565. var ReflectionProbe = /** @class */ (function () {
  93566. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93567. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93568. var _this = this;
  93569. this.name = name;
  93570. this._viewMatrix = BABYLON.Matrix.Identity();
  93571. this._target = BABYLON.Vector3.Zero();
  93572. this._add = BABYLON.Vector3.Zero();
  93573. this._invertYAxis = false;
  93574. this.position = BABYLON.Vector3.Zero();
  93575. this._scene = scene;
  93576. this._scene.reflectionProbes.push(this);
  93577. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93578. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93579. switch (faceIndex) {
  93580. case 0:
  93581. _this._add.copyFromFloats(1, 0, 0);
  93582. break;
  93583. case 1:
  93584. _this._add.copyFromFloats(-1, 0, 0);
  93585. break;
  93586. case 2:
  93587. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93588. break;
  93589. case 3:
  93590. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93591. break;
  93592. case 4:
  93593. _this._add.copyFromFloats(0, 0, 1);
  93594. break;
  93595. case 5:
  93596. _this._add.copyFromFloats(0, 0, -1);
  93597. break;
  93598. }
  93599. if (_this._attachedMesh) {
  93600. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93601. }
  93602. _this.position.addToRef(_this._add, _this._target);
  93603. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93604. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93605. scene._forcedViewPosition = _this.position;
  93606. });
  93607. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93608. scene._forcedViewPosition = null;
  93609. scene.updateTransformMatrix(true);
  93610. });
  93611. if (scene.activeCamera) {
  93612. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93613. }
  93614. }
  93615. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93616. get: function () {
  93617. return this._renderTargetTexture.samples;
  93618. },
  93619. set: function (value) {
  93620. this._renderTargetTexture.samples = value;
  93621. },
  93622. enumerable: true,
  93623. configurable: true
  93624. });
  93625. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93626. get: function () {
  93627. return this._renderTargetTexture.refreshRate;
  93628. },
  93629. set: function (value) {
  93630. this._renderTargetTexture.refreshRate = value;
  93631. },
  93632. enumerable: true,
  93633. configurable: true
  93634. });
  93635. ReflectionProbe.prototype.getScene = function () {
  93636. return this._scene;
  93637. };
  93638. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93639. get: function () {
  93640. return this._renderTargetTexture;
  93641. },
  93642. enumerable: true,
  93643. configurable: true
  93644. });
  93645. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93646. get: function () {
  93647. return this._renderTargetTexture.renderList;
  93648. },
  93649. enumerable: true,
  93650. configurable: true
  93651. });
  93652. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93653. this._attachedMesh = mesh;
  93654. };
  93655. /**
  93656. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93657. *
  93658. * @param renderingGroupId The rendering group id corresponding to its index
  93659. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93660. */
  93661. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93662. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93663. };
  93664. ReflectionProbe.prototype.dispose = function () {
  93665. var index = this._scene.reflectionProbes.indexOf(this);
  93666. if (index !== -1) {
  93667. // Remove from the scene if found
  93668. this._scene.reflectionProbes.splice(index, 1);
  93669. }
  93670. if (this._renderTargetTexture) {
  93671. this._renderTargetTexture.dispose();
  93672. this._renderTargetTexture = null;
  93673. }
  93674. };
  93675. return ReflectionProbe;
  93676. }());
  93677. BABYLON.ReflectionProbe = ReflectionProbe;
  93678. })(BABYLON || (BABYLON = {}));
  93679. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93680. var BABYLON;
  93681. (function (BABYLON) {
  93682. var Layer = /** @class */ (function () {
  93683. function Layer(name, imgUrl, scene, isBackground, color) {
  93684. this.name = name;
  93685. this.scale = new BABYLON.Vector2(1, 1);
  93686. this.offset = new BABYLON.Vector2(0, 0);
  93687. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93688. this.layerMask = 0x0FFFFFFF;
  93689. this._vertexBuffers = {};
  93690. // Events
  93691. /**
  93692. * An event triggered when the layer is disposed.
  93693. */
  93694. this.onDisposeObservable = new BABYLON.Observable();
  93695. /**
  93696. * An event triggered before rendering the scene
  93697. */
  93698. this.onBeforeRenderObservable = new BABYLON.Observable();
  93699. /**
  93700. * An event triggered after rendering the scene
  93701. */
  93702. this.onAfterRenderObservable = new BABYLON.Observable();
  93703. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93704. this.isBackground = isBackground === undefined ? true : isBackground;
  93705. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93706. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93707. this._scene.layers.push(this);
  93708. var engine = this._scene.getEngine();
  93709. // VBO
  93710. var vertices = [];
  93711. vertices.push(1, 1);
  93712. vertices.push(-1, 1);
  93713. vertices.push(-1, -1);
  93714. vertices.push(1, -1);
  93715. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93716. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93717. this._createIndexBuffer();
  93718. // Effects
  93719. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93720. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93721. }
  93722. Object.defineProperty(Layer.prototype, "onDispose", {
  93723. set: function (callback) {
  93724. if (this._onDisposeObserver) {
  93725. this.onDisposeObservable.remove(this._onDisposeObserver);
  93726. }
  93727. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93728. },
  93729. enumerable: true,
  93730. configurable: true
  93731. });
  93732. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93733. set: function (callback) {
  93734. if (this._onBeforeRenderObserver) {
  93735. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93736. }
  93737. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93738. },
  93739. enumerable: true,
  93740. configurable: true
  93741. });
  93742. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93743. set: function (callback) {
  93744. if (this._onAfterRenderObserver) {
  93745. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93746. }
  93747. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93748. },
  93749. enumerable: true,
  93750. configurable: true
  93751. });
  93752. Layer.prototype._createIndexBuffer = function () {
  93753. var engine = this._scene.getEngine();
  93754. // Indices
  93755. var indices = [];
  93756. indices.push(0);
  93757. indices.push(1);
  93758. indices.push(2);
  93759. indices.push(0);
  93760. indices.push(2);
  93761. indices.push(3);
  93762. this._indexBuffer = engine.createIndexBuffer(indices);
  93763. };
  93764. Layer.prototype._rebuild = function () {
  93765. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93766. if (vb) {
  93767. vb._rebuild();
  93768. }
  93769. this._createIndexBuffer();
  93770. };
  93771. Layer.prototype.render = function () {
  93772. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93773. // Check
  93774. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93775. return;
  93776. var engine = this._scene.getEngine();
  93777. this.onBeforeRenderObservable.notifyObservers(this);
  93778. // Render
  93779. engine.enableEffect(currentEffect);
  93780. engine.setState(false);
  93781. // Texture
  93782. currentEffect.setTexture("textureSampler", this.texture);
  93783. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93784. // Color
  93785. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93786. // Scale / offset
  93787. currentEffect.setVector2("offset", this.offset);
  93788. currentEffect.setVector2("scale", this.scale);
  93789. // VBOs
  93790. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93791. // Draw order
  93792. if (!this.alphaTest) {
  93793. engine.setAlphaMode(this.alphaBlendingMode);
  93794. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93795. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93796. }
  93797. else {
  93798. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93799. }
  93800. this.onAfterRenderObservable.notifyObservers(this);
  93801. };
  93802. Layer.prototype.dispose = function () {
  93803. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93804. if (vertexBuffer) {
  93805. vertexBuffer.dispose();
  93806. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93807. }
  93808. if (this._indexBuffer) {
  93809. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93810. this._indexBuffer = null;
  93811. }
  93812. if (this.texture) {
  93813. this.texture.dispose();
  93814. this.texture = null;
  93815. }
  93816. // Remove from scene
  93817. var index = this._scene.layers.indexOf(this);
  93818. this._scene.layers.splice(index, 1);
  93819. // Callback
  93820. this.onDisposeObservable.notifyObservers(this);
  93821. this.onDisposeObservable.clear();
  93822. this.onAfterRenderObservable.clear();
  93823. this.onBeforeRenderObservable.clear();
  93824. };
  93825. return Layer;
  93826. }());
  93827. BABYLON.Layer = Layer;
  93828. })(BABYLON || (BABYLON = {}));
  93829. //# sourceMappingURL=babylon.layer.js.map
  93830. var BABYLON;
  93831. (function (BABYLON) {
  93832. var TextureTools = /** @class */ (function () {
  93833. function TextureTools() {
  93834. }
  93835. /**
  93836. * Uses the GPU to create a copy texture rescaled at a given size
  93837. * @param texture Texture to copy from
  93838. * @param width Desired width
  93839. * @param height Desired height
  93840. * @return Generated texture
  93841. */
  93842. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93843. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93844. var scene = texture.getScene();
  93845. var engine = scene.getEngine();
  93846. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93847. rtt.wrapU = texture.wrapU;
  93848. rtt.wrapV = texture.wrapV;
  93849. rtt.uOffset = texture.uOffset;
  93850. rtt.vOffset = texture.vOffset;
  93851. rtt.uScale = texture.uScale;
  93852. rtt.vScale = texture.vScale;
  93853. rtt.uAng = texture.uAng;
  93854. rtt.vAng = texture.vAng;
  93855. rtt.wAng = texture.wAng;
  93856. rtt.coordinatesIndex = texture.coordinatesIndex;
  93857. rtt.level = texture.level;
  93858. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  93859. rtt._texture.isReady = false;
  93860. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93861. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93862. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93863. passPostProcess.getEffect().executeWhenCompiled(function () {
  93864. passPostProcess.onApply = function (effect) {
  93865. effect.setTexture("textureSampler", texture);
  93866. };
  93867. var internalTexture = rtt.getInternalTexture();
  93868. if (internalTexture) {
  93869. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  93870. engine.unBindFramebuffer(internalTexture);
  93871. rtt.disposeFramebufferObjects();
  93872. passPostProcess.dispose();
  93873. internalTexture.isReady = true;
  93874. }
  93875. });
  93876. return rtt;
  93877. };
  93878. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  93879. if (!scene._environmentBRDFTexture) {
  93880. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93881. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93882. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93883. scene._environmentBRDFTexture = texture;
  93884. }
  93885. return scene._environmentBRDFTexture;
  93886. };
  93887. 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=";
  93888. return TextureTools;
  93889. }());
  93890. BABYLON.TextureTools = TextureTools;
  93891. })(BABYLON || (BABYLON = {}));
  93892. //# sourceMappingURL=babylon.textureTools.js.map
  93893. var BABYLON;
  93894. (function (BABYLON) {
  93895. var FramingBehavior = /** @class */ (function () {
  93896. function FramingBehavior() {
  93897. this._mode = FramingBehavior.FitFrustumSidesMode;
  93898. this._radiusScale = 1.0;
  93899. this._positionScale = 0.5;
  93900. this._defaultElevation = 0.3;
  93901. this._elevationReturnTime = 1500;
  93902. this._elevationReturnWaitTime = 1000;
  93903. this._zoomStopsAnimation = false;
  93904. this._framingTime = 1500;
  93905. this._isPointerDown = false;
  93906. this._lastInteractionTime = -Infinity;
  93907. // Framing control
  93908. this._animatables = new Array();
  93909. this._betaIsAnimating = false;
  93910. }
  93911. Object.defineProperty(FramingBehavior.prototype, "name", {
  93912. get: function () {
  93913. return "Framing";
  93914. },
  93915. enumerable: true,
  93916. configurable: true
  93917. });
  93918. Object.defineProperty(FramingBehavior.prototype, "mode", {
  93919. /**
  93920. * Gets current mode used by the behavior.
  93921. */
  93922. get: function () {
  93923. return this._mode;
  93924. },
  93925. /**
  93926. * Sets the current mode used by the behavior
  93927. */
  93928. set: function (mode) {
  93929. this._mode = mode;
  93930. },
  93931. enumerable: true,
  93932. configurable: true
  93933. });
  93934. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  93935. /**
  93936. * Gets the scale applied to the radius
  93937. */
  93938. get: function () {
  93939. return this._radiusScale;
  93940. },
  93941. /**
  93942. * Sets the scale applied to the radius (1 by default)
  93943. */
  93944. set: function (radius) {
  93945. this._radiusScale = radius;
  93946. },
  93947. enumerable: true,
  93948. configurable: true
  93949. });
  93950. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  93951. /**
  93952. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93953. */
  93954. get: function () {
  93955. return this._positionScale;
  93956. },
  93957. /**
  93958. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93959. */
  93960. set: function (scale) {
  93961. this._positionScale = scale;
  93962. },
  93963. enumerable: true,
  93964. configurable: true
  93965. });
  93966. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  93967. /**
  93968. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93969. * behaviour is triggered, in radians.
  93970. */
  93971. get: function () {
  93972. return this._defaultElevation;
  93973. },
  93974. /**
  93975. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93976. * behaviour is triggered, in radians.
  93977. */
  93978. set: function (elevation) {
  93979. this._defaultElevation = elevation;
  93980. },
  93981. enumerable: true,
  93982. configurable: true
  93983. });
  93984. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  93985. /**
  93986. * Gets the time (in milliseconds) taken to return to the default beta position.
  93987. * Negative value indicates camera should not return to default.
  93988. */
  93989. get: function () {
  93990. return this._elevationReturnTime;
  93991. },
  93992. /**
  93993. * Sets the time (in milliseconds) taken to return to the default beta position.
  93994. * Negative value indicates camera should not return to default.
  93995. */
  93996. set: function (speed) {
  93997. this._elevationReturnTime = speed;
  93998. },
  93999. enumerable: true,
  94000. configurable: true
  94001. });
  94002. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94003. /**
  94004. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94005. */
  94006. get: function () {
  94007. return this._elevationReturnWaitTime;
  94008. },
  94009. /**
  94010. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94011. */
  94012. set: function (time) {
  94013. this._elevationReturnWaitTime = time;
  94014. },
  94015. enumerable: true,
  94016. configurable: true
  94017. });
  94018. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94019. /**
  94020. * Gets the flag that indicates if user zooming should stop animation.
  94021. */
  94022. get: function () {
  94023. return this._zoomStopsAnimation;
  94024. },
  94025. /**
  94026. * Sets the flag that indicates if user zooming should stop animation.
  94027. */
  94028. set: function (flag) {
  94029. this._zoomStopsAnimation = flag;
  94030. },
  94031. enumerable: true,
  94032. configurable: true
  94033. });
  94034. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94035. /**
  94036. * Gets the transition time when framing the mesh, in milliseconds
  94037. */
  94038. get: function () {
  94039. return this._framingTime;
  94040. },
  94041. /**
  94042. * Sets the transition time when framing the mesh, in milliseconds
  94043. */
  94044. set: function (time) {
  94045. this._framingTime = time;
  94046. },
  94047. enumerable: true,
  94048. configurable: true
  94049. });
  94050. FramingBehavior.prototype.init = function () {
  94051. // Do notihng
  94052. };
  94053. FramingBehavior.prototype.attach = function (camera) {
  94054. var _this = this;
  94055. this._attachedCamera = camera;
  94056. var scene = this._attachedCamera.getScene();
  94057. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94058. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94059. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94060. _this._isPointerDown = true;
  94061. return;
  94062. }
  94063. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94064. _this._isPointerDown = false;
  94065. }
  94066. });
  94067. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94068. if (mesh) {
  94069. _this.zoomOnMesh(mesh);
  94070. }
  94071. });
  94072. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94073. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94074. _this._applyUserInteraction();
  94075. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94076. // back to the default position after a given timeout
  94077. _this._maintainCameraAboveGround();
  94078. });
  94079. };
  94080. FramingBehavior.prototype.detach = function () {
  94081. if (!this._attachedCamera) {
  94082. return;
  94083. }
  94084. var scene = this._attachedCamera.getScene();
  94085. if (this._onPrePointerObservableObserver) {
  94086. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94087. }
  94088. if (this._onAfterCheckInputsObserver) {
  94089. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94090. }
  94091. if (this._onMeshTargetChangedObserver) {
  94092. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94093. }
  94094. this._attachedCamera = null;
  94095. };
  94096. /**
  94097. * Targets the given mesh and updates zoom level accordingly.
  94098. * @param mesh The mesh to target.
  94099. * @param radius Optional. If a cached radius position already exists, overrides default.
  94100. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94101. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94102. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94103. */
  94104. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94105. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94106. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94107. mesh.computeWorldMatrix(true);
  94108. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94109. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94110. };
  94111. /**
  94112. * Targets the given mesh with its children and updates zoom level accordingly.
  94113. * @param mesh The mesh to target.
  94114. * @param radius Optional. If a cached radius position already exists, overrides default.
  94115. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94116. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94117. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94118. */
  94119. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94120. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94121. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94122. mesh.computeWorldMatrix(true);
  94123. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94124. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94125. };
  94126. /**
  94127. * Targets the given meshes with their children and updates zoom level accordingly.
  94128. * @param meshes The mesh to target.
  94129. * @param radius Optional. If a cached radius position already exists, overrides default.
  94130. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94131. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94132. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94133. */
  94134. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94135. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94136. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94137. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94138. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94139. for (var i = 0; i < meshes.length; i++) {
  94140. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94141. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94142. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94143. }
  94144. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94145. };
  94146. /**
  94147. * Targets the given mesh and updates zoom level accordingly.
  94148. * @param mesh The mesh to target.
  94149. * @param radius Optional. If a cached radius position already exists, overrides default.
  94150. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94151. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94152. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94153. */
  94154. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94155. var _this = this;
  94156. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94157. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94158. var zoomTarget;
  94159. if (!this._attachedCamera) {
  94160. return;
  94161. }
  94162. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94163. var bottom = minimumWorld.y;
  94164. var top = maximumWorld.y;
  94165. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94166. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94167. if (focusOnOriginXZ) {
  94168. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94169. }
  94170. else {
  94171. var centerWorld = minimumWorld.add(radiusWorld);
  94172. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94173. }
  94174. if (!this._vectorTransition) {
  94175. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94176. }
  94177. this._betaIsAnimating = true;
  94178. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94179. if (animatable) {
  94180. this._animatables.push(animatable);
  94181. }
  94182. // sets the radius and lower radius bounds
  94183. // Small delta ensures camera is not always at lower zoom limit.
  94184. var radius = 0;
  94185. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94186. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94187. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94188. radius = position;
  94189. }
  94190. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94191. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94192. if (this._attachedCamera.lowerRadiusLimit === null) {
  94193. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94194. }
  94195. }
  94196. // Set sensibilities
  94197. var extend = maximumWorld.subtract(minimumWorld).length();
  94198. this._attachedCamera.panningSensibility = 5000 / extend;
  94199. this._attachedCamera.wheelPrecision = 100 / radius;
  94200. // transition to new radius
  94201. if (!this._radiusTransition) {
  94202. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94203. }
  94204. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94205. _this.stopAllAnimations();
  94206. if (onAnimationEnd) {
  94207. onAnimationEnd();
  94208. }
  94209. if (_this._attachedCamera) {
  94210. _this._attachedCamera.storeState();
  94211. }
  94212. });
  94213. if (animatable) {
  94214. this._animatables.push(animatable);
  94215. }
  94216. };
  94217. /**
  94218. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94219. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94220. * frustum width.
  94221. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94222. * to fully enclose the mesh in the viewing frustum.
  94223. */
  94224. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94225. var size = maximumWorld.subtract(minimumWorld);
  94226. var boxVectorGlobalDiagonal = size.length();
  94227. var frustumSlope = this._getFrustumSlope();
  94228. // Formula for setting distance
  94229. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94230. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94231. // Horizon distance
  94232. var radius = radiusWithoutFraming * this._radiusScale;
  94233. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94234. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94235. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94236. var camera = this._attachedCamera;
  94237. if (!camera) {
  94238. return 0;
  94239. }
  94240. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94241. // Don't exceed the requested limit
  94242. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94243. }
  94244. // Don't exceed the upper radius limit
  94245. if (camera.upperRadiusLimit) {
  94246. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94247. }
  94248. return distance;
  94249. };
  94250. /**
  94251. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94252. * is automatically returned to its default position (expected to be above ground plane).
  94253. */
  94254. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94255. var _this = this;
  94256. if (this._elevationReturnTime < 0) {
  94257. return;
  94258. }
  94259. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94260. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94261. var limitBeta = Math.PI * 0.5;
  94262. // Bring the camera back up if below the ground plane
  94263. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94264. this._betaIsAnimating = true;
  94265. //Transition to new position
  94266. this.stopAllAnimations();
  94267. if (!this._betaTransition) {
  94268. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94269. }
  94270. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94271. _this._clearAnimationLocks();
  94272. _this.stopAllAnimations();
  94273. });
  94274. if (animatabe) {
  94275. this._animatables.push(animatabe);
  94276. }
  94277. }
  94278. };
  94279. /**
  94280. * Returns the frustum slope based on the canvas ratio and camera FOV
  94281. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94282. */
  94283. FramingBehavior.prototype._getFrustumSlope = function () {
  94284. // Calculate the viewport ratio
  94285. // Aspect Ratio is Height/Width.
  94286. var camera = this._attachedCamera;
  94287. if (!camera) {
  94288. return BABYLON.Vector2.Zero();
  94289. }
  94290. var engine = camera.getScene().getEngine();
  94291. var aspectRatio = engine.getAspectRatio(camera);
  94292. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94293. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94294. var frustumSlopeY = Math.tan(camera.fov / 2);
  94295. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94296. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94297. // along the forward vector.
  94298. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94299. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94300. };
  94301. /**
  94302. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94303. */
  94304. FramingBehavior.prototype._clearAnimationLocks = function () {
  94305. this._betaIsAnimating = false;
  94306. };
  94307. /**
  94308. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94309. */
  94310. FramingBehavior.prototype._applyUserInteraction = function () {
  94311. if (this.isUserIsMoving) {
  94312. this._lastInteractionTime = BABYLON.Tools.Now;
  94313. this.stopAllAnimations();
  94314. this._clearAnimationLocks();
  94315. }
  94316. };
  94317. /**
  94318. * Stops and removes all animations that have been applied to the camera
  94319. */
  94320. FramingBehavior.prototype.stopAllAnimations = function () {
  94321. if (this._attachedCamera) {
  94322. this._attachedCamera.animations = [];
  94323. }
  94324. while (this._animatables.length) {
  94325. if (this._animatables[0]) {
  94326. this._animatables[0].onAnimationEnd = null;
  94327. this._animatables[0].stop();
  94328. }
  94329. this._animatables.shift();
  94330. }
  94331. };
  94332. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94333. /**
  94334. * Gets a value indicating if the user is moving the camera
  94335. */
  94336. get: function () {
  94337. if (!this._attachedCamera) {
  94338. return false;
  94339. }
  94340. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94341. this._attachedCamera.inertialBetaOffset !== 0 ||
  94342. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94343. this._attachedCamera.inertialPanningX !== 0 ||
  94344. this._attachedCamera.inertialPanningY !== 0 ||
  94345. this._isPointerDown;
  94346. },
  94347. enumerable: true,
  94348. configurable: true
  94349. });
  94350. /**
  94351. * The easing function used by animations
  94352. */
  94353. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94354. /**
  94355. * The easing mode used by animations
  94356. */
  94357. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94358. // Statics
  94359. /**
  94360. * The camera can move all the way towards the mesh.
  94361. */
  94362. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94363. /**
  94364. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94365. */
  94366. FramingBehavior.FitFrustumSidesMode = 1;
  94367. return FramingBehavior;
  94368. }());
  94369. BABYLON.FramingBehavior = FramingBehavior;
  94370. })(BABYLON || (BABYLON = {}));
  94371. //# sourceMappingURL=babylon.framingBehavior.js.map
  94372. var BABYLON;
  94373. (function (BABYLON) {
  94374. /**
  94375. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94376. */
  94377. var BouncingBehavior = /** @class */ (function () {
  94378. function BouncingBehavior() {
  94379. /**
  94380. * The duration of the animation, in milliseconds
  94381. */
  94382. this.transitionDuration = 450;
  94383. /**
  94384. * Length of the distance animated by the transition when lower radius is reached
  94385. */
  94386. this.lowerRadiusTransitionRange = 2;
  94387. /**
  94388. * Length of the distance animated by the transition when upper radius is reached
  94389. */
  94390. this.upperRadiusTransitionRange = -2;
  94391. this._autoTransitionRange = false;
  94392. // Animations
  94393. this._radiusIsAnimating = false;
  94394. this._radiusBounceTransition = null;
  94395. this._animatables = new Array();
  94396. }
  94397. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94398. get: function () {
  94399. return "Bouncing";
  94400. },
  94401. enumerable: true,
  94402. configurable: true
  94403. });
  94404. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94405. /**
  94406. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94407. */
  94408. get: function () {
  94409. return this._autoTransitionRange;
  94410. },
  94411. /**
  94412. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94413. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94414. */
  94415. set: function (value) {
  94416. var _this = this;
  94417. if (this._autoTransitionRange === value) {
  94418. return;
  94419. }
  94420. this._autoTransitionRange = value;
  94421. var camera = this._attachedCamera;
  94422. if (!camera) {
  94423. return;
  94424. }
  94425. if (value) {
  94426. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94427. if (!mesh) {
  94428. return;
  94429. }
  94430. mesh.computeWorldMatrix(true);
  94431. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94432. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94433. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94434. });
  94435. }
  94436. else if (this._onMeshTargetChangedObserver) {
  94437. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94438. }
  94439. },
  94440. enumerable: true,
  94441. configurable: true
  94442. });
  94443. BouncingBehavior.prototype.init = function () {
  94444. // Do notihng
  94445. };
  94446. BouncingBehavior.prototype.attach = function (camera) {
  94447. var _this = this;
  94448. this._attachedCamera = camera;
  94449. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94450. if (!_this._attachedCamera) {
  94451. return;
  94452. }
  94453. // Add the bounce animation to the lower radius limit
  94454. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94455. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94456. }
  94457. // Add the bounce animation to the upper radius limit
  94458. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94459. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94460. }
  94461. });
  94462. };
  94463. BouncingBehavior.prototype.detach = function () {
  94464. if (!this._attachedCamera) {
  94465. return;
  94466. }
  94467. if (this._onAfterCheckInputsObserver) {
  94468. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94469. }
  94470. if (this._onMeshTargetChangedObserver) {
  94471. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94472. }
  94473. this._attachedCamera = null;
  94474. };
  94475. /**
  94476. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94477. * @param radiusLimit The limit to check against.
  94478. * @return Bool to indicate if at limit.
  94479. */
  94480. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94481. if (!this._attachedCamera) {
  94482. return false;
  94483. }
  94484. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94485. return true;
  94486. }
  94487. return false;
  94488. };
  94489. /**
  94490. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94491. * @param radiusDelta The delta by which to animate to. Can be negative.
  94492. */
  94493. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94494. var _this = this;
  94495. if (!this._attachedCamera) {
  94496. return;
  94497. }
  94498. if (!this._radiusBounceTransition) {
  94499. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94500. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94501. }
  94502. // Prevent zoom until bounce has completed
  94503. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94504. this._attachedCamera.wheelPrecision = Infinity;
  94505. this._attachedCamera.inertialRadiusOffset = 0;
  94506. // Animate to the radius limit
  94507. this.stopAllAnimations();
  94508. this._radiusIsAnimating = true;
  94509. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94510. if (animatable) {
  94511. this._animatables.push(animatable);
  94512. }
  94513. };
  94514. /**
  94515. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94516. */
  94517. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94518. this._radiusIsAnimating = false;
  94519. if (this._attachedCamera) {
  94520. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94521. }
  94522. };
  94523. /**
  94524. * Stops and removes all animations that have been applied to the camera
  94525. */
  94526. BouncingBehavior.prototype.stopAllAnimations = function () {
  94527. if (this._attachedCamera) {
  94528. this._attachedCamera.animations = [];
  94529. }
  94530. while (this._animatables.length) {
  94531. this._animatables[0].onAnimationEnd = null;
  94532. this._animatables[0].stop();
  94533. this._animatables.shift();
  94534. }
  94535. };
  94536. /**
  94537. * The easing function used by animations
  94538. */
  94539. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94540. /**
  94541. * The easing mode used by animations
  94542. */
  94543. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94544. return BouncingBehavior;
  94545. }());
  94546. BABYLON.BouncingBehavior = BouncingBehavior;
  94547. })(BABYLON || (BABYLON = {}));
  94548. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94549. var BABYLON;
  94550. (function (BABYLON) {
  94551. var AutoRotationBehavior = /** @class */ (function () {
  94552. function AutoRotationBehavior() {
  94553. this._zoomStopsAnimation = false;
  94554. this._idleRotationSpeed = 0.05;
  94555. this._idleRotationWaitTime = 2000;
  94556. this._idleRotationSpinupTime = 2000;
  94557. this._isPointerDown = false;
  94558. this._lastFrameTime = null;
  94559. this._lastInteractionTime = -Infinity;
  94560. this._cameraRotationSpeed = 0;
  94561. this._lastFrameRadius = 0;
  94562. }
  94563. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94564. get: function () {
  94565. return "AutoRotation";
  94566. },
  94567. enumerable: true,
  94568. configurable: true
  94569. });
  94570. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94571. /**
  94572. * Gets the flag that indicates if user zooming should stop animation.
  94573. */
  94574. get: function () {
  94575. return this._zoomStopsAnimation;
  94576. },
  94577. /**
  94578. * Sets the flag that indicates if user zooming should stop animation.
  94579. */
  94580. set: function (flag) {
  94581. this._zoomStopsAnimation = flag;
  94582. },
  94583. enumerable: true,
  94584. configurable: true
  94585. });
  94586. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94587. /**
  94588. * Gets the default speed at which the camera rotates around the model.
  94589. */
  94590. get: function () {
  94591. return this._idleRotationSpeed;
  94592. },
  94593. /**
  94594. * Sets the default speed at which the camera rotates around the model.
  94595. */
  94596. set: function (speed) {
  94597. this._idleRotationSpeed = speed;
  94598. },
  94599. enumerable: true,
  94600. configurable: true
  94601. });
  94602. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94603. /**
  94604. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94605. */
  94606. get: function () {
  94607. return this._idleRotationWaitTime;
  94608. },
  94609. /**
  94610. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94611. */
  94612. set: function (time) {
  94613. this._idleRotationWaitTime = time;
  94614. },
  94615. enumerable: true,
  94616. configurable: true
  94617. });
  94618. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94619. /**
  94620. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94621. */
  94622. get: function () {
  94623. return this._idleRotationSpinupTime;
  94624. },
  94625. /**
  94626. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94627. */
  94628. set: function (time) {
  94629. this._idleRotationSpinupTime = time;
  94630. },
  94631. enumerable: true,
  94632. configurable: true
  94633. });
  94634. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94635. /**
  94636. * Gets a value indicating if the camera is currently rotating because of this behavior
  94637. */
  94638. get: function () {
  94639. return Math.abs(this._cameraRotationSpeed) > 0;
  94640. },
  94641. enumerable: true,
  94642. configurable: true
  94643. });
  94644. AutoRotationBehavior.prototype.init = function () {
  94645. // Do notihng
  94646. };
  94647. AutoRotationBehavior.prototype.attach = function (camera) {
  94648. var _this = this;
  94649. this._attachedCamera = camera;
  94650. var scene = this._attachedCamera.getScene();
  94651. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94652. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94653. _this._isPointerDown = true;
  94654. return;
  94655. }
  94656. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94657. _this._isPointerDown = false;
  94658. }
  94659. });
  94660. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94661. var now = BABYLON.Tools.Now;
  94662. var dt = 0;
  94663. if (_this._lastFrameTime != null) {
  94664. dt = now - _this._lastFrameTime;
  94665. }
  94666. _this._lastFrameTime = now;
  94667. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94668. _this._applyUserInteraction();
  94669. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94670. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94671. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94672. // Step camera rotation by rotation speed
  94673. if (_this._attachedCamera) {
  94674. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94675. }
  94676. });
  94677. };
  94678. AutoRotationBehavior.prototype.detach = function () {
  94679. if (!this._attachedCamera) {
  94680. return;
  94681. }
  94682. var scene = this._attachedCamera.getScene();
  94683. if (this._onPrePointerObservableObserver) {
  94684. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94685. }
  94686. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94687. this._attachedCamera = null;
  94688. };
  94689. /**
  94690. * Returns true if user is scrolling.
  94691. * @return true if user is scrolling.
  94692. */
  94693. AutoRotationBehavior.prototype._userIsZooming = function () {
  94694. if (!this._attachedCamera) {
  94695. return false;
  94696. }
  94697. return this._attachedCamera.inertialRadiusOffset !== 0;
  94698. };
  94699. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94700. if (!this._attachedCamera) {
  94701. return false;
  94702. }
  94703. var zoomHasHitLimit = false;
  94704. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94705. zoomHasHitLimit = true;
  94706. }
  94707. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94708. this._lastFrameRadius = this._attachedCamera.radius;
  94709. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94710. };
  94711. /**
  94712. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94713. */
  94714. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94715. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94716. this._lastInteractionTime = BABYLON.Tools.Now;
  94717. }
  94718. };
  94719. // Tools
  94720. AutoRotationBehavior.prototype._userIsMoving = function () {
  94721. if (!this._attachedCamera) {
  94722. return false;
  94723. }
  94724. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94725. this._attachedCamera.inertialBetaOffset !== 0 ||
  94726. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94727. this._attachedCamera.inertialPanningX !== 0 ||
  94728. this._attachedCamera.inertialPanningY !== 0 ||
  94729. this._isPointerDown;
  94730. };
  94731. return AutoRotationBehavior;
  94732. }());
  94733. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94734. })(BABYLON || (BABYLON = {}));
  94735. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94736. var BABYLON;
  94737. (function (BABYLON) {
  94738. var NullEngineOptions = /** @class */ (function () {
  94739. function NullEngineOptions() {
  94740. this.renderWidth = 512;
  94741. this.renderHeight = 256;
  94742. this.textureSize = 512;
  94743. this.deterministicLockstep = false;
  94744. this.lockstepMaxSteps = 4;
  94745. }
  94746. return NullEngineOptions;
  94747. }());
  94748. BABYLON.NullEngineOptions = NullEngineOptions;
  94749. /**
  94750. * The null engine class provides support for headless version of babylon.js.
  94751. * This can be used in server side scenario or for testing purposes
  94752. */
  94753. var NullEngine = /** @class */ (function (_super) {
  94754. __extends(NullEngine, _super);
  94755. function NullEngine(options) {
  94756. if (options === void 0) { options = new NullEngineOptions(); }
  94757. var _this = _super.call(this, null) || this;
  94758. if (options.deterministicLockstep === undefined) {
  94759. options.deterministicLockstep = false;
  94760. }
  94761. if (options.lockstepMaxSteps === undefined) {
  94762. options.lockstepMaxSteps = 4;
  94763. }
  94764. _this._options = options;
  94765. // Init caps
  94766. // We consider we are on a webgl1 capable device
  94767. _this._caps = new BABYLON.EngineCapabilities();
  94768. _this._caps.maxTexturesImageUnits = 16;
  94769. _this._caps.maxVertexTextureImageUnits = 16;
  94770. _this._caps.maxTextureSize = 512;
  94771. _this._caps.maxCubemapTextureSize = 512;
  94772. _this._caps.maxRenderTextureSize = 512;
  94773. _this._caps.maxVertexAttribs = 16;
  94774. _this._caps.maxVaryingVectors = 16;
  94775. _this._caps.maxFragmentUniformVectors = 16;
  94776. _this._caps.maxVertexUniformVectors = 16;
  94777. // Extensions
  94778. _this._caps.standardDerivatives = false;
  94779. _this._caps.astc = null;
  94780. _this._caps.s3tc = null;
  94781. _this._caps.pvrtc = null;
  94782. _this._caps.etc1 = null;
  94783. _this._caps.etc2 = null;
  94784. _this._caps.textureAnisotropicFilterExtension = null;
  94785. _this._caps.maxAnisotropy = 0;
  94786. _this._caps.uintIndices = false;
  94787. _this._caps.fragmentDepthSupported = false;
  94788. _this._caps.highPrecisionShaderSupported = true;
  94789. _this._caps.colorBufferFloat = false;
  94790. _this._caps.textureFloat = false;
  94791. _this._caps.textureFloatLinearFiltering = false;
  94792. _this._caps.textureFloatRender = false;
  94793. _this._caps.textureHalfFloat = false;
  94794. _this._caps.textureHalfFloatLinearFiltering = false;
  94795. _this._caps.textureHalfFloatRender = false;
  94796. _this._caps.textureLOD = false;
  94797. _this._caps.drawBuffersExtension = false;
  94798. _this._caps.depthTextureExtension = false;
  94799. _this._caps.vertexArrayObject = false;
  94800. _this._caps.instancedArrays = false;
  94801. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94802. // Wrappers
  94803. if (typeof URL === "undefined") {
  94804. URL = {
  94805. createObjectURL: function () { },
  94806. revokeObjectURL: function () { }
  94807. };
  94808. }
  94809. if (typeof Blob === "undefined") {
  94810. Blob = function () { };
  94811. }
  94812. return _this;
  94813. }
  94814. NullEngine.prototype.isDeterministicLockStep = function () {
  94815. return this._options.deterministicLockstep;
  94816. };
  94817. NullEngine.prototype.getLockstepMaxSteps = function () {
  94818. return this._options.lockstepMaxSteps;
  94819. };
  94820. NullEngine.prototype.getHardwareScalingLevel = function () {
  94821. return 1.0;
  94822. };
  94823. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94824. return {
  94825. capacity: 0,
  94826. references: 1,
  94827. is32Bits: false
  94828. };
  94829. };
  94830. NullEngine.prototype.createIndexBuffer = function (indices) {
  94831. return {
  94832. capacity: 0,
  94833. references: 1,
  94834. is32Bits: false
  94835. };
  94836. };
  94837. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94838. if (stencil === void 0) { stencil = false; }
  94839. };
  94840. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94841. if (useScreen === void 0) { useScreen = false; }
  94842. if (!useScreen && this._currentRenderTarget) {
  94843. return this._currentRenderTarget.width;
  94844. }
  94845. return this._options.renderWidth;
  94846. };
  94847. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94848. if (useScreen === void 0) { useScreen = false; }
  94849. if (!useScreen && this._currentRenderTarget) {
  94850. return this._currentRenderTarget.height;
  94851. }
  94852. return this._options.renderHeight;
  94853. };
  94854. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94855. this._cachedViewport = viewport;
  94856. };
  94857. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94858. return {
  94859. transformFeedback: null,
  94860. __SPECTOR_rebuildProgram: null
  94861. };
  94862. };
  94863. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  94864. return [];
  94865. };
  94866. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  94867. return [];
  94868. };
  94869. NullEngine.prototype.bindSamplers = function (effect) {
  94870. this._currentEffect = null;
  94871. };
  94872. NullEngine.prototype.enableEffect = function (effect) {
  94873. this._currentEffect = effect;
  94874. if (effect.onBind) {
  94875. effect.onBind(effect);
  94876. }
  94877. effect.onBindObservable.notifyObservers(effect);
  94878. };
  94879. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  94880. if (zOffset === void 0) { zOffset = 0; }
  94881. if (reverseSide === void 0) { reverseSide = false; }
  94882. };
  94883. NullEngine.prototype.setIntArray = function (uniform, array) {
  94884. };
  94885. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  94886. };
  94887. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  94888. };
  94889. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  94890. };
  94891. NullEngine.prototype.setFloatArray = function (uniform, array) {
  94892. };
  94893. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  94894. };
  94895. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  94896. };
  94897. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  94898. };
  94899. NullEngine.prototype.setArray = function (uniform, array) {
  94900. };
  94901. NullEngine.prototype.setArray2 = function (uniform, array) {
  94902. };
  94903. NullEngine.prototype.setArray3 = function (uniform, array) {
  94904. };
  94905. NullEngine.prototype.setArray4 = function (uniform, array) {
  94906. };
  94907. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  94908. };
  94909. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  94910. };
  94911. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  94912. };
  94913. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  94914. };
  94915. NullEngine.prototype.setFloat = function (uniform, value) {
  94916. };
  94917. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  94918. };
  94919. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  94920. };
  94921. NullEngine.prototype.setBool = function (uniform, bool) {
  94922. };
  94923. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  94924. };
  94925. NullEngine.prototype.setColor3 = function (uniform, color3) {
  94926. };
  94927. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  94928. };
  94929. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  94930. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  94931. if (this._alphaMode === mode) {
  94932. return;
  94933. }
  94934. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  94935. if (!noDepthWriteChange) {
  94936. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  94937. }
  94938. this._alphaMode = mode;
  94939. };
  94940. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  94941. };
  94942. NullEngine.prototype.wipeCaches = function (bruteForce) {
  94943. if (this.preventCacheWipeBetweenFrames) {
  94944. return;
  94945. }
  94946. this.resetTextureCache();
  94947. this._currentEffect = null;
  94948. if (bruteForce) {
  94949. this._currentProgram = null;
  94950. this._stencilState.reset();
  94951. this._depthCullingState.reset();
  94952. this._alphaState.reset();
  94953. }
  94954. this._cachedVertexBuffers = null;
  94955. this._cachedIndexBuffer = null;
  94956. this._cachedEffectForVertexBuffers = null;
  94957. };
  94958. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  94959. };
  94960. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  94961. };
  94962. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  94963. };
  94964. NullEngine.prototype._createTexture = function () {
  94965. return {};
  94966. };
  94967. NullEngine.prototype._releaseTexture = function (texture) {
  94968. };
  94969. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  94970. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94971. if (onLoad === void 0) { onLoad = null; }
  94972. if (onError === void 0) { onError = null; }
  94973. if (buffer === void 0) { buffer = null; }
  94974. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  94975. var url = String(urlArg);
  94976. texture.url = url;
  94977. texture.generateMipMaps = !noMipmap;
  94978. texture.samplingMode = samplingMode;
  94979. texture.invertY = invertY;
  94980. texture.baseWidth = this._options.textureSize;
  94981. texture.baseHeight = this._options.textureSize;
  94982. texture.width = this._options.textureSize;
  94983. texture.height = this._options.textureSize;
  94984. if (format) {
  94985. texture.format = format;
  94986. }
  94987. texture.isReady = true;
  94988. if (onLoad) {
  94989. onLoad();
  94990. }
  94991. return texture;
  94992. };
  94993. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  94994. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  94995. if (options !== undefined && typeof options === "object") {
  94996. fullOptions.generateMipMaps = options.generateMipMaps;
  94997. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  94998. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  94999. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95000. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95001. }
  95002. else {
  95003. fullOptions.generateMipMaps = options;
  95004. fullOptions.generateDepthBuffer = true;
  95005. fullOptions.generateStencilBuffer = false;
  95006. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95007. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95008. }
  95009. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95010. var width = size.width || size;
  95011. var height = size.height || size;
  95012. texture._depthStencilBuffer = {};
  95013. texture._framebuffer = {};
  95014. texture.baseWidth = width;
  95015. texture.baseHeight = height;
  95016. texture.width = width;
  95017. texture.height = height;
  95018. texture.isReady = true;
  95019. texture.samples = 1;
  95020. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95021. texture.samplingMode = fullOptions.samplingMode;
  95022. texture.type = fullOptions.type;
  95023. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95024. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95025. return texture;
  95026. };
  95027. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95028. texture.samplingMode = samplingMode;
  95029. };
  95030. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95031. if (this._currentRenderTarget) {
  95032. this.unBindFramebuffer(this._currentRenderTarget);
  95033. }
  95034. this._currentRenderTarget = texture;
  95035. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95036. if (this._cachedViewport && !forceFullscreenViewport) {
  95037. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95038. }
  95039. };
  95040. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95041. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95042. this._currentRenderTarget = null;
  95043. if (onBeforeUnbind) {
  95044. if (texture._MSAAFramebuffer) {
  95045. this._currentFramebuffer = texture._framebuffer;
  95046. }
  95047. onBeforeUnbind();
  95048. }
  95049. this._currentFramebuffer = null;
  95050. };
  95051. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95052. var vbo = {
  95053. capacity: 1,
  95054. references: 1,
  95055. is32Bits: false
  95056. };
  95057. return vbo;
  95058. };
  95059. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95060. if (offset === void 0) { offset = 0; }
  95061. };
  95062. /**
  95063. * Updates a dynamic vertex buffer.
  95064. * @param vertexBuffer the vertex buffer to update
  95065. * @param data the data used to update the vertex buffer
  95066. * @param byteOffset the byte offset of the data (optional)
  95067. * @param byteLength the byte length of the data (optional)
  95068. */
  95069. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95070. };
  95071. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95072. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95073. this._boundTexturesCache[this._activeChannel] = texture;
  95074. }
  95075. };
  95076. NullEngine.prototype._bindTexture = function (channel, texture) {
  95077. if (channel < 0) {
  95078. return;
  95079. }
  95080. this._bindTextureDirectly(0, texture);
  95081. };
  95082. NullEngine.prototype._releaseBuffer = function (buffer) {
  95083. buffer.references--;
  95084. if (buffer.references === 0) {
  95085. return true;
  95086. }
  95087. return false;
  95088. };
  95089. return NullEngine;
  95090. }(BABYLON.Engine));
  95091. BABYLON.NullEngine = NullEngine;
  95092. })(BABYLON || (BABYLON = {}));
  95093. //# sourceMappingURL=babylon.nullEngine.js.map
  95094. var BABYLON;
  95095. (function (BABYLON) {
  95096. /**
  95097. * This class can be used to get instrumentation data from a Babylon engine
  95098. */
  95099. var EngineInstrumentation = /** @class */ (function () {
  95100. function EngineInstrumentation(engine) {
  95101. this.engine = engine;
  95102. this._captureGPUFrameTime = false;
  95103. this._gpuFrameTime = new BABYLON.PerfCounter();
  95104. this._captureShaderCompilationTime = false;
  95105. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95106. // Observers
  95107. this._onBeginFrameObserver = null;
  95108. this._onEndFrameObserver = null;
  95109. this._onBeforeShaderCompilationObserver = null;
  95110. this._onAfterShaderCompilationObserver = null;
  95111. }
  95112. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95113. // Properties
  95114. /**
  95115. * Gets the perf counter used for GPU frame time
  95116. */
  95117. get: function () {
  95118. return this._gpuFrameTime;
  95119. },
  95120. enumerable: true,
  95121. configurable: true
  95122. });
  95123. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95124. /**
  95125. * Gets the GPU frame time capture status
  95126. */
  95127. get: function () {
  95128. return this._captureGPUFrameTime;
  95129. },
  95130. /**
  95131. * Enable or disable the GPU frame time capture
  95132. */
  95133. set: function (value) {
  95134. var _this = this;
  95135. if (value === this._captureGPUFrameTime) {
  95136. return;
  95137. }
  95138. this._captureGPUFrameTime = value;
  95139. if (value) {
  95140. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95141. if (!_this._gpuFrameTimeToken) {
  95142. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95143. }
  95144. });
  95145. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95146. if (!_this._gpuFrameTimeToken) {
  95147. return;
  95148. }
  95149. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95150. if (time > -1) {
  95151. _this._gpuFrameTimeToken = null;
  95152. _this._gpuFrameTime.fetchNewFrame();
  95153. _this._gpuFrameTime.addCount(time, true);
  95154. }
  95155. });
  95156. }
  95157. else {
  95158. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95159. this._onBeginFrameObserver = null;
  95160. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95161. this._onEndFrameObserver = null;
  95162. }
  95163. },
  95164. enumerable: true,
  95165. configurable: true
  95166. });
  95167. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95168. /**
  95169. * Gets the perf counter used for shader compilation time
  95170. */
  95171. get: function () {
  95172. return this._shaderCompilationTime;
  95173. },
  95174. enumerable: true,
  95175. configurable: true
  95176. });
  95177. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95178. /**
  95179. * Gets the shader compilation time capture status
  95180. */
  95181. get: function () {
  95182. return this._captureShaderCompilationTime;
  95183. },
  95184. /**
  95185. * Enable or disable the shader compilation time capture
  95186. */
  95187. set: function (value) {
  95188. var _this = this;
  95189. if (value === this._captureShaderCompilationTime) {
  95190. return;
  95191. }
  95192. this._captureShaderCompilationTime = value;
  95193. if (value) {
  95194. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95195. _this._shaderCompilationTime.fetchNewFrame();
  95196. _this._shaderCompilationTime.beginMonitoring();
  95197. });
  95198. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95199. _this._shaderCompilationTime.endMonitoring();
  95200. });
  95201. }
  95202. else {
  95203. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95204. this._onBeforeShaderCompilationObserver = null;
  95205. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95206. this._onAfterShaderCompilationObserver = null;
  95207. }
  95208. },
  95209. enumerable: true,
  95210. configurable: true
  95211. });
  95212. EngineInstrumentation.prototype.dispose = function () {
  95213. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95214. this._onBeginFrameObserver = null;
  95215. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95216. this._onEndFrameObserver = null;
  95217. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95218. this._onBeforeShaderCompilationObserver = null;
  95219. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95220. this._onAfterShaderCompilationObserver = null;
  95221. this.engine = null;
  95222. };
  95223. return EngineInstrumentation;
  95224. }());
  95225. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95226. })(BABYLON || (BABYLON = {}));
  95227. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95228. var BABYLON;
  95229. (function (BABYLON) {
  95230. /**
  95231. * This class can be used to get instrumentation data from a Babylon engine
  95232. */
  95233. var SceneInstrumentation = /** @class */ (function () {
  95234. function SceneInstrumentation(scene) {
  95235. var _this = this;
  95236. this.scene = scene;
  95237. this._captureActiveMeshesEvaluationTime = false;
  95238. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95239. this._captureRenderTargetsRenderTime = false;
  95240. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95241. this._captureFrameTime = false;
  95242. this._frameTime = new BABYLON.PerfCounter();
  95243. this._captureRenderTime = false;
  95244. this._renderTime = new BABYLON.PerfCounter();
  95245. this._captureInterFrameTime = false;
  95246. this._interFrameTime = new BABYLON.PerfCounter();
  95247. this._captureParticlesRenderTime = false;
  95248. this._particlesRenderTime = new BABYLON.PerfCounter();
  95249. this._captureSpritesRenderTime = false;
  95250. this._spritesRenderTime = new BABYLON.PerfCounter();
  95251. this._capturePhysicsTime = false;
  95252. this._physicsTime = new BABYLON.PerfCounter();
  95253. this._captureAnimationsTime = false;
  95254. this._animationsTime = new BABYLON.PerfCounter();
  95255. // Observers
  95256. this._onBeforeActiveMeshesEvaluationObserver = null;
  95257. this._onAfterActiveMeshesEvaluationObserver = null;
  95258. this._onBeforeRenderTargetsRenderObserver = null;
  95259. this._onAfterRenderTargetsRenderObserver = null;
  95260. this._onAfterRenderObserver = null;
  95261. this._onBeforeDrawPhaseObserver = null;
  95262. this._onAfterDrawPhaseObserver = null;
  95263. this._onBeforeAnimationsObserver = null;
  95264. this._onBeforeParticlesRenderingObserver = null;
  95265. this._onAfterParticlesRenderingObserver = null;
  95266. this._onBeforeSpritesRenderingObserver = null;
  95267. this._onAfterSpritesRenderingObserver = null;
  95268. this._onBeforePhysicsObserver = null;
  95269. this._onAfterPhysicsObserver = null;
  95270. this._onAfterAnimationsObserver = null;
  95271. // Before render
  95272. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95273. if (_this._captureActiveMeshesEvaluationTime) {
  95274. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95275. }
  95276. if (_this._captureRenderTargetsRenderTime) {
  95277. _this._renderTargetsRenderTime.fetchNewFrame();
  95278. }
  95279. if (_this._captureFrameTime) {
  95280. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95281. _this._frameTime.beginMonitoring();
  95282. }
  95283. if (_this._captureInterFrameTime) {
  95284. _this._interFrameTime.endMonitoring();
  95285. }
  95286. if (_this._captureParticlesRenderTime) {
  95287. _this._particlesRenderTime.fetchNewFrame();
  95288. }
  95289. if (_this._captureSpritesRenderTime) {
  95290. _this._spritesRenderTime.fetchNewFrame();
  95291. }
  95292. if (_this._captureAnimationsTime) {
  95293. _this._animationsTime.beginMonitoring();
  95294. }
  95295. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95296. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95297. });
  95298. // After render
  95299. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95300. if (_this._captureFrameTime) {
  95301. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95302. _this._frameTime.endMonitoring();
  95303. }
  95304. if (_this._captureRenderTime) {
  95305. _this._renderTime.endMonitoring(false);
  95306. }
  95307. if (_this._captureInterFrameTime) {
  95308. _this._interFrameTime.beginMonitoring();
  95309. }
  95310. });
  95311. }
  95312. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95313. // Properties
  95314. /**
  95315. * Gets the perf counter used for active meshes evaluation time
  95316. */
  95317. get: function () {
  95318. return this._activeMeshesEvaluationTime;
  95319. },
  95320. enumerable: true,
  95321. configurable: true
  95322. });
  95323. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95324. /**
  95325. * Gets the active meshes evaluation time capture status
  95326. */
  95327. get: function () {
  95328. return this._captureActiveMeshesEvaluationTime;
  95329. },
  95330. /**
  95331. * Enable or disable the active meshes evaluation time capture
  95332. */
  95333. set: function (value) {
  95334. var _this = this;
  95335. if (value === this._captureActiveMeshesEvaluationTime) {
  95336. return;
  95337. }
  95338. this._captureActiveMeshesEvaluationTime = value;
  95339. if (value) {
  95340. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95341. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95342. _this._activeMeshesEvaluationTime.beginMonitoring();
  95343. });
  95344. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95345. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95346. _this._activeMeshesEvaluationTime.endMonitoring();
  95347. });
  95348. }
  95349. else {
  95350. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95351. this._onBeforeActiveMeshesEvaluationObserver = null;
  95352. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95353. this._onAfterActiveMeshesEvaluationObserver = null;
  95354. }
  95355. },
  95356. enumerable: true,
  95357. configurable: true
  95358. });
  95359. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95360. /**
  95361. * Gets the perf counter used for render targets render time
  95362. */
  95363. get: function () {
  95364. return this._renderTargetsRenderTime;
  95365. },
  95366. enumerable: true,
  95367. configurable: true
  95368. });
  95369. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95370. /**
  95371. * Gets the render targets render time capture status
  95372. */
  95373. get: function () {
  95374. return this._captureRenderTargetsRenderTime;
  95375. },
  95376. /**
  95377. * Enable or disable the render targets render time capture
  95378. */
  95379. set: function (value) {
  95380. var _this = this;
  95381. if (value === this._captureRenderTargetsRenderTime) {
  95382. return;
  95383. }
  95384. this._captureRenderTargetsRenderTime = value;
  95385. if (value) {
  95386. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95387. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95388. _this._renderTargetsRenderTime.beginMonitoring();
  95389. });
  95390. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95391. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95392. _this._renderTargetsRenderTime.endMonitoring(false);
  95393. });
  95394. }
  95395. else {
  95396. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95397. this._onBeforeRenderTargetsRenderObserver = null;
  95398. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95399. this._onAfterRenderTargetsRenderObserver = null;
  95400. }
  95401. },
  95402. enumerable: true,
  95403. configurable: true
  95404. });
  95405. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95406. /**
  95407. * Gets the perf counter used for particles render time
  95408. */
  95409. get: function () {
  95410. return this._particlesRenderTime;
  95411. },
  95412. enumerable: true,
  95413. configurable: true
  95414. });
  95415. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95416. /**
  95417. * Gets the particles render time capture status
  95418. */
  95419. get: function () {
  95420. return this._captureParticlesRenderTime;
  95421. },
  95422. /**
  95423. * Enable or disable the particles render time capture
  95424. */
  95425. set: function (value) {
  95426. var _this = this;
  95427. if (value === this._captureParticlesRenderTime) {
  95428. return;
  95429. }
  95430. this._captureParticlesRenderTime = value;
  95431. if (value) {
  95432. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95433. BABYLON.Tools.StartPerformanceCounter("Particles");
  95434. _this._particlesRenderTime.beginMonitoring();
  95435. });
  95436. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95437. BABYLON.Tools.EndPerformanceCounter("Particles");
  95438. _this._particlesRenderTime.endMonitoring(false);
  95439. });
  95440. }
  95441. else {
  95442. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95443. this._onBeforeParticlesRenderingObserver = null;
  95444. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95445. this._onAfterParticlesRenderingObserver = null;
  95446. }
  95447. },
  95448. enumerable: true,
  95449. configurable: true
  95450. });
  95451. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95452. /**
  95453. * Gets the perf counter used for sprites render time
  95454. */
  95455. get: function () {
  95456. return this._spritesRenderTime;
  95457. },
  95458. enumerable: true,
  95459. configurable: true
  95460. });
  95461. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95462. /**
  95463. * Gets the sprites render time capture status
  95464. */
  95465. get: function () {
  95466. return this._captureSpritesRenderTime;
  95467. },
  95468. /**
  95469. * Enable or disable the sprites render time capture
  95470. */
  95471. set: function (value) {
  95472. var _this = this;
  95473. if (value === this._captureSpritesRenderTime) {
  95474. return;
  95475. }
  95476. this._captureSpritesRenderTime = value;
  95477. if (value) {
  95478. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95479. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95480. _this._spritesRenderTime.beginMonitoring();
  95481. });
  95482. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95483. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95484. _this._spritesRenderTime.endMonitoring(false);
  95485. });
  95486. }
  95487. else {
  95488. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95489. this._onBeforeSpritesRenderingObserver = null;
  95490. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95491. this._onAfterSpritesRenderingObserver = null;
  95492. }
  95493. },
  95494. enumerable: true,
  95495. configurable: true
  95496. });
  95497. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95498. /**
  95499. * Gets the perf counter used for physics time
  95500. */
  95501. get: function () {
  95502. return this._physicsTime;
  95503. },
  95504. enumerable: true,
  95505. configurable: true
  95506. });
  95507. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95508. /**
  95509. * Gets the physics time capture status
  95510. */
  95511. get: function () {
  95512. return this._capturePhysicsTime;
  95513. },
  95514. /**
  95515. * Enable or disable the physics time capture
  95516. */
  95517. set: function (value) {
  95518. var _this = this;
  95519. if (value === this._capturePhysicsTime) {
  95520. return;
  95521. }
  95522. this._capturePhysicsTime = value;
  95523. if (value) {
  95524. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95525. BABYLON.Tools.StartPerformanceCounter("Physics");
  95526. _this._physicsTime.beginMonitoring();
  95527. });
  95528. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95529. BABYLON.Tools.EndPerformanceCounter("Physics");
  95530. _this._physicsTime.endMonitoring();
  95531. });
  95532. }
  95533. else {
  95534. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95535. this._onBeforePhysicsObserver = null;
  95536. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95537. this._onAfterPhysicsObserver = null;
  95538. }
  95539. },
  95540. enumerable: true,
  95541. configurable: true
  95542. });
  95543. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95544. /**
  95545. * Gets the perf counter used for animations time
  95546. */
  95547. get: function () {
  95548. return this._animationsTime;
  95549. },
  95550. enumerable: true,
  95551. configurable: true
  95552. });
  95553. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95554. /**
  95555. * Gets the animations time capture status
  95556. */
  95557. get: function () {
  95558. return this._captureAnimationsTime;
  95559. },
  95560. /**
  95561. * Enable or disable the animations time capture
  95562. */
  95563. set: function (value) {
  95564. var _this = this;
  95565. if (value === this._captureAnimationsTime) {
  95566. return;
  95567. }
  95568. this._captureAnimationsTime = value;
  95569. if (value) {
  95570. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95571. _this._animationsTime.endMonitoring();
  95572. });
  95573. }
  95574. else {
  95575. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95576. this._onAfterAnimationsObserver = null;
  95577. }
  95578. },
  95579. enumerable: true,
  95580. configurable: true
  95581. });
  95582. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95583. /**
  95584. * Gets the perf counter used for frame time capture
  95585. */
  95586. get: function () {
  95587. return this._frameTime;
  95588. },
  95589. enumerable: true,
  95590. configurable: true
  95591. });
  95592. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95593. /**
  95594. * Gets the frame time capture status
  95595. */
  95596. get: function () {
  95597. return this._captureFrameTime;
  95598. },
  95599. /**
  95600. * Enable or disable the frame time capture
  95601. */
  95602. set: function (value) {
  95603. this._captureFrameTime = value;
  95604. },
  95605. enumerable: true,
  95606. configurable: true
  95607. });
  95608. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95609. /**
  95610. * Gets the perf counter used for inter-frames time capture
  95611. */
  95612. get: function () {
  95613. return this._interFrameTime;
  95614. },
  95615. enumerable: true,
  95616. configurable: true
  95617. });
  95618. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95619. /**
  95620. * Gets the inter-frames time capture status
  95621. */
  95622. get: function () {
  95623. return this._captureInterFrameTime;
  95624. },
  95625. /**
  95626. * Enable or disable the inter-frames time capture
  95627. */
  95628. set: function (value) {
  95629. this._captureInterFrameTime = value;
  95630. },
  95631. enumerable: true,
  95632. configurable: true
  95633. });
  95634. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95635. /**
  95636. * Gets the perf counter used for render time capture
  95637. */
  95638. get: function () {
  95639. return this._renderTime;
  95640. },
  95641. enumerable: true,
  95642. configurable: true
  95643. });
  95644. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95645. /**
  95646. * Gets the render time capture status
  95647. */
  95648. get: function () {
  95649. return this._captureRenderTime;
  95650. },
  95651. /**
  95652. * Enable or disable the render time capture
  95653. */
  95654. set: function (value) {
  95655. var _this = this;
  95656. if (value === this._captureRenderTime) {
  95657. return;
  95658. }
  95659. this._captureRenderTime = value;
  95660. if (value) {
  95661. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95662. _this._renderTime.beginMonitoring();
  95663. BABYLON.Tools.StartPerformanceCounter("Main render");
  95664. });
  95665. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95666. _this._renderTime.endMonitoring(false);
  95667. BABYLON.Tools.EndPerformanceCounter("Main render");
  95668. });
  95669. }
  95670. else {
  95671. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95672. this._onBeforeDrawPhaseObserver = null;
  95673. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95674. this._onAfterDrawPhaseObserver = null;
  95675. }
  95676. },
  95677. enumerable: true,
  95678. configurable: true
  95679. });
  95680. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95681. /**
  95682. * Gets the perf counter used for draw calls
  95683. */
  95684. get: function () {
  95685. return this.scene.getEngine()._drawCalls;
  95686. },
  95687. enumerable: true,
  95688. configurable: true
  95689. });
  95690. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95691. /**
  95692. * Gets the perf counter used for texture collisions
  95693. */
  95694. get: function () {
  95695. return this.scene.getEngine()._textureCollisions;
  95696. },
  95697. enumerable: true,
  95698. configurable: true
  95699. });
  95700. SceneInstrumentation.prototype.dispose = function () {
  95701. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95702. this._onAfterRenderObserver = null;
  95703. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95704. this._onBeforeActiveMeshesEvaluationObserver = null;
  95705. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95706. this._onAfterActiveMeshesEvaluationObserver = null;
  95707. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95708. this._onBeforeRenderTargetsRenderObserver = null;
  95709. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95710. this._onAfterRenderTargetsRenderObserver = null;
  95711. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95712. this._onBeforeAnimationsObserver = null;
  95713. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95714. this._onBeforeParticlesRenderingObserver = null;
  95715. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95716. this._onAfterParticlesRenderingObserver = null;
  95717. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95718. this._onBeforeSpritesRenderingObserver = null;
  95719. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95720. this._onAfterSpritesRenderingObserver = null;
  95721. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95722. this._onBeforeDrawPhaseObserver = null;
  95723. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95724. this._onAfterDrawPhaseObserver = null;
  95725. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95726. this._onBeforePhysicsObserver = null;
  95727. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95728. this._onAfterPhysicsObserver = null;
  95729. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95730. this._onAfterAnimationsObserver = null;
  95731. this.scene = null;
  95732. };
  95733. return SceneInstrumentation;
  95734. }());
  95735. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95736. })(BABYLON || (BABYLON = {}));
  95737. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95738. var BABYLON;
  95739. (function (BABYLON) {
  95740. /**
  95741. * @hidden
  95742. **/
  95743. var _TimeToken = /** @class */ (function () {
  95744. function _TimeToken() {
  95745. this._timeElapsedQueryEnded = false;
  95746. }
  95747. return _TimeToken;
  95748. }());
  95749. BABYLON._TimeToken = _TimeToken;
  95750. })(BABYLON || (BABYLON = {}));
  95751. //# sourceMappingURL=babylon.timeToken.js.map
  95752. var BABYLON;
  95753. (function (BABYLON) {
  95754. /**
  95755. * Background material defines definition.
  95756. * @hidden Mainly internal Use
  95757. */
  95758. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95759. __extends(BackgroundMaterialDefines, _super);
  95760. /**
  95761. * Constructor of the defines.
  95762. */
  95763. function BackgroundMaterialDefines() {
  95764. var _this = _super.call(this) || this;
  95765. /**
  95766. * True if the diffuse texture is in use.
  95767. */
  95768. _this.DIFFUSE = false;
  95769. /**
  95770. * The direct UV channel to use.
  95771. */
  95772. _this.DIFFUSEDIRECTUV = 0;
  95773. /**
  95774. * True if the diffuse texture is in gamma space.
  95775. */
  95776. _this.GAMMADIFFUSE = false;
  95777. /**
  95778. * True if the diffuse texture has opacity in the alpha channel.
  95779. */
  95780. _this.DIFFUSEHASALPHA = false;
  95781. /**
  95782. * True if you want the material to fade to transparent at grazing angle.
  95783. */
  95784. _this.OPACITYFRESNEL = false;
  95785. /**
  95786. * True if an extra blur needs to be added in the reflection.
  95787. */
  95788. _this.REFLECTIONBLUR = false;
  95789. /**
  95790. * True if you want the material to fade to reflection at grazing angle.
  95791. */
  95792. _this.REFLECTIONFRESNEL = false;
  95793. /**
  95794. * True if you want the material to falloff as far as you move away from the scene center.
  95795. */
  95796. _this.REFLECTIONFALLOFF = false;
  95797. /**
  95798. * False if the current Webgl implementation does not support the texture lod extension.
  95799. */
  95800. _this.TEXTURELODSUPPORT = false;
  95801. /**
  95802. * True to ensure the data are premultiplied.
  95803. */
  95804. _this.PREMULTIPLYALPHA = false;
  95805. /**
  95806. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95807. */
  95808. _this.USERGBCOLOR = false;
  95809. /**
  95810. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95811. * stays aligned with the desired configuration.
  95812. */
  95813. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95814. /**
  95815. * True to add noise in order to reduce the banding effect.
  95816. */
  95817. _this.NOISE = false;
  95818. /**
  95819. * is the reflection texture in BGR color scheme?
  95820. * Mainly used to solve a bug in ios10 video tag
  95821. */
  95822. _this.REFLECTIONBGR = false;
  95823. _this.IMAGEPROCESSING = false;
  95824. _this.VIGNETTE = false;
  95825. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95826. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95827. _this.TONEMAPPING = false;
  95828. _this.CONTRAST = false;
  95829. _this.COLORCURVES = false;
  95830. _this.COLORGRADING = false;
  95831. _this.COLORGRADING3D = false;
  95832. _this.SAMPLER3DGREENDEPTH = false;
  95833. _this.SAMPLER3DBGRMAP = false;
  95834. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95835. _this.EXPOSURE = false;
  95836. // Reflection.
  95837. _this.REFLECTION = false;
  95838. _this.REFLECTIONMAP_3D = false;
  95839. _this.REFLECTIONMAP_SPHERICAL = false;
  95840. _this.REFLECTIONMAP_PLANAR = false;
  95841. _this.REFLECTIONMAP_CUBIC = false;
  95842. _this.REFLECTIONMAP_PROJECTION = false;
  95843. _this.REFLECTIONMAP_SKYBOX = false;
  95844. _this.REFLECTIONMAP_EXPLICIT = false;
  95845. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95846. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95847. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95848. _this.INVERTCUBICMAP = false;
  95849. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95850. _this.LODINREFLECTIONALPHA = false;
  95851. _this.GAMMAREFLECTION = false;
  95852. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95853. // Default BJS.
  95854. _this.MAINUV1 = false;
  95855. _this.MAINUV2 = false;
  95856. _this.UV1 = false;
  95857. _this.UV2 = false;
  95858. _this.CLIPPLANE = false;
  95859. _this.POINTSIZE = false;
  95860. _this.FOG = false;
  95861. _this.NORMAL = false;
  95862. _this.NUM_BONE_INFLUENCERS = 0;
  95863. _this.BonesPerMesh = 0;
  95864. _this.INSTANCES = false;
  95865. _this.SHADOWFLOAT = false;
  95866. _this.rebuild();
  95867. return _this;
  95868. }
  95869. return BackgroundMaterialDefines;
  95870. }(BABYLON.MaterialDefines));
  95871. /**
  95872. * Background material used to create an efficient environement around your scene.
  95873. */
  95874. var BackgroundMaterial = /** @class */ (function (_super) {
  95875. __extends(BackgroundMaterial, _super);
  95876. /**
  95877. * Instantiates a Background Material in the given scene
  95878. * @param name The friendly name of the material
  95879. * @param scene The scene to add the material to
  95880. */
  95881. function BackgroundMaterial(name, scene) {
  95882. var _this = _super.call(this, name, scene) || this;
  95883. /**
  95884. * Key light Color (multiply against the environement texture)
  95885. */
  95886. _this.primaryColor = BABYLON.Color3.White();
  95887. _this._primaryColorShadowLevel = 0;
  95888. _this._primaryColorHighlightLevel = 0;
  95889. /**
  95890. * Reflection Texture used in the material.
  95891. * Should be author in a specific way for the best result (refer to the documentation).
  95892. */
  95893. _this.reflectionTexture = null;
  95894. /**
  95895. * Reflection Texture level of blur.
  95896. *
  95897. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  95898. * texture twice.
  95899. */
  95900. _this.reflectionBlur = 0;
  95901. /**
  95902. * Diffuse Texture used in the material.
  95903. * Should be author in a specific way for the best result (refer to the documentation).
  95904. */
  95905. _this.diffuseTexture = null;
  95906. _this._shadowLights = null;
  95907. /**
  95908. * Specify the list of lights casting shadow on the material.
  95909. * All scene shadow lights will be included if null.
  95910. */
  95911. _this.shadowLights = null;
  95912. /**
  95913. * Helps adjusting the shadow to a softer level if required.
  95914. * 0 means black shadows and 1 means no shadows.
  95915. */
  95916. _this.shadowLevel = 0;
  95917. /**
  95918. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  95919. * It is usually zero but might be interesting to modify according to your setup.
  95920. */
  95921. _this.sceneCenter = BABYLON.Vector3.Zero();
  95922. /**
  95923. * This helps specifying that the material is falling off to the sky box at grazing angle.
  95924. * This helps ensuring a nice transition when the camera goes under the ground.
  95925. */
  95926. _this.opacityFresnel = true;
  95927. /**
  95928. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  95929. * This helps adding a mirror texture on the ground.
  95930. */
  95931. _this.reflectionFresnel = false;
  95932. /**
  95933. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  95934. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  95935. */
  95936. _this.reflectionFalloffDistance = 0.0;
  95937. /**
  95938. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  95939. */
  95940. _this.reflectionAmount = 1.0;
  95941. /**
  95942. * This specifies the weight of the reflection at grazing angle.
  95943. */
  95944. _this.reflectionReflectance0 = 0.05;
  95945. /**
  95946. * This specifies the weight of the reflection at a perpendicular point of view.
  95947. */
  95948. _this.reflectionReflectance90 = 0.5;
  95949. /**
  95950. * Helps to directly use the maps channels instead of their level.
  95951. */
  95952. _this.useRGBColor = true;
  95953. /**
  95954. * This helps reducing the banding effect that could occur on the background.
  95955. */
  95956. _this.enableNoise = false;
  95957. _this._fovMultiplier = 1.0;
  95958. /**
  95959. * Enable the FOV adjustment feature controlled by fovMultiplier.
  95960. */
  95961. _this.useEquirectangularFOV = false;
  95962. _this._maxSimultaneousLights = 4;
  95963. /**
  95964. * Number of Simultaneous lights allowed on the material.
  95965. */
  95966. _this.maxSimultaneousLights = 4;
  95967. /**
  95968. * Keep track of the image processing observer to allow dispose and replace.
  95969. */
  95970. _this._imageProcessingObserver = null;
  95971. /**
  95972. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  95973. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  95974. */
  95975. _this.switchToBGR = false;
  95976. // Temp values kept as cache in the material.
  95977. _this._renderTargets = new BABYLON.SmartArray(16);
  95978. _this._reflectionControls = BABYLON.Vector4.Zero();
  95979. _this._white = BABYLON.Color3.White();
  95980. _this._primaryShadowColor = BABYLON.Color3.Black();
  95981. _this._primaryHighlightColor = BABYLON.Color3.Black();
  95982. // Setup the default processing configuration to the scene.
  95983. _this._attachImageProcessingConfiguration(null);
  95984. _this.getRenderTargetTextures = function () {
  95985. _this._renderTargets.reset();
  95986. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  95987. _this._renderTargets.push(_this._diffuseTexture);
  95988. }
  95989. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  95990. _this._renderTargets.push(_this._reflectionTexture);
  95991. }
  95992. return _this._renderTargets;
  95993. };
  95994. return _this;
  95995. }
  95996. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  95997. /**
  95998. * Experimental Internal Use Only.
  95999. *
  96000. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96001. * This acts as a helper to set the primary color to a more "human friendly" value.
  96002. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96003. * output color as close as possible from the chosen value.
  96004. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96005. * part of lighting setup.)
  96006. */
  96007. get: function () {
  96008. return this.__perceptualColor;
  96009. },
  96010. set: function (value) {
  96011. this.__perceptualColor = value;
  96012. this._computePrimaryColorFromPerceptualColor();
  96013. this._markAllSubMeshesAsLightsDirty();
  96014. },
  96015. enumerable: true,
  96016. configurable: true
  96017. });
  96018. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96019. /**
  96020. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96021. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96022. */
  96023. get: function () {
  96024. return this._primaryColorShadowLevel;
  96025. },
  96026. set: function (value) {
  96027. this._primaryColorShadowLevel = value;
  96028. this._computePrimaryColors();
  96029. this._markAllSubMeshesAsLightsDirty();
  96030. },
  96031. enumerable: true,
  96032. configurable: true
  96033. });
  96034. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96035. /**
  96036. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96037. * The primary color is used at the level chosen to define what the white area would look.
  96038. */
  96039. get: function () {
  96040. return this._primaryColorHighlightLevel;
  96041. },
  96042. set: function (value) {
  96043. this._primaryColorHighlightLevel = value;
  96044. this._computePrimaryColors();
  96045. this._markAllSubMeshesAsLightsDirty();
  96046. },
  96047. enumerable: true,
  96048. configurable: true
  96049. });
  96050. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96051. /**
  96052. * Sets the reflection reflectance fresnel values according to the default standard
  96053. * empirically know to work well :-)
  96054. */
  96055. set: function (value) {
  96056. var reflectionWeight = value;
  96057. if (reflectionWeight < 0.5) {
  96058. reflectionWeight = reflectionWeight * 2.0;
  96059. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96060. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96061. }
  96062. else {
  96063. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96064. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96065. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96066. }
  96067. },
  96068. enumerable: true,
  96069. configurable: true
  96070. });
  96071. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96072. /**
  96073. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96074. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96075. * Recommended to be keep at 1.0 except for special cases.
  96076. */
  96077. get: function () {
  96078. return this._fovMultiplier;
  96079. },
  96080. set: function (value) {
  96081. if (isNaN(value)) {
  96082. value = 1.0;
  96083. }
  96084. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96085. },
  96086. enumerable: true,
  96087. configurable: true
  96088. });
  96089. /**
  96090. * Attaches a new image processing configuration to the PBR Material.
  96091. * @param configuration (if null the scene configuration will be use)
  96092. */
  96093. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96094. var _this = this;
  96095. if (configuration === this._imageProcessingConfiguration) {
  96096. return;
  96097. }
  96098. // Detaches observer.
  96099. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96100. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96101. }
  96102. // Pick the scene configuration if needed.
  96103. if (!configuration) {
  96104. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96105. }
  96106. else {
  96107. this._imageProcessingConfiguration = configuration;
  96108. }
  96109. // Attaches observer.
  96110. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96111. _this._computePrimaryColorFromPerceptualColor();
  96112. _this._markAllSubMeshesAsImageProcessingDirty();
  96113. });
  96114. };
  96115. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96116. /**
  96117. * Gets the image processing configuration used either in this material.
  96118. */
  96119. get: function () {
  96120. return this._imageProcessingConfiguration;
  96121. },
  96122. /**
  96123. * Sets the Default image processing configuration used either in the this material.
  96124. *
  96125. * If sets to null, the scene one is in use.
  96126. */
  96127. set: function (value) {
  96128. this._attachImageProcessingConfiguration(value);
  96129. // Ensure the effect will be rebuilt.
  96130. this._markAllSubMeshesAsTexturesDirty();
  96131. },
  96132. enumerable: true,
  96133. configurable: true
  96134. });
  96135. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96136. /**
  96137. * Gets wether the color curves effect is enabled.
  96138. */
  96139. get: function () {
  96140. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96141. },
  96142. /**
  96143. * Sets wether the color curves effect is enabled.
  96144. */
  96145. set: function (value) {
  96146. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96147. },
  96148. enumerable: true,
  96149. configurable: true
  96150. });
  96151. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96152. /**
  96153. * Gets wether the color grading effect is enabled.
  96154. */
  96155. get: function () {
  96156. return this.imageProcessingConfiguration.colorGradingEnabled;
  96157. },
  96158. /**
  96159. * Gets wether the color grading effect is enabled.
  96160. */
  96161. set: function (value) {
  96162. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96163. },
  96164. enumerable: true,
  96165. configurable: true
  96166. });
  96167. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96168. /**
  96169. * Gets wether tonemapping is enabled or not.
  96170. */
  96171. get: function () {
  96172. return this._imageProcessingConfiguration.toneMappingEnabled;
  96173. },
  96174. /**
  96175. * Sets wether tonemapping is enabled or not
  96176. */
  96177. set: function (value) {
  96178. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96179. },
  96180. enumerable: true,
  96181. configurable: true
  96182. });
  96183. ;
  96184. ;
  96185. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96186. /**
  96187. * The camera exposure used on this material.
  96188. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96189. * This corresponds to a photographic exposure.
  96190. */
  96191. get: function () {
  96192. return this._imageProcessingConfiguration.exposure;
  96193. },
  96194. /**
  96195. * The camera exposure used on this material.
  96196. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96197. * This corresponds to a photographic exposure.
  96198. */
  96199. set: function (value) {
  96200. this._imageProcessingConfiguration.exposure = value;
  96201. },
  96202. enumerable: true,
  96203. configurable: true
  96204. });
  96205. ;
  96206. ;
  96207. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96208. /**
  96209. * Gets The camera contrast used on this material.
  96210. */
  96211. get: function () {
  96212. return this._imageProcessingConfiguration.contrast;
  96213. },
  96214. /**
  96215. * Sets The camera contrast used on this material.
  96216. */
  96217. set: function (value) {
  96218. this._imageProcessingConfiguration.contrast = value;
  96219. },
  96220. enumerable: true,
  96221. configurable: true
  96222. });
  96223. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96224. /**
  96225. * Gets the Color Grading 2D Lookup Texture.
  96226. */
  96227. get: function () {
  96228. return this._imageProcessingConfiguration.colorGradingTexture;
  96229. },
  96230. /**
  96231. * Sets the Color Grading 2D Lookup Texture.
  96232. */
  96233. set: function (value) {
  96234. this.imageProcessingConfiguration.colorGradingTexture = value;
  96235. },
  96236. enumerable: true,
  96237. configurable: true
  96238. });
  96239. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96240. /**
  96241. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96242. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96243. * 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;
  96244. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96245. */
  96246. get: function () {
  96247. return this.imageProcessingConfiguration.colorCurves;
  96248. },
  96249. /**
  96250. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96251. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96252. * 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;
  96253. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96254. */
  96255. set: function (value) {
  96256. this.imageProcessingConfiguration.colorCurves = value;
  96257. },
  96258. enumerable: true,
  96259. configurable: true
  96260. });
  96261. /**
  96262. * The entire material has been created in order to prevent overdraw.
  96263. * @returns false
  96264. */
  96265. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96266. return true;
  96267. };
  96268. /**
  96269. * The entire material has been created in order to prevent overdraw.
  96270. * @returns true if blending is enable
  96271. */
  96272. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96273. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96274. };
  96275. /**
  96276. * Checks wether the material is ready to be rendered for a given mesh.
  96277. * @param mesh The mesh to render
  96278. * @param subMesh The submesh to check against
  96279. * @param useInstances Specify wether or not the material is used with instances
  96280. * @returns true if all the dependencies are ready (Textures, Effects...)
  96281. */
  96282. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96283. var _this = this;
  96284. if (useInstances === void 0) { useInstances = false; }
  96285. if (subMesh.effect && this.isFrozen) {
  96286. if (this._wasPreviouslyReady) {
  96287. return true;
  96288. }
  96289. }
  96290. if (!subMesh._materialDefines) {
  96291. subMesh._materialDefines = new BackgroundMaterialDefines();
  96292. }
  96293. var scene = this.getScene();
  96294. var defines = subMesh._materialDefines;
  96295. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96296. if (defines._renderId === scene.getRenderId()) {
  96297. return true;
  96298. }
  96299. }
  96300. var engine = scene.getEngine();
  96301. // Lights
  96302. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96303. defines._needNormals = true;
  96304. // Textures
  96305. if (defines._areTexturesDirty) {
  96306. defines._needUVs = false;
  96307. if (scene.texturesEnabled) {
  96308. if (scene.getEngine().getCaps().textureLOD) {
  96309. defines.TEXTURELODSUPPORT = true;
  96310. }
  96311. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96312. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96313. return false;
  96314. }
  96315. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96316. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96317. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96318. defines.OPACITYFRESNEL = this._opacityFresnel;
  96319. }
  96320. else {
  96321. defines.DIFFUSE = false;
  96322. defines.DIFFUSEHASALPHA = false;
  96323. defines.GAMMADIFFUSE = false;
  96324. defines.OPACITYFRESNEL = false;
  96325. }
  96326. var reflectionTexture = this._reflectionTexture;
  96327. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96328. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96329. return false;
  96330. }
  96331. defines.REFLECTION = true;
  96332. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96333. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96334. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96335. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96336. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96337. defines.REFLECTIONBGR = this.switchToBGR;
  96338. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96339. defines.INVERTCUBICMAP = true;
  96340. }
  96341. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96342. switch (reflectionTexture.coordinatesMode) {
  96343. case BABYLON.Texture.EXPLICIT_MODE:
  96344. defines.REFLECTIONMAP_EXPLICIT = true;
  96345. break;
  96346. case BABYLON.Texture.PLANAR_MODE:
  96347. defines.REFLECTIONMAP_PLANAR = true;
  96348. break;
  96349. case BABYLON.Texture.PROJECTION_MODE:
  96350. defines.REFLECTIONMAP_PROJECTION = true;
  96351. break;
  96352. case BABYLON.Texture.SKYBOX_MODE:
  96353. defines.REFLECTIONMAP_SKYBOX = true;
  96354. break;
  96355. case BABYLON.Texture.SPHERICAL_MODE:
  96356. defines.REFLECTIONMAP_SPHERICAL = true;
  96357. break;
  96358. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96359. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96360. break;
  96361. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96362. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96363. break;
  96364. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96365. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96366. break;
  96367. case BABYLON.Texture.CUBIC_MODE:
  96368. case BABYLON.Texture.INVCUBIC_MODE:
  96369. default:
  96370. defines.REFLECTIONMAP_CUBIC = true;
  96371. break;
  96372. }
  96373. if (this.reflectionFresnel) {
  96374. defines.REFLECTIONFRESNEL = true;
  96375. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96376. this._reflectionControls.x = this.reflectionAmount;
  96377. this._reflectionControls.y = this.reflectionReflectance0;
  96378. this._reflectionControls.z = this.reflectionReflectance90;
  96379. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96380. }
  96381. else {
  96382. defines.REFLECTIONFRESNEL = false;
  96383. defines.REFLECTIONFALLOFF = false;
  96384. }
  96385. }
  96386. else {
  96387. defines.REFLECTION = false;
  96388. defines.REFLECTIONFRESNEL = false;
  96389. defines.REFLECTIONFALLOFF = false;
  96390. defines.REFLECTIONBLUR = false;
  96391. defines.REFLECTIONMAP_3D = false;
  96392. defines.REFLECTIONMAP_SPHERICAL = false;
  96393. defines.REFLECTIONMAP_PLANAR = false;
  96394. defines.REFLECTIONMAP_CUBIC = false;
  96395. defines.REFLECTIONMAP_PROJECTION = false;
  96396. defines.REFLECTIONMAP_SKYBOX = false;
  96397. defines.REFLECTIONMAP_EXPLICIT = false;
  96398. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96399. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96400. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96401. defines.INVERTCUBICMAP = false;
  96402. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96403. defines.LODINREFLECTIONALPHA = false;
  96404. defines.GAMMAREFLECTION = false;
  96405. }
  96406. }
  96407. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96408. defines.USERGBCOLOR = this._useRGBColor;
  96409. defines.NOISE = this._enableNoise;
  96410. }
  96411. if (defines._areLightsDirty) {
  96412. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96413. }
  96414. if (defines._areImageProcessingDirty) {
  96415. if (!this._imageProcessingConfiguration.isReady()) {
  96416. return false;
  96417. }
  96418. this._imageProcessingConfiguration.prepareDefines(defines);
  96419. }
  96420. // Misc.
  96421. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96422. // Values that need to be evaluated on every frame
  96423. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96424. // Attribs
  96425. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96426. if (mesh) {
  96427. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96428. mesh.createNormals(true);
  96429. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96430. }
  96431. }
  96432. }
  96433. // Get correct effect
  96434. if (defines.isDirty) {
  96435. defines.markAsProcessed();
  96436. scene.resetCachedMaterial();
  96437. // Fallbacks
  96438. var fallbacks = new BABYLON.EffectFallbacks();
  96439. if (defines.FOG) {
  96440. fallbacks.addFallback(0, "FOG");
  96441. }
  96442. if (defines.POINTSIZE) {
  96443. fallbacks.addFallback(1, "POINTSIZE");
  96444. }
  96445. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96446. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96447. fallbacks.addCPUSkinningFallback(0, mesh);
  96448. }
  96449. //Attributes
  96450. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96451. if (defines.NORMAL) {
  96452. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96453. }
  96454. if (defines.UV1) {
  96455. attribs.push(BABYLON.VertexBuffer.UVKind);
  96456. }
  96457. if (defines.UV2) {
  96458. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96459. }
  96460. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96461. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96462. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96463. "vFogInfos", "vFogColor", "pointSize",
  96464. "vClipPlane", "mBones",
  96465. "vPrimaryColor", "vPrimaryColorShadow",
  96466. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96467. "shadowLevel", "alpha",
  96468. "vBackgroundCenter", "vReflectionControl",
  96469. "vDiffuseInfos", "diffuseMatrix",
  96470. ];
  96471. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96472. var uniformBuffers = ["Material", "Scene"];
  96473. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96474. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96475. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96476. uniformsNames: uniforms,
  96477. uniformBuffersNames: uniformBuffers,
  96478. samplers: samplers,
  96479. defines: defines,
  96480. maxSimultaneousLights: this._maxSimultaneousLights
  96481. });
  96482. var onCompiled = function (effect) {
  96483. if (_this.onCompiled) {
  96484. _this.onCompiled(effect);
  96485. }
  96486. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96487. };
  96488. var join = defines.toString();
  96489. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96490. attributes: attribs,
  96491. uniformsNames: uniforms,
  96492. uniformBuffersNames: uniformBuffers,
  96493. samplers: samplers,
  96494. defines: join,
  96495. fallbacks: fallbacks,
  96496. onCompiled: onCompiled,
  96497. onError: this.onError,
  96498. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96499. }, engine), defines);
  96500. this.buildUniformLayout();
  96501. }
  96502. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96503. return false;
  96504. }
  96505. defines._renderId = scene.getRenderId();
  96506. this._wasPreviouslyReady = true;
  96507. return true;
  96508. };
  96509. /**
  96510. * Compute the primary color according to the chosen perceptual color.
  96511. */
  96512. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96513. if (!this.__perceptualColor) {
  96514. return;
  96515. }
  96516. this._primaryColor.copyFrom(this.__perceptualColor);
  96517. // Revert gamma space.
  96518. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96519. // Revert image processing configuration.
  96520. if (this._imageProcessingConfiguration) {
  96521. // Revert Exposure.
  96522. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96523. }
  96524. this._computePrimaryColors();
  96525. };
  96526. /**
  96527. * Compute the highlights and shadow colors according to their chosen levels.
  96528. */
  96529. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96530. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96531. return;
  96532. }
  96533. // Find the highlight color based on the configuration.
  96534. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96535. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96536. // Find the shadow color based on the configuration.
  96537. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96538. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96539. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96540. };
  96541. /**
  96542. * Build the uniform buffer used in the material.
  96543. */
  96544. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96545. // Order is important !
  96546. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96547. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96548. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96549. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96550. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96551. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96552. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96553. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96554. this._uniformBuffer.addUniform("pointSize", 1);
  96555. this._uniformBuffer.addUniform("shadowLevel", 1);
  96556. this._uniformBuffer.addUniform("alpha", 1);
  96557. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96558. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96559. this._uniformBuffer.create();
  96560. };
  96561. /**
  96562. * Unbind the material.
  96563. */
  96564. BackgroundMaterial.prototype.unbind = function () {
  96565. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96566. this._uniformBuffer.setTexture("diffuseSampler", null);
  96567. }
  96568. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96569. this._uniformBuffer.setTexture("reflectionSampler", null);
  96570. }
  96571. _super.prototype.unbind.call(this);
  96572. };
  96573. /**
  96574. * Bind only the world matrix to the material.
  96575. * @param world The world matrix to bind.
  96576. */
  96577. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96578. this._activeEffect.setMatrix("world", world);
  96579. };
  96580. /**
  96581. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96582. * @param world The world matrix to bind.
  96583. * @param subMesh The submesh to bind for.
  96584. */
  96585. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96586. var scene = this.getScene();
  96587. var defines = subMesh._materialDefines;
  96588. if (!defines) {
  96589. return;
  96590. }
  96591. var effect = subMesh.effect;
  96592. if (!effect) {
  96593. return;
  96594. }
  96595. this._activeEffect = effect;
  96596. // Matrices
  96597. this.bindOnlyWorldMatrix(world);
  96598. // Bones
  96599. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96600. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96601. if (mustRebind) {
  96602. this._uniformBuffer.bindToEffect(effect, "Material");
  96603. this.bindViewProjection(effect);
  96604. var reflectionTexture = this._reflectionTexture;
  96605. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96606. // Texture uniforms
  96607. if (scene.texturesEnabled) {
  96608. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96609. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96610. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96611. }
  96612. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96613. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96614. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96615. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96616. }
  96617. }
  96618. if (this.shadowLevel > 0) {
  96619. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96620. }
  96621. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96622. // Point size
  96623. if (this.pointsCloud) {
  96624. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96625. }
  96626. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96627. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96628. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96629. }
  96630. else {
  96631. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96632. }
  96633. }
  96634. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96635. // Textures
  96636. if (scene.texturesEnabled) {
  96637. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96638. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96639. }
  96640. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96641. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96642. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96643. }
  96644. else if (!defines.REFLECTIONBLUR) {
  96645. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96646. }
  96647. else {
  96648. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96649. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96650. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96651. }
  96652. if (defines.REFLECTIONFRESNEL) {
  96653. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96654. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96655. }
  96656. }
  96657. }
  96658. // Clip plane
  96659. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96660. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96661. }
  96662. if (mustRebind || !this.isFrozen) {
  96663. if (scene.lightsEnabled) {
  96664. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96665. }
  96666. // View
  96667. this.bindView(effect);
  96668. // Fog
  96669. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96670. // image processing
  96671. this._imageProcessingConfiguration.bind(this._activeEffect);
  96672. }
  96673. this._uniformBuffer.update();
  96674. this._afterBind(mesh);
  96675. };
  96676. /**
  96677. * Dispose the material.
  96678. * @param forceDisposeEffect Force disposal of the associated effect.
  96679. * @param forceDisposeTextures Force disposal of the associated textures.
  96680. */
  96681. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96682. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96683. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96684. if (forceDisposeTextures) {
  96685. if (this.diffuseTexture) {
  96686. this.diffuseTexture.dispose();
  96687. }
  96688. if (this.reflectionTexture) {
  96689. this.reflectionTexture.dispose();
  96690. }
  96691. }
  96692. this._renderTargets.dispose();
  96693. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96694. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96695. }
  96696. _super.prototype.dispose.call(this, forceDisposeEffect);
  96697. };
  96698. /**
  96699. * Clones the material.
  96700. * @param name The cloned name.
  96701. * @returns The cloned material.
  96702. */
  96703. BackgroundMaterial.prototype.clone = function (name) {
  96704. var _this = this;
  96705. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96706. };
  96707. /**
  96708. * Serializes the current material to its JSON representation.
  96709. * @returns The JSON representation.
  96710. */
  96711. BackgroundMaterial.prototype.serialize = function () {
  96712. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96713. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96714. return serializationObject;
  96715. };
  96716. /**
  96717. * Gets the class name of the material
  96718. * @returns "BackgroundMaterial"
  96719. */
  96720. BackgroundMaterial.prototype.getClassName = function () {
  96721. return "BackgroundMaterial";
  96722. };
  96723. /**
  96724. * Parse a JSON input to create back a background material.
  96725. * @param source The JSON data to parse
  96726. * @param scene The scene to create the parsed material in
  96727. * @param rootUrl The root url of the assets the material depends upon
  96728. * @returns the instantiated BackgroundMaterial.
  96729. */
  96730. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96731. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96732. };
  96733. /**
  96734. * Standard reflectance value at parallel view angle.
  96735. */
  96736. BackgroundMaterial.StandardReflectance0 = 0.05;
  96737. /**
  96738. * Standard reflectance value at grazing angle.
  96739. */
  96740. BackgroundMaterial.StandardReflectance90 = 0.5;
  96741. __decorate([
  96742. BABYLON.serializeAsColor3()
  96743. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96744. __decorate([
  96745. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96746. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96747. __decorate([
  96748. BABYLON.serializeAsColor3()
  96749. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96750. __decorate([
  96751. BABYLON.serialize()
  96752. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96753. __decorate([
  96754. BABYLON.serialize()
  96755. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96756. __decorate([
  96757. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96758. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96759. __decorate([
  96760. BABYLON.serializeAsTexture()
  96761. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96762. __decorate([
  96763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96764. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96765. __decorate([
  96766. BABYLON.serialize()
  96767. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96768. __decorate([
  96769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96770. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96771. __decorate([
  96772. BABYLON.serializeAsTexture()
  96773. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96774. __decorate([
  96775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96776. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96777. __decorate([
  96778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96779. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96780. __decorate([
  96781. BABYLON.serialize()
  96782. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96783. __decorate([
  96784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96785. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96786. __decorate([
  96787. BABYLON.serializeAsVector3()
  96788. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96789. __decorate([
  96790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96791. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96792. __decorate([
  96793. BABYLON.serialize()
  96794. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96795. __decorate([
  96796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96797. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96798. __decorate([
  96799. BABYLON.serialize()
  96800. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96801. __decorate([
  96802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96803. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96804. __decorate([
  96805. BABYLON.serialize()
  96806. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96807. __decorate([
  96808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96809. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96810. __decorate([
  96811. BABYLON.serialize()
  96812. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96813. __decorate([
  96814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96815. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96816. __decorate([
  96817. BABYLON.serialize()
  96818. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96819. __decorate([
  96820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96821. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96822. __decorate([
  96823. BABYLON.serialize()
  96824. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96825. __decorate([
  96826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96827. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96828. __decorate([
  96829. BABYLON.serialize()
  96830. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96831. __decorate([
  96832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96833. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96834. __decorate([
  96835. BABYLON.serialize()
  96836. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96837. __decorate([
  96838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96839. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96840. __decorate([
  96841. BABYLON.serialize()
  96842. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96843. __decorate([
  96844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96845. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96846. __decorate([
  96847. BABYLON.serializeAsImageProcessingConfiguration()
  96848. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96849. return BackgroundMaterial;
  96850. }(BABYLON.PushMaterial));
  96851. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96852. })(BABYLON || (BABYLON = {}));
  96853. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96854. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96855. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96856. s = arguments[i];
  96857. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96858. t[p] = s[p];
  96859. }
  96860. return t;
  96861. };
  96862. var BABYLON;
  96863. (function (BABYLON) {
  96864. /**
  96865. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  96866. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  96867. * It also helps with the default setup of your imageProcessing configuration.
  96868. */
  96869. var EnvironmentHelper = /** @class */ (function () {
  96870. /**
  96871. * constructor
  96872. * @param options
  96873. * @param scene The scene to add the material to
  96874. */
  96875. function EnvironmentHelper(options, scene) {
  96876. var _this = this;
  96877. this._errorHandler = function (message, exception) {
  96878. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  96879. };
  96880. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  96881. this._scene = scene;
  96882. this.onErrorObservable = new BABYLON.Observable();
  96883. this._setupBackground();
  96884. this._setupImageProcessing();
  96885. }
  96886. /**
  96887. * Creates the default options for the helper.
  96888. */
  96889. EnvironmentHelper._getDefaultOptions = function () {
  96890. return {
  96891. createGround: true,
  96892. groundSize: 15,
  96893. groundTexture: this._groundTextureCDNUrl,
  96894. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96895. groundOpacity: 0.9,
  96896. enableGroundShadow: true,
  96897. groundShadowLevel: 0.5,
  96898. enableGroundMirror: false,
  96899. groundMirrorSizeRatio: 0.3,
  96900. groundMirrorBlurKernel: 64,
  96901. groundMirrorAmount: 1,
  96902. groundMirrorFresnelWeight: 1,
  96903. groundMirrorFallOffDistance: 0,
  96904. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  96905. groundYBias: 0.00001,
  96906. createSkybox: true,
  96907. skyboxSize: 20,
  96908. skyboxTexture: this._skyboxTextureCDNUrl,
  96909. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96910. backgroundYRotation: 0,
  96911. sizeAuto: true,
  96912. rootPosition: BABYLON.Vector3.Zero(),
  96913. setupImageProcessing: true,
  96914. environmentTexture: this._environmentTextureCDNUrl,
  96915. cameraExposure: 0.8,
  96916. cameraContrast: 1.2,
  96917. toneMappingEnabled: true,
  96918. };
  96919. };
  96920. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  96921. /**
  96922. * Gets the root mesh created by the helper.
  96923. */
  96924. get: function () {
  96925. return this._rootMesh;
  96926. },
  96927. enumerable: true,
  96928. configurable: true
  96929. });
  96930. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  96931. /**
  96932. * Gets the skybox created by the helper.
  96933. */
  96934. get: function () {
  96935. return this._skybox;
  96936. },
  96937. enumerable: true,
  96938. configurable: true
  96939. });
  96940. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  96941. /**
  96942. * Gets the skybox texture created by the helper.
  96943. */
  96944. get: function () {
  96945. return this._skyboxTexture;
  96946. },
  96947. enumerable: true,
  96948. configurable: true
  96949. });
  96950. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  96951. /**
  96952. * Gets the skybox material created by the helper.
  96953. */
  96954. get: function () {
  96955. return this._skyboxMaterial;
  96956. },
  96957. enumerable: true,
  96958. configurable: true
  96959. });
  96960. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  96961. /**
  96962. * Gets the ground mesh created by the helper.
  96963. */
  96964. get: function () {
  96965. return this._ground;
  96966. },
  96967. enumerable: true,
  96968. configurable: true
  96969. });
  96970. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  96971. /**
  96972. * Gets the ground texture created by the helper.
  96973. */
  96974. get: function () {
  96975. return this._groundTexture;
  96976. },
  96977. enumerable: true,
  96978. configurable: true
  96979. });
  96980. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  96981. /**
  96982. * Gets the ground mirror created by the helper.
  96983. */
  96984. get: function () {
  96985. return this._groundMirror;
  96986. },
  96987. enumerable: true,
  96988. configurable: true
  96989. });
  96990. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  96991. /**
  96992. * Gets the ground mirror render list to helps pushing the meshes
  96993. * you wish in the ground reflection.
  96994. */
  96995. get: function () {
  96996. if (this._groundMirror) {
  96997. return this._groundMirror.renderList;
  96998. }
  96999. return null;
  97000. },
  97001. enumerable: true,
  97002. configurable: true
  97003. });
  97004. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97005. /**
  97006. * Gets the ground material created by the helper.
  97007. */
  97008. get: function () {
  97009. return this._groundMaterial;
  97010. },
  97011. enumerable: true,
  97012. configurable: true
  97013. });
  97014. /**
  97015. * Updates the background according to the new options
  97016. * @param options
  97017. */
  97018. EnvironmentHelper.prototype.updateOptions = function (options) {
  97019. var newOptions = __assign({}, this._options, options);
  97020. if (this._ground && !newOptions.createGround) {
  97021. this._ground.dispose();
  97022. this._ground = null;
  97023. }
  97024. if (this._groundMaterial && !newOptions.createGround) {
  97025. this._groundMaterial.dispose();
  97026. this._groundMaterial = null;
  97027. }
  97028. if (this._groundTexture) {
  97029. if (this._options.groundTexture != newOptions.groundTexture) {
  97030. this._groundTexture.dispose();
  97031. this._groundTexture = null;
  97032. }
  97033. }
  97034. if (this._skybox && !newOptions.createSkybox) {
  97035. this._skybox.dispose();
  97036. this._skybox = null;
  97037. }
  97038. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97039. this._skyboxMaterial.dispose();
  97040. this._skyboxMaterial = null;
  97041. }
  97042. if (this._skyboxTexture) {
  97043. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97044. this._skyboxTexture.dispose();
  97045. this._skyboxTexture = null;
  97046. }
  97047. }
  97048. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97049. this._groundMirror.dispose();
  97050. this._groundMirror = null;
  97051. }
  97052. if (this._scene.environmentTexture) {
  97053. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97054. this._scene.environmentTexture.dispose();
  97055. }
  97056. }
  97057. this._options = newOptions;
  97058. this._setupBackground();
  97059. this._setupImageProcessing();
  97060. };
  97061. /**
  97062. * Sets the primary color of all the available elements.
  97063. * @param color the main color to affect to the ground and the background
  97064. */
  97065. EnvironmentHelper.prototype.setMainColor = function (color) {
  97066. if (this.groundMaterial) {
  97067. this.groundMaterial.primaryColor = color;
  97068. }
  97069. if (this.skyboxMaterial) {
  97070. this.skyboxMaterial.primaryColor = color;
  97071. }
  97072. if (this.groundMirror) {
  97073. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97074. }
  97075. };
  97076. /**
  97077. * Setup the image processing according to the specified options.
  97078. */
  97079. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97080. if (this._options.setupImageProcessing) {
  97081. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97082. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97083. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97084. this._setupEnvironmentTexture();
  97085. }
  97086. };
  97087. /**
  97088. * Setup the environment texture according to the specified options.
  97089. */
  97090. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97091. if (this._scene.environmentTexture) {
  97092. return;
  97093. }
  97094. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97095. this._scene.environmentTexture = this._options.environmentTexture;
  97096. return;
  97097. }
  97098. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97099. this._scene.environmentTexture = environmentTexture;
  97100. };
  97101. /**
  97102. * Setup the background according to the specified options.
  97103. */
  97104. EnvironmentHelper.prototype._setupBackground = function () {
  97105. if (!this._rootMesh) {
  97106. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97107. }
  97108. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97109. var sceneSize = this._getSceneSize();
  97110. if (this._options.createGround) {
  97111. this._setupGround(sceneSize);
  97112. this._setupGroundMaterial();
  97113. this._setupGroundDiffuseTexture();
  97114. if (this._options.enableGroundMirror) {
  97115. this._setupGroundMirrorTexture(sceneSize);
  97116. }
  97117. this._setupMirrorInGroundMaterial();
  97118. }
  97119. if (this._options.createSkybox) {
  97120. this._setupSkybox(sceneSize);
  97121. this._setupSkyboxMaterial();
  97122. this._setupSkyboxReflectionTexture();
  97123. }
  97124. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97125. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97126. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97127. };
  97128. /**
  97129. * Get the scene sizes according to the setup.
  97130. */
  97131. EnvironmentHelper.prototype._getSceneSize = function () {
  97132. var _this = this;
  97133. var groundSize = this._options.groundSize;
  97134. var skyboxSize = this._options.skyboxSize;
  97135. var rootPosition = this._options.rootPosition;
  97136. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97137. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97138. }
  97139. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97140. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97141. });
  97142. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97143. if (this._options.sizeAuto) {
  97144. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97145. this._scene.activeCamera.upperRadiusLimit) {
  97146. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97147. skyboxSize = groundSize;
  97148. }
  97149. var sceneDiagonalLenght = sceneDiagonal.length();
  97150. if (sceneDiagonalLenght > groundSize) {
  97151. groundSize = sceneDiagonalLenght * 2;
  97152. skyboxSize = groundSize;
  97153. }
  97154. // 10 % bigger.
  97155. groundSize *= 1.1;
  97156. skyboxSize *= 1.5;
  97157. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97158. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97159. }
  97160. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97161. };
  97162. /**
  97163. * Setup the ground according to the specified options.
  97164. */
  97165. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97166. var _this = this;
  97167. if (!this._ground) {
  97168. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97169. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97170. this._ground.parent = this._rootMesh;
  97171. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97172. }
  97173. this._ground.receiveShadows = this._options.enableGroundShadow;
  97174. };
  97175. /**
  97176. * Setup the ground material according to the specified options.
  97177. */
  97178. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97179. if (!this._groundMaterial) {
  97180. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97181. }
  97182. this._groundMaterial.alpha = this._options.groundOpacity;
  97183. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97184. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97185. this._groundMaterial.primaryColor = this._options.groundColor;
  97186. this._groundMaterial.useRGBColor = false;
  97187. this._groundMaterial.enableNoise = true;
  97188. if (this._ground) {
  97189. this._ground.material = this._groundMaterial;
  97190. }
  97191. };
  97192. /**
  97193. * Setup the ground diffuse texture according to the specified options.
  97194. */
  97195. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97196. if (!this._groundMaterial) {
  97197. return;
  97198. }
  97199. if (this._groundTexture) {
  97200. return;
  97201. }
  97202. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97203. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97204. return;
  97205. }
  97206. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97207. diffuseTexture.gammaSpace = false;
  97208. diffuseTexture.hasAlpha = true;
  97209. this._groundMaterial.diffuseTexture = diffuseTexture;
  97210. };
  97211. /**
  97212. * Setup the ground mirror texture according to the specified options.
  97213. */
  97214. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97215. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97216. if (!this._groundMirror) {
  97217. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97218. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97219. this._groundMirror.anisotropicFilteringLevel = 1;
  97220. this._groundMirror.wrapU = wrapping;
  97221. this._groundMirror.wrapV = wrapping;
  97222. this._groundMirror.gammaSpace = false;
  97223. if (this._groundMirror.renderList) {
  97224. for (var i = 0; i < this._scene.meshes.length; i++) {
  97225. var mesh = this._scene.meshes[i];
  97226. if (mesh !== this._ground &&
  97227. mesh !== this._skybox &&
  97228. mesh !== this._rootMesh) {
  97229. this._groundMirror.renderList.push(mesh);
  97230. }
  97231. }
  97232. }
  97233. }
  97234. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97235. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97236. };
  97237. /**
  97238. * Setup the ground to receive the mirror texture.
  97239. */
  97240. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97241. if (this._groundMaterial) {
  97242. this._groundMaterial.reflectionTexture = this._groundMirror;
  97243. this._groundMaterial.reflectionFresnel = true;
  97244. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97245. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97246. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97247. }
  97248. };
  97249. /**
  97250. * Setup the skybox according to the specified options.
  97251. */
  97252. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97253. var _this = this;
  97254. if (!this._skybox) {
  97255. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97256. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97257. }
  97258. this._skybox.parent = this._rootMesh;
  97259. };
  97260. /**
  97261. * Setup the skybox material according to the specified options.
  97262. */
  97263. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97264. if (!this._skybox) {
  97265. return;
  97266. }
  97267. if (!this._skyboxMaterial) {
  97268. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97269. }
  97270. this._skyboxMaterial.useRGBColor = false;
  97271. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97272. this._skyboxMaterial.enableNoise = true;
  97273. this._skybox.material = this._skyboxMaterial;
  97274. };
  97275. /**
  97276. * Setup the skybox reflection texture according to the specified options.
  97277. */
  97278. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97279. if (!this._skyboxMaterial) {
  97280. return;
  97281. }
  97282. if (this._skyboxTexture) {
  97283. return;
  97284. }
  97285. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97286. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97287. return;
  97288. }
  97289. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97290. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97291. this._skyboxTexture.gammaSpace = false;
  97292. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97293. };
  97294. /**
  97295. * Dispose all the elements created by the Helper.
  97296. */
  97297. EnvironmentHelper.prototype.dispose = function () {
  97298. if (this._groundMaterial) {
  97299. this._groundMaterial.dispose(true, true);
  97300. }
  97301. if (this._skyboxMaterial) {
  97302. this._skyboxMaterial.dispose(true, true);
  97303. }
  97304. this._rootMesh.dispose(false);
  97305. };
  97306. /**
  97307. * Default ground texture URL.
  97308. */
  97309. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97310. /**
  97311. * Default skybox texture URL.
  97312. */
  97313. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97314. /**
  97315. * Default environment texture URL.
  97316. */
  97317. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97318. return EnvironmentHelper;
  97319. }());
  97320. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97321. })(BABYLON || (BABYLON = {}));
  97322. //# sourceMappingURL=babylon.environmentHelper.js.map
  97323. var BABYLON;
  97324. (function (BABYLON) {
  97325. /**
  97326. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97327. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97328. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97329. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97330. */
  97331. var VideoDome = /** @class */ (function (_super) {
  97332. __extends(VideoDome, _super);
  97333. /**
  97334. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97335. * @param name Element's name, child elements will append suffixes for their own names.
  97336. * @param urlsOrVideo
  97337. * @param options An object containing optional or exposed sub element properties:
  97338. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97339. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97340. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97341. * @param options **loop=true** Automatically loop video on end.
  97342. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97343. */
  97344. function VideoDome(name, urlsOrVideo, options, scene) {
  97345. var _this = _super.call(this, name, scene) || this;
  97346. // set defaults and manage values
  97347. name = name || "videoDome";
  97348. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97349. options.clickToPlay = Boolean(options.clickToPlay);
  97350. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97351. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97352. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97353. // create
  97354. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97355. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97356. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97357. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97358. flat: false,
  97359. radius: options.size,
  97360. subdivisions: options.resolution,
  97361. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97362. }, scene);
  97363. // configure material
  97364. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97365. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97366. material.reflectionTexture = _this._videoTexture;
  97367. material.useEquirectangularFOV = true;
  97368. material.fovMultiplier = 1.0;
  97369. // configure mesh
  97370. _this._mesh.material = material;
  97371. _this._mesh.parent = _this;
  97372. // optional configuration
  97373. if (options.clickToPlay) {
  97374. scene.onPointerUp = function () {
  97375. _this._videoTexture.video.play();
  97376. };
  97377. }
  97378. return _this;
  97379. }
  97380. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97381. /**
  97382. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97383. * Also see the options.resolution property.
  97384. */
  97385. get: function () {
  97386. return this._material.fovMultiplier;
  97387. },
  97388. set: function (value) {
  97389. this._material.fovMultiplier = value;
  97390. },
  97391. enumerable: true,
  97392. configurable: true
  97393. });
  97394. /**
  97395. * Releases resources associated with this node.
  97396. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97397. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97398. */
  97399. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97400. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97401. this._videoTexture.dispose();
  97402. this._mesh.dispose();
  97403. this._material.dispose();
  97404. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97405. };
  97406. return VideoDome;
  97407. }(BABYLON.Node));
  97408. BABYLON.VideoDome = VideoDome;
  97409. })(BABYLON || (BABYLON = {}));
  97410. //# sourceMappingURL=babylon.videoDome.js.map
  97411. 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\nvPositionUVW=positionUpdated;\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\nvPositionUVW=positionUpdated;\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\nvec3 environmentRefraction=vec3(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).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=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*=vReflectionInfos.x;\nenvironmentRadiance*=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;\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*=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;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*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}","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 vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*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); \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#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,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() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*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(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-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;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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}","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}","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;\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;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\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\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\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);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\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}","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}","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\nvPositionUVW=position;\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\nvec3 reflectionColor=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=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*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,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"};
  97412. 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","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","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}","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};\n#endif\n#ifdef 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;\n#endif\n#ifdef 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 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=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\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=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\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\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\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\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","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","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}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef 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#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(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#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if 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 vec3 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 vec3 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 vec3 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#ifdef USEPHYSICALLIGHTFALLOFF\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};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,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*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*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,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*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*attenuation;\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}","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};","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","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};"};