babylon.no-module.max.js 4.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629956309563195632956339563495635956369563795638956399564095641956429564395644956459564695647956489564995650956519565295653956549565595656956579565895659956609566195662956639566495665956669566795668956699567095671956729567395674956759567695677956789567995680956819568295683956849568595686956879568895689956909569195692956939569495695956969569795698956999570095701957029570395704957059570695707957089570995710957119571295713957149571595716957179571895719957209572195722957239572495725957269572795728957299573095731957329573395734957359573695737957389573995740957419574295743957449574595746957479574895749957509575195752957539575495755957569575795758957599576095761957629576395764957659576695767957689576995770957719577295773957749577595776957779577895779957809578195782957839578495785957869578795788957899579095791957929579395794957959579695797957989579995800958019580295803958049580595806958079580895809958109581195812958139581495815958169581795818958199582095821958229582395824958259582695827958289582995830958319583295833958349583595836958379583895839958409584195842958439584495845958469584795848958499585095851958529585395854958559585695857958589585995860958619586295863958649586595866958679586895869958709587195872958739587495875958769587795878958799588095881958829588395884958859588695887958889588995890958919589295893958949589595896958979589895899959009590195902959039590495905959069590795908959099591095911959129591395914959159591695917959189591995920959219592295923959249592595926959279592895929959309593195932959339593495935959369593795938959399594095941959429594395944959459594695947959489594995950959519595295953959549595595956959579595895959959609596195962959639596495965959669596795968959699597095971959729597395974959759597695977959789597995980959819598295983959849598595986959879598895989959909599195992959939599495995959969599795998959999600096001960029600396004960059600696007960089600996010960119601296013960149601596016960179601896019960209602196022960239602496025960269602796028960299603096031960329603396034960359603696037960389603996040960419604296043960449604596046960479604896049960509605196052960539605496055960569605796058960599606096061960629606396064960659606696067960689606996070960719607296073960749607596076960779607896079960809608196082960839608496085960869608796088960899609096091960929609396094960959609696097960989609996100961019610296103961049610596106961079610896109961109611196112961139611496115961169611796118961199612096121961229612396124961259612696127961289612996130961319613296133961349613596136961379613896139961409614196142961439614496145961469614796148961499615096151961529615396154961559615696157961589615996160961619616296163961649616596166961679616896169961709617196172961739617496175961769617796178961799618096181961829618396184961859618696187961889618996190961919619296193961949619596196961979619896199962009620196202962039620496205962069620796208962099621096211962129621396214962159621696217962189621996220962219622296223962249622596226962279622896229962309623196232
  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. "use strict";
  4. var BABYLON;
  5. (function (BABYLON) {
  6. /**
  7. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  8. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  9. */
  10. var EffectFallbacks = /** @class */ (function () {
  11. function EffectFallbacks() {
  12. this._defines = {};
  13. this._currentRank = 32;
  14. this._maxRank = -1;
  15. }
  16. /**
  17. * Removes the fallback from the bound mesh.
  18. */
  19. EffectFallbacks.prototype.unBindMesh = function () {
  20. this._mesh = null;
  21. };
  22. /**
  23. * Adds a fallback on the specified property.
  24. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  25. * @param define The name of the define in the shader
  26. */
  27. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28. if (!this._defines[rank]) {
  29. if (rank < this._currentRank) {
  30. this._currentRank = rank;
  31. }
  32. if (rank > this._maxRank) {
  33. this._maxRank = rank;
  34. }
  35. this._defines[rank] = new Array();
  36. }
  37. this._defines[rank].push(define);
  38. };
  39. /**
  40. * Sets the mesh to use CPU skinning when needing to fallback.
  41. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  42. * @param mesh The mesh to use the fallbacks.
  43. */
  44. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  45. this._mesh = mesh;
  46. if (rank < this._currentRank) {
  47. this._currentRank = rank;
  48. }
  49. if (rank > this._maxRank) {
  50. this._maxRank = rank;
  51. }
  52. };
  53. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  54. /**
  55. * Checks to see if more fallbacks are still availible.
  56. */
  57. get: function () {
  58. return this._currentRank <= this._maxRank;
  59. },
  60. enumerable: true,
  61. configurable: true
  62. });
  63. /**
  64. * Removes the defines that shoould be removed when falling back.
  65. * @param currentDefines defines the current define statements for the shader.
  66. * @param effect defines the current effect we try to compile
  67. * @returns The resulting defines with defines of the current rank removed.
  68. */
  69. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  70. // First we try to switch to CPU skinning
  71. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  72. this._mesh.computeBonesUsingShaders = false;
  73. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. this._uniformBuffersNames = {};
  163. this._isReady = false;
  164. this._compilationError = "";
  165. this.name = baseName;
  166. if (attributesNamesOrOptions.attributes) {
  167. var options = attributesNamesOrOptions;
  168. this._engine = uniformsNamesOrEngine;
  169. this._attributesNames = options.attributes;
  170. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  171. this._samplers = options.samplers.slice();
  172. this.defines = options.defines;
  173. this.onError = options.onError;
  174. this.onCompiled = options.onCompiled;
  175. this._fallbacks = options.fallbacks;
  176. this._indexParameters = options.indexParameters;
  177. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  178. if (options.uniformBuffersNames) {
  179. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  180. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  181. }
  182. }
  183. }
  184. else {
  185. this._engine = engine;
  186. this.defines = defines;
  187. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  188. this._samplers = samplers ? samplers.slice() : [];
  189. this._attributesNames = attributesNamesOrOptions;
  190. this.onError = onError;
  191. this.onCompiled = onCompiled;
  192. this._indexParameters = indexParameters;
  193. this._fallbacks = fallbacks;
  194. }
  195. this.uniqueId = Effect._uniqueIdSeed++;
  196. var vertexSource;
  197. var fragmentSource;
  198. if (baseName.vertexElement) {
  199. vertexSource = document.getElementById(baseName.vertexElement);
  200. if (!vertexSource) {
  201. vertexSource = baseName.vertexElement;
  202. }
  203. }
  204. else {
  205. vertexSource = baseName.vertex || baseName;
  206. }
  207. if (baseName.fragmentElement) {
  208. fragmentSource = document.getElementById(baseName.fragmentElement);
  209. if (!fragmentSource) {
  210. fragmentSource = baseName.fragmentElement;
  211. }
  212. }
  213. else {
  214. fragmentSource = baseName.fragment || baseName;
  215. }
  216. this._loadVertexShader(vertexSource, function (vertexCode) {
  217. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  218. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  219. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  220. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  221. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  222. if (baseName) {
  223. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  224. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  225. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  226. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  227. }
  228. else {
  229. _this._vertexSourceCode = migratedVertexCode;
  230. _this._fragmentSourceCode = migratedFragmentCode;
  231. }
  232. _this._prepareEffect();
  233. });
  234. });
  235. });
  236. });
  237. });
  238. });
  239. }
  240. Object.defineProperty(Effect.prototype, "key", {
  241. /**
  242. * Unique key for this effect
  243. */
  244. get: function () {
  245. return this._key;
  246. },
  247. enumerable: true,
  248. configurable: true
  249. });
  250. /**
  251. * If the effect has been compiled and prepared.
  252. * @returns if the effect is compiled and prepared.
  253. */
  254. Effect.prototype.isReady = function () {
  255. return this._isReady;
  256. };
  257. /**
  258. * The engine the effect was initialized with.
  259. * @returns the engine.
  260. */
  261. Effect.prototype.getEngine = function () {
  262. return this._engine;
  263. };
  264. /**
  265. * The compiled webGL program for the effect
  266. * @returns the webGL program.
  267. */
  268. Effect.prototype.getProgram = function () {
  269. return this._program;
  270. };
  271. /**
  272. * The set of names of attribute variables for the shader.
  273. * @returns An array of attribute names.
  274. */
  275. Effect.prototype.getAttributesNames = function () {
  276. return this._attributesNames;
  277. };
  278. /**
  279. * Returns the attribute at the given index.
  280. * @param index The index of the attribute.
  281. * @returns The location of the attribute.
  282. */
  283. Effect.prototype.getAttributeLocation = function (index) {
  284. return this._attributes[index];
  285. };
  286. /**
  287. * Returns the attribute based on the name of the variable.
  288. * @param name of the attribute to look up.
  289. * @returns the attribute location.
  290. */
  291. Effect.prototype.getAttributeLocationByName = function (name) {
  292. var index = this._attributesNames.indexOf(name);
  293. return this._attributes[index];
  294. };
  295. /**
  296. * The number of attributes.
  297. * @returns the numnber of attributes.
  298. */
  299. Effect.prototype.getAttributesCount = function () {
  300. return this._attributes.length;
  301. };
  302. /**
  303. * Gets the index of a uniform variable.
  304. * @param uniformName of the uniform to look up.
  305. * @returns the index.
  306. */
  307. Effect.prototype.getUniformIndex = function (uniformName) {
  308. return this._uniformsNames.indexOf(uniformName);
  309. };
  310. /**
  311. * Returns the attribute based on the name of the variable.
  312. * @param uniformName of the uniform to look up.
  313. * @returns the location of the uniform.
  314. */
  315. Effect.prototype.getUniform = function (uniformName) {
  316. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  317. };
  318. /**
  319. * Returns an array of sampler variable names
  320. * @returns The array of sampler variable neames.
  321. */
  322. Effect.prototype.getSamplers = function () {
  323. return this._samplers;
  324. };
  325. /**
  326. * The error from the last compilation.
  327. * @returns the error string.
  328. */
  329. Effect.prototype.getCompilationError = function () {
  330. return this._compilationError;
  331. };
  332. /**
  333. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  334. * @param func The callback to be used.
  335. */
  336. Effect.prototype.executeWhenCompiled = function (func) {
  337. if (this.isReady()) {
  338. func(this);
  339. return;
  340. }
  341. this.onCompileObservable.add(function (effect) {
  342. func(effect);
  343. });
  344. };
  345. /** @ignore */
  346. Effect.prototype._loadVertexShader = function (vertex, callback) {
  347. if (BABYLON.Tools.IsWindowObjectExist()) {
  348. // DOM element ?
  349. if (vertex instanceof HTMLElement) {
  350. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  351. callback(vertexCode);
  352. return;
  353. }
  354. }
  355. // Base64 encoded ?
  356. if (vertex.substr(0, 7) === "base64:") {
  357. var vertexBinary = window.atob(vertex.substr(7));
  358. callback(vertexBinary);
  359. return;
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  364. return;
  365. }
  366. var vertexShaderUrl;
  367. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  368. vertexShaderUrl = vertex;
  369. }
  370. else {
  371. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  372. }
  373. // Vertex shader
  374. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  375. };
  376. /** @ignore */
  377. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  378. if (BABYLON.Tools.IsWindowObjectExist()) {
  379. // DOM element ?
  380. if (fragment instanceof HTMLElement) {
  381. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  382. callback(fragmentCode);
  383. return;
  384. }
  385. }
  386. // Base64 encoded ?
  387. if (fragment.substr(0, 7) === "base64:") {
  388. var fragmentBinary = window.atob(fragment.substr(7));
  389. callback(fragmentBinary);
  390. return;
  391. }
  392. // Is in local store ?
  393. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  394. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  395. return;
  396. }
  397. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  398. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  399. return;
  400. }
  401. var fragmentShaderUrl;
  402. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  403. fragmentShaderUrl = fragment;
  404. }
  405. else {
  406. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  407. }
  408. // Fragment shader
  409. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  410. };
  411. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  412. // Rebuild shaders source code
  413. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  414. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  415. vertexCode = prefix + vertexCode;
  416. fragmentCode = prefix + fragmentCode;
  417. // Number lines of shaders source code
  418. var i = 2;
  419. var regex = /\n/gm;
  420. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  421. i = 2;
  422. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. // Dump shaders name and formatted source code
  424. if (this.name.vertexElement) {
  425. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  426. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  427. }
  428. else if (this.name.vertex) {
  429. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  430. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  431. }
  432. else {
  433. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  434. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  435. }
  436. };
  437. ;
  438. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  439. var preparedSourceCode = this._processPrecision(sourceCode);
  440. if (this._engine.webGLVersion == 1) {
  441. callback(preparedSourceCode);
  442. return;
  443. }
  444. // Already converted
  445. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  446. callback(preparedSourceCode.replace("#version 300 es", ""));
  447. return;
  448. }
  449. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  450. // Remove extensions
  451. // #extension GL_OES_standard_derivatives : enable
  452. // #extension GL_EXT_shader_texture_lod : enable
  453. // #extension GL_EXT_frag_depth : enable
  454. // #extension GL_EXT_draw_buffers : require
  455. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  456. var result = preparedSourceCode.replace(regex, "");
  457. // Migrate to GLSL v300
  458. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  459. result = result.replace(/attribute[ \t]/g, "in ");
  460. result = result.replace(/[ \t]attribute/g, " in");
  461. if (isFragment) {
  462. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  464. result = result.replace(/texture2D\s*\(/g, "texture(");
  465. result = result.replace(/textureCube\s*\(/g, "texture(");
  466. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  467. result = result.replace(/gl_FragColor/g, "glFragColor");
  468. result = result.replace(/gl_FragData/g, "glFragData");
  469. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  470. }
  471. callback(result);
  472. };
  473. Effect.prototype._processIncludes = function (sourceCode, callback) {
  474. var _this = this;
  475. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  476. var match = regex.exec(sourceCode);
  477. var returnValue = new String(sourceCode);
  478. while (match != null) {
  479. var includeFile = match[1];
  480. // Uniform declaration
  481. if (includeFile.indexOf("__decl__") !== -1) {
  482. includeFile = includeFile.replace(/__decl__/, "");
  483. if (this._engine.supportsUniformBuffers) {
  484. includeFile = includeFile.replace(/Vertex/, "Ubo");
  485. includeFile = includeFile.replace(/Fragment/, "Ubo");
  486. }
  487. includeFile = includeFile + "Declaration";
  488. }
  489. if (Effect.IncludesShadersStore[includeFile]) {
  490. // Substitution
  491. var includeContent = Effect.IncludesShadersStore[includeFile];
  492. if (match[2]) {
  493. var splits = match[3].split(",");
  494. for (var index = 0; index < splits.length; index += 2) {
  495. var source = new RegExp(splits[index], "g");
  496. var dest = splits[index + 1];
  497. includeContent = includeContent.replace(source, dest);
  498. }
  499. }
  500. if (match[4]) {
  501. var indexString = match[5];
  502. if (indexString.indexOf("..") !== -1) {
  503. var indexSplits = indexString.split("..");
  504. var minIndex = parseInt(indexSplits[0]);
  505. var maxIndex = parseInt(indexSplits[1]);
  506. var sourceIncludeContent = includeContent.slice(0);
  507. includeContent = "";
  508. if (isNaN(maxIndex)) {
  509. maxIndex = this._indexParameters[indexSplits[1]];
  510. }
  511. for (var i = minIndex; i < maxIndex; i++) {
  512. if (!this._engine.supportsUniformBuffers) {
  513. // Ubo replacement
  514. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  515. return p1 + "{X}";
  516. });
  517. }
  518. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  519. }
  520. }
  521. else {
  522. if (!this._engine.supportsUniformBuffers) {
  523. // Ubo replacement
  524. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  525. return p1 + "{X}";
  526. });
  527. }
  528. includeContent = includeContent.replace(/\{X\}/g, indexString);
  529. }
  530. }
  531. // Replace
  532. returnValue = returnValue.replace(match[0], includeContent);
  533. }
  534. else {
  535. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  536. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  537. Effect.IncludesShadersStore[includeFile] = fileContent;
  538. _this._processIncludes(returnValue, callback);
  539. });
  540. return;
  541. }
  542. match = regex.exec(sourceCode);
  543. }
  544. callback(returnValue);
  545. };
  546. Effect.prototype._processPrecision = function (source) {
  547. if (source.indexOf("precision highp float") === -1) {
  548. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  549. source = "precision mediump float;\n" + source;
  550. }
  551. else {
  552. source = "precision highp float;\n" + source;
  553. }
  554. }
  555. else {
  556. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  557. source = source.replace("precision highp float", "precision mediump float");
  558. }
  559. }
  560. return source;
  561. };
  562. /**
  563. * Recompiles the webGL program
  564. * @param vertexSourceCode The source code for the vertex shader.
  565. * @param fragmentSourceCode The source code for the fragment shader.
  566. * @param onCompiled Callback called when completed.
  567. * @param onError Callback called on error.
  568. */
  569. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  570. var _this = this;
  571. this._isReady = false;
  572. this._vertexSourceCodeOverride = vertexSourceCode;
  573. this._fragmentSourceCodeOverride = fragmentSourceCode;
  574. this.onError = function (effect, error) {
  575. if (onError) {
  576. onError(error);
  577. }
  578. };
  579. this.onCompiled = function () {
  580. var scenes = _this.getEngine().scenes;
  581. for (var i = 0; i < scenes.length; i++) {
  582. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  583. }
  584. if (onCompiled) {
  585. onCompiled(_this._program);
  586. }
  587. };
  588. this._fallbacks = null;
  589. this._prepareEffect();
  590. };
  591. /**
  592. * Gets the uniform locations of the the specified variable names
  593. * @param names THe names of the variables to lookup.
  594. * @returns Array of locations in the same order as variable names.
  595. */
  596. Effect.prototype.getSpecificUniformLocations = function (names) {
  597. var engine = this._engine;
  598. return engine.getUniforms(this._program, names);
  599. };
  600. /**
  601. * Prepares the effect
  602. */
  603. Effect.prototype._prepareEffect = function () {
  604. var attributesNames = this._attributesNames;
  605. var defines = this.defines;
  606. var fallbacks = this._fallbacks;
  607. this._valueCache = {};
  608. var previousProgram = this._program;
  609. try {
  610. var engine = this._engine;
  611. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  612. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  613. }
  614. else {
  615. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  616. }
  617. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  618. if (engine.supportsUniformBuffers) {
  619. for (var name in this._uniformBuffersNames) {
  620. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  621. }
  622. }
  623. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  624. this._attributes = engine.getAttributes(this._program, attributesNames);
  625. var index;
  626. for (index = 0; index < this._samplers.length; index++) {
  627. var sampler = this.getUniform(this._samplers[index]);
  628. if (sampler == null) {
  629. this._samplers.splice(index, 1);
  630. index--;
  631. }
  632. }
  633. engine.bindSamplers(this);
  634. this._compilationError = "";
  635. this._isReady = true;
  636. if (this.onCompiled) {
  637. this.onCompiled(this);
  638. }
  639. this.onCompileObservable.notifyObservers(this);
  640. this.onCompileObservable.clear();
  641. // Unbind mesh reference in fallbacks
  642. if (this._fallbacks) {
  643. this._fallbacks.unBindMesh();
  644. }
  645. if (previousProgram) {
  646. this.getEngine()._deleteProgram(previousProgram);
  647. }
  648. }
  649. catch (e) {
  650. this._compilationError = e.message;
  651. // Let's go through fallbacks then
  652. BABYLON.Tools.Error("Unable to compile effect:");
  653. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  654. return " " + uniform;
  655. }));
  656. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  657. return " " + attribute;
  658. }));
  659. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  660. BABYLON.Tools.Error("Error: " + this._compilationError);
  661. if (previousProgram) {
  662. this._program = previousProgram;
  663. this._isReady = true;
  664. if (this.onError) {
  665. this.onError(this, this._compilationError);
  666. }
  667. this.onErrorObservable.notifyObservers(this);
  668. }
  669. if (fallbacks && fallbacks.isMoreFallbacks) {
  670. BABYLON.Tools.Error("Trying next fallback.");
  671. this.defines = fallbacks.reduce(this.defines, this);
  672. this._prepareEffect();
  673. }
  674. else {
  675. if (this.onError) {
  676. this.onError(this, this._compilationError);
  677. }
  678. this.onErrorObservable.notifyObservers(this);
  679. this.onErrorObservable.clear();
  680. // Unbind mesh reference in fallbacks
  681. if (this._fallbacks) {
  682. this._fallbacks.unBindMesh();
  683. }
  684. }
  685. }
  686. };
  687. Object.defineProperty(Effect.prototype, "isSupported", {
  688. /**
  689. * Checks if the effect is supported. (Must be called after compilation)
  690. */
  691. get: function () {
  692. return this._compilationError === "";
  693. },
  694. enumerable: true,
  695. configurable: true
  696. });
  697. /**
  698. * Binds a texture to the engine to be used as output of the shader.
  699. * @param channel Name of the output variable.
  700. * @param texture Texture to bind.
  701. */
  702. Effect.prototype._bindTexture = function (channel, texture) {
  703. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  704. };
  705. /**
  706. * Sets a texture on the engine to be used in the shader.
  707. * @param channel Name of the sampler variable.
  708. * @param texture Texture to set.
  709. */
  710. Effect.prototype.setTexture = function (channel, texture) {
  711. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  712. };
  713. /**
  714. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  715. * @param channel Name of the sampler variable.
  716. * @param texture Texture to set.
  717. */
  718. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  719. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  720. };
  721. /**
  722. * Sets an array of textures on the engine to be used in the shader.
  723. * @param channel Name of the variable.
  724. * @param textures Textures to set.
  725. */
  726. Effect.prototype.setTextureArray = function (channel, textures) {
  727. if (this._samplers.indexOf(channel + "Ex") === -1) {
  728. var initialPos = this._samplers.indexOf(channel);
  729. for (var index = 1; index < textures.length; index++) {
  730. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  731. }
  732. }
  733. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  734. };
  735. /**
  736. * 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)
  737. * @param channel Name of the sampler variable.
  738. * @param postProcess Post process to get the input texture from.
  739. */
  740. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  741. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  742. };
  743. /**
  744. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  745. * 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)
  746. * @param channel Name of the sampler variable.
  747. * @param postProcess Post process to get the output texture from.
  748. */
  749. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  750. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  751. };
  752. /** @ignore */
  753. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  754. var cache = this._valueCache[uniformName];
  755. var flag = matrix.updateFlag;
  756. if (cache !== undefined && cache === flag) {
  757. return false;
  758. }
  759. this._valueCache[uniformName] = flag;
  760. return true;
  761. };
  762. /** @ignore */
  763. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  764. var cache = this._valueCache[uniformName];
  765. if (!cache) {
  766. cache = [x, y];
  767. this._valueCache[uniformName] = cache;
  768. return true;
  769. }
  770. var changed = false;
  771. if (cache[0] !== x) {
  772. cache[0] = x;
  773. changed = true;
  774. }
  775. if (cache[1] !== y) {
  776. cache[1] = y;
  777. changed = true;
  778. }
  779. return changed;
  780. };
  781. /** @ignore */
  782. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  783. var cache = this._valueCache[uniformName];
  784. if (!cache) {
  785. cache = [x, y, z];
  786. this._valueCache[uniformName] = cache;
  787. return true;
  788. }
  789. var changed = false;
  790. if (cache[0] !== x) {
  791. cache[0] = x;
  792. changed = true;
  793. }
  794. if (cache[1] !== y) {
  795. cache[1] = y;
  796. changed = true;
  797. }
  798. if (cache[2] !== z) {
  799. cache[2] = z;
  800. changed = true;
  801. }
  802. return changed;
  803. };
  804. /** @ignore */
  805. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  806. var cache = this._valueCache[uniformName];
  807. if (!cache) {
  808. cache = [x, y, z, w];
  809. this._valueCache[uniformName] = cache;
  810. return true;
  811. }
  812. var changed = false;
  813. if (cache[0] !== x) {
  814. cache[0] = x;
  815. changed = true;
  816. }
  817. if (cache[1] !== y) {
  818. cache[1] = y;
  819. changed = true;
  820. }
  821. if (cache[2] !== z) {
  822. cache[2] = z;
  823. changed = true;
  824. }
  825. if (cache[3] !== w) {
  826. cache[3] = w;
  827. changed = true;
  828. }
  829. return changed;
  830. };
  831. /**
  832. * Binds a buffer to a uniform.
  833. * @param buffer Buffer to bind.
  834. * @param name Name of the uniform variable to bind to.
  835. */
  836. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  837. var bufferName = this._uniformBuffersNames[name];
  838. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  839. return;
  840. }
  841. Effect._baseCache[bufferName] = buffer;
  842. this._engine.bindUniformBufferBase(buffer, bufferName);
  843. };
  844. /**
  845. * Binds block to a uniform.
  846. * @param blockName Name of the block to bind.
  847. * @param index Index to bind.
  848. */
  849. Effect.prototype.bindUniformBlock = function (blockName, index) {
  850. this._engine.bindUniformBlock(this._program, blockName, index);
  851. };
  852. /**
  853. * Sets an interger value on a uniform variable.
  854. * @param uniformName Name of the variable.
  855. * @param value Value to be set.
  856. * @returns this effect.
  857. */
  858. Effect.prototype.setInt = function (uniformName, value) {
  859. var cache = this._valueCache[uniformName];
  860. if (cache !== undefined && cache === value)
  861. return this;
  862. this._valueCache[uniformName] = value;
  863. this._engine.setInt(this.getUniform(uniformName), value);
  864. return this;
  865. };
  866. /**
  867. * Sets an int array on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param array array to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setIntArray = function (uniformName, array) {
  873. this._valueCache[uniformName] = null;
  874. this._engine.setIntArray(this.getUniform(uniformName), array);
  875. return this;
  876. };
  877. /**
  878. * 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)
  879. * @param uniformName Name of the variable.
  880. * @param array array to be set.
  881. * @returns this effect.
  882. */
  883. Effect.prototype.setIntArray2 = function (uniformName, array) {
  884. this._valueCache[uniformName] = null;
  885. this._engine.setIntArray2(this.getUniform(uniformName), array);
  886. return this;
  887. };
  888. /**
  889. * 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)
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray3 = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray3(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * 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)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray4 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray4(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * Sets an float array on a uniform variable.
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setFloatArray = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setFloatArray(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * 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)
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * 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)
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * 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)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * Sets an array on a uniform variable.
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setArray = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setArray(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * 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)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setArray2 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setArray2(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * 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)
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray3 = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray3(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * 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)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray4 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray4(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * Sets matrices on a uniform variable.
  1000. * @param uniformName Name of the variable.
  1001. * @param matrices matrices to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1005. if (!matrices) {
  1006. return this;
  1007. }
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrix on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrix matrix to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1019. if (this._cacheMatrix(uniformName, matrix)) {
  1020. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1021. }
  1022. return this;
  1023. };
  1024. /**
  1025. * 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)
  1026. * @param uniformName Name of the variable.
  1027. * @param matrix matrix to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1033. return this;
  1034. };
  1035. /**
  1036. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1037. * @param uniformName Name of the variable.
  1038. * @param matrix matrix to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1044. return this;
  1045. };
  1046. /**
  1047. * Sets a float on a uniform variable.
  1048. * @param uniformName Name of the variable.
  1049. * @param value value to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setFloat = function (uniformName, value) {
  1053. var cache = this._valueCache[uniformName];
  1054. if (cache !== undefined && cache === value)
  1055. return this;
  1056. this._valueCache[uniformName] = value;
  1057. this._engine.setFloat(this.getUniform(uniformName), value);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a boolean on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param bool value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setBool = function (uniformName, bool) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === bool)
  1069. return this;
  1070. this._valueCache[uniformName] = bool;
  1071. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a Vector2 on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param vector2 vector2 to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1081. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1082. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1083. }
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a float2 on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param x First float in float2.
  1090. * @param y Second float in float2.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1094. if (this._cacheFloat2(uniformName, x, y)) {
  1095. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1096. }
  1097. return this;
  1098. };
  1099. /**
  1100. * Sets a Vector3 on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param vector3 Value to be set.
  1103. * @returns this effect.
  1104. */
  1105. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1106. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1107. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1108. }
  1109. return this;
  1110. };
  1111. /**
  1112. * Sets a float3 on a uniform variable.
  1113. * @param uniformName Name of the variable.
  1114. * @param x First float in float3.
  1115. * @param y Second float in float3.
  1116. * @param z Third float in float3.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1120. if (this._cacheFloat3(uniformName, x, y, z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector4 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector4 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1132. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1133. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float4 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float4.
  1141. * @param y Second float in float4.
  1142. * @param z Third float in float4.
  1143. * @param w Fourth float in float4.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1147. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1148. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a Color3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param color3 Value to be set.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setColor3 = function (uniformName, color3) {
  1159. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1160. this._engine.setColor3(this.getUniform(uniformName), color3);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a Color4 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param color3 Value to be set.
  1168. * @param alpha Alpha value to be set.
  1169. * @returns this effect.
  1170. */
  1171. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1172. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1173. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1174. }
  1175. return this;
  1176. };
  1177. /**
  1178. * Sets a Color4 on a uniform variable
  1179. * @param uniformName defines the name of the variable
  1180. * @param color4 defines the value to be set
  1181. * @returns this effect.
  1182. */
  1183. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1184. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1185. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1186. }
  1187. return this;
  1188. };
  1189. /**
  1190. * Resets the cache of effects.
  1191. */
  1192. Effect.ResetCache = function () {
  1193. Effect._baseCache = {};
  1194. };
  1195. Effect._uniqueIdSeed = 0;
  1196. Effect._baseCache = {};
  1197. /**
  1198. * Store of each shader (The can be looked up using effect.key)
  1199. */
  1200. Effect.ShadersStore = {};
  1201. /**
  1202. * Store of each included file for a shader (The can be looked up using effect.key)
  1203. */
  1204. Effect.IncludesShadersStore = {};
  1205. return Effect;
  1206. }());
  1207. BABYLON.Effect = Effect;
  1208. })(BABYLON || (BABYLON = {}));
  1209. //# sourceMappingURL=babylon.effect.js.map
  1210. "use strict";
  1211. //# sourceMappingURL=babylon.types.js.map
  1212. "use strict";
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. "use strict";
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var PointerEventTypes = /** @class */ (function () {
  1265. function PointerEventTypes() {
  1266. }
  1267. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1268. get: function () {
  1269. return PointerEventTypes._POINTERDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1275. get: function () {
  1276. return PointerEventTypes._POINTERUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1282. get: function () {
  1283. return PointerEventTypes._POINTERMOVE;
  1284. },
  1285. enumerable: true,
  1286. configurable: true
  1287. });
  1288. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1289. get: function () {
  1290. return PointerEventTypes._POINTERWHEEL;
  1291. },
  1292. enumerable: true,
  1293. configurable: true
  1294. });
  1295. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1296. get: function () {
  1297. return PointerEventTypes._POINTERPICK;
  1298. },
  1299. enumerable: true,
  1300. configurable: true
  1301. });
  1302. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1303. get: function () {
  1304. return PointerEventTypes._POINTERTAP;
  1305. },
  1306. enumerable: true,
  1307. configurable: true
  1308. });
  1309. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1310. get: function () {
  1311. return PointerEventTypes._POINTERDOUBLETAP;
  1312. },
  1313. enumerable: true,
  1314. configurable: true
  1315. });
  1316. PointerEventTypes._POINTERDOWN = 0x01;
  1317. PointerEventTypes._POINTERUP = 0x02;
  1318. PointerEventTypes._POINTERMOVE = 0x04;
  1319. PointerEventTypes._POINTERWHEEL = 0x08;
  1320. PointerEventTypes._POINTERPICK = 0x10;
  1321. PointerEventTypes._POINTERTAP = 0x20;
  1322. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1323. return PointerEventTypes;
  1324. }());
  1325. BABYLON.PointerEventTypes = PointerEventTypes;
  1326. var PointerInfoBase = /** @class */ (function () {
  1327. function PointerInfoBase(type, event) {
  1328. this.type = type;
  1329. this.event = event;
  1330. }
  1331. return PointerInfoBase;
  1332. }());
  1333. BABYLON.PointerInfoBase = PointerInfoBase;
  1334. /**
  1335. * This class is used to store pointer related info for the onPrePointerObservable event.
  1336. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1337. */
  1338. var PointerInfoPre = /** @class */ (function (_super) {
  1339. __extends(PointerInfoPre, _super);
  1340. function PointerInfoPre(type, event, localX, localY) {
  1341. var _this = _super.call(this, type, event) || this;
  1342. _this.skipOnPointerObservable = false;
  1343. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1344. return _this;
  1345. }
  1346. return PointerInfoPre;
  1347. }(PointerInfoBase));
  1348. BABYLON.PointerInfoPre = PointerInfoPre;
  1349. /**
  1350. * This type contains all the data related to a pointer event in Babylon.js.
  1351. * 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.
  1352. */
  1353. var PointerInfo = /** @class */ (function (_super) {
  1354. __extends(PointerInfo, _super);
  1355. function PointerInfo(type, event, pickInfo) {
  1356. var _this = _super.call(this, type, event) || this;
  1357. _this.pickInfo = pickInfo;
  1358. return _this;
  1359. }
  1360. return PointerInfo;
  1361. }(PointerInfoBase));
  1362. BABYLON.PointerInfo = PointerInfo;
  1363. })(BABYLON || (BABYLON = {}));
  1364. //# sourceMappingURL=babylon.pointerEvents.js.map
  1365. "use strict";
  1366. var BABYLON;
  1367. (function (BABYLON) {
  1368. BABYLON.ToGammaSpace = 1 / 2.2;
  1369. BABYLON.ToLinearSpace = 2.2;
  1370. BABYLON.Epsilon = 0.001;
  1371. /**
  1372. * Class used to hold a RBG color
  1373. */
  1374. var Color3 = /** @class */ (function () {
  1375. /**
  1376. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1377. * @param r defines the red component (between 0 and 1, default is 0)
  1378. * @param g defines the green component (between 0 and 1, default is 0)
  1379. * @param b defines the blue component (between 0 and 1, default is 0)
  1380. */
  1381. function Color3(
  1382. /**
  1383. * Defines the red component (between 0 and 1, default is 0)
  1384. */
  1385. r,
  1386. /**
  1387. * Defines the green component (between 0 and 1, default is 0)
  1388. */
  1389. g,
  1390. /**
  1391. * Defines the blue component (between 0 and 1, default is 0)
  1392. */
  1393. b) {
  1394. if (r === void 0) { r = 0; }
  1395. if (g === void 0) { g = 0; }
  1396. if (b === void 0) { b = 0; }
  1397. this.r = r;
  1398. this.g = g;
  1399. this.b = b;
  1400. }
  1401. /**
  1402. * Creates a string with the Color3 current values
  1403. * @returns the string representation of the Color3 object
  1404. */
  1405. Color3.prototype.toString = function () {
  1406. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1407. };
  1408. /**
  1409. * Returns the string "Color3"
  1410. * @returns "Color3"
  1411. */
  1412. Color3.prototype.getClassName = function () {
  1413. return "Color3";
  1414. };
  1415. /**
  1416. * Compute the Color3 hash code
  1417. * @returns an unique number that can be used to hash Color3 objects
  1418. */
  1419. Color3.prototype.getHashCode = function () {
  1420. var hash = this.r || 0;
  1421. hash = (hash * 397) ^ (this.g || 0);
  1422. hash = (hash * 397) ^ (this.b || 0);
  1423. return hash;
  1424. };
  1425. // Operators
  1426. /**
  1427. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1428. * @param array defines the array where to store the r,g,b components
  1429. * @param index defines an optional index in the target array to define where to start storing values
  1430. * @returns the current Color3 object
  1431. */
  1432. Color3.prototype.toArray = function (array, index) {
  1433. if (index === undefined) {
  1434. index = 0;
  1435. }
  1436. array[index] = this.r;
  1437. array[index + 1] = this.g;
  1438. array[index + 2] = this.b;
  1439. return this;
  1440. };
  1441. /**
  1442. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1443. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1444. * @returns a new {BABYLON.Color4} object
  1445. */
  1446. Color3.prototype.toColor4 = function (alpha) {
  1447. if (alpha === void 0) { alpha = 1; }
  1448. return new Color4(this.r, this.g, this.b, alpha);
  1449. };
  1450. /**
  1451. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1452. * @returns the new array
  1453. */
  1454. Color3.prototype.asArray = function () {
  1455. var result = new Array();
  1456. this.toArray(result, 0);
  1457. return result;
  1458. };
  1459. /**
  1460. * Returns the luminance value
  1461. * @returns a float value
  1462. */
  1463. Color3.prototype.toLuminance = function () {
  1464. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1465. };
  1466. /**
  1467. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1468. * @param otherColor defines the second operand
  1469. * @returns the new Color3 object
  1470. */
  1471. Color3.prototype.multiply = function (otherColor) {
  1472. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1473. };
  1474. /**
  1475. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1476. * @param otherColor defines the second operand
  1477. * @param result defines the Color3 object where to store the result
  1478. * @returns the current Color3
  1479. */
  1480. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1481. result.r = this.r * otherColor.r;
  1482. result.g = this.g * otherColor.g;
  1483. result.b = this.b * otherColor.b;
  1484. return this;
  1485. };
  1486. /**
  1487. * Determines equality between Color3 objects
  1488. * @param otherColor defines the second operand
  1489. * @returns true if the rgb values are equal to the passed ones
  1490. */
  1491. Color3.prototype.equals = function (otherColor) {
  1492. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1493. };
  1494. /**
  1495. * Determines equality between the current Color3 object and a set of r,b,g values
  1496. * @param r defines the red component to check
  1497. * @param g defines the green component to check
  1498. * @param b defines the blue component to check
  1499. * @returns true if the rgb values are equal to the passed ones
  1500. */
  1501. Color3.prototype.equalsFloats = function (r, g, b) {
  1502. return this.r === r && this.g === g && this.b === b;
  1503. };
  1504. /**
  1505. * Multiplies in place each rgb value by scale
  1506. * @param scale defines the scaling factor
  1507. * @returns the updated Color3
  1508. */
  1509. Color3.prototype.scale = function (scale) {
  1510. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1511. };
  1512. /**
  1513. * Multiplies the rgb values by scale and stores the result into "result"
  1514. * @param scale defines the scaling factor
  1515. * @param result defines the Color3 object where to store the result
  1516. * @returns the unmodified current Color3
  1517. */
  1518. Color3.prototype.scaleToRef = function (scale, result) {
  1519. result.r = this.r * scale;
  1520. result.g = this.g * scale;
  1521. result.b = this.b * scale;
  1522. return this;
  1523. };
  1524. /**
  1525. * Scale the current Color3 values by a factor and add the result to a given Color3
  1526. * @param scale defines the scale factor
  1527. * @param result defines color to store the result into
  1528. * @returns the unmodified current Color3
  1529. */
  1530. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1531. result.r += this.r * scale;
  1532. result.g += this.g * scale;
  1533. result.b += this.b * scale;
  1534. return this;
  1535. };
  1536. /**
  1537. * Clamps the rgb values by the min and max values and stores the result into "result"
  1538. * @param min defines minimum clamping value (default is 0)
  1539. * @param max defines maximum clamping value (default is 1)
  1540. * @param result defines color to store the result into
  1541. * @returns the original Color3
  1542. */
  1543. Color3.prototype.clampToRef = function (min, max, result) {
  1544. if (min === void 0) { min = 0; }
  1545. if (max === void 0) { max = 1; }
  1546. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1547. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1548. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1549. return this;
  1550. };
  1551. /**
  1552. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1553. * @param otherColor defines the second operand
  1554. * @returns the new Color3
  1555. */
  1556. Color3.prototype.add = function (otherColor) {
  1557. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1558. };
  1559. /**
  1560. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1561. * @param otherColor defines the second operand
  1562. * @param result defines Color3 object to store the result into
  1563. * @returns the unmodified current Color3
  1564. */
  1565. Color3.prototype.addToRef = function (otherColor, result) {
  1566. result.r = this.r + otherColor.r;
  1567. result.g = this.g + otherColor.g;
  1568. result.b = this.b + otherColor.b;
  1569. return this;
  1570. };
  1571. /**
  1572. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1573. * @param otherColor defines the second operand
  1574. * @returns the new Color3
  1575. */
  1576. Color3.prototype.subtract = function (otherColor) {
  1577. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1578. };
  1579. /**
  1580. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1581. * @param otherColor defines the second operand
  1582. * @param result defines Color3 object to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.subtractToRef = function (otherColor, result) {
  1586. result.r = this.r - otherColor.r;
  1587. result.g = this.g - otherColor.g;
  1588. result.b = this.b - otherColor.b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Copy the current object
  1593. * @returns a new Color3 copied the current one
  1594. */
  1595. Color3.prototype.clone = function () {
  1596. return new Color3(this.r, this.g, this.b);
  1597. };
  1598. /**
  1599. * Copies the rgb values from the source in the current Color3
  1600. * @param source defines the source Color3 object
  1601. * @returns the updated Color3 object
  1602. */
  1603. Color3.prototype.copyFrom = function (source) {
  1604. this.r = source.r;
  1605. this.g = source.g;
  1606. this.b = source.b;
  1607. return this;
  1608. };
  1609. /**
  1610. * Updates the Color3 rgb values from the passed floats
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @returns the current Color3 object
  1615. */
  1616. Color3.prototype.copyFromFloats = function (r, g, b) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. return this;
  1621. };
  1622. /**
  1623. * Updates the Color3 rgb values from the passed floats
  1624. * @param r defines the red component to read from
  1625. * @param g defines the green component to read from
  1626. * @param b defines the blue component to read from
  1627. * @returns the current Color3 object
  1628. */
  1629. Color3.prototype.set = function (r, g, b) {
  1630. return this.copyFromFloats(r, g, b);
  1631. };
  1632. /**
  1633. * Compute the Color3 hexadecimal code as a string
  1634. * @returns a string containing the hexadecimal representation of the Color3 object
  1635. */
  1636. Color3.prototype.toHexString = function () {
  1637. var intR = (this.r * 255) | 0;
  1638. var intG = (this.g * 255) | 0;
  1639. var intB = (this.b * 255) | 0;
  1640. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1641. };
  1642. /**
  1643. * Computes a new Color3 converted from the current one to linear space
  1644. * @returns a new Color3 object
  1645. */
  1646. Color3.prototype.toLinearSpace = function () {
  1647. var convertedColor = new Color3();
  1648. this.toLinearSpaceToRef(convertedColor);
  1649. return convertedColor;
  1650. };
  1651. /**
  1652. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1653. * @param convertedColor defines the Color3 object where to store the linear space version
  1654. * @returns the unmodified Color3
  1655. */
  1656. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1657. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1658. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1659. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1660. return this;
  1661. };
  1662. /**
  1663. * Computes a new Color3 converted from the current one to gamma space
  1664. * @returns a new Color3 object
  1665. */
  1666. Color3.prototype.toGammaSpace = function () {
  1667. var convertedColor = new Color3();
  1668. this.toGammaSpaceToRef(convertedColor);
  1669. return convertedColor;
  1670. };
  1671. /**
  1672. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1673. * @param convertedColor defines the Color3 object where to store the gamma space version
  1674. * @returns the unmodified Color3
  1675. */
  1676. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1677. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1678. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1679. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1680. return this;
  1681. };
  1682. // Statics
  1683. /**
  1684. * Creates a new Color3 from the string containing valid hexadecimal values
  1685. * @param hex defines a string containing valid hexadecimal values
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.FromHexString = function (hex) {
  1689. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1690. return new Color3(0, 0, 0);
  1691. }
  1692. var r = parseInt(hex.substring(1, 3), 16);
  1693. var g = parseInt(hex.substring(3, 5), 16);
  1694. var b = parseInt(hex.substring(5, 7), 16);
  1695. return Color3.FromInts(r, g, b);
  1696. };
  1697. /**
  1698. * Creates a new Vector3 from the starting index of the passed array
  1699. * @param array defines the source array
  1700. * @param offset defines an offset in the source array
  1701. * @returns a new Color3 object
  1702. */
  1703. Color3.FromArray = function (array, offset) {
  1704. if (offset === void 0) { offset = 0; }
  1705. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1706. };
  1707. /**
  1708. * Creates a new Color3 from integer values (< 256)
  1709. * @param r defines the red component to read from (value between 0 and 255)
  1710. * @param g defines the green component to read from (value between 0 and 255)
  1711. * @param b defines the blue component to read from (value between 0 and 255)
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.FromInts = function (r, g, b) {
  1715. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1716. };
  1717. /**
  1718. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1719. * @param start defines the start Color3 value
  1720. * @param end defines the end Color3 value
  1721. * @param amount defines the gradient value between start and end
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Lerp = function (start, end, amount) {
  1725. var r = start.r + ((end.r - start.r) * amount);
  1726. var g = start.g + ((end.g - start.g) * amount);
  1727. var b = start.b + ((end.b - start.b) * amount);
  1728. return new Color3(r, g, b);
  1729. };
  1730. /**
  1731. * Returns a Color3 value containing a red color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Red = function () { return new Color3(1, 0, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a green color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Green = function () { return new Color3(0, 1, 0); };
  1740. /**
  1741. * Returns a Color3 value containing a blue color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1745. /**
  1746. * Returns a Color3 value containing a black color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Black = function () { return new Color3(0, 0, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a white color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.White = function () { return new Color3(1, 1, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a purple color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1760. /**
  1761. * Returns a Color3 value containing a magenta color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a yellow color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a gray color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1775. /**
  1776. * Returns a Color3 value containing a teal color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1780. /**
  1781. * Returns a Color3 value containing a random color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1785. return Color3;
  1786. }());
  1787. BABYLON.Color3 = Color3;
  1788. /**
  1789. * Class used to hold a RBGA color
  1790. */
  1791. var Color4 = /** @class */ (function () {
  1792. /**
  1793. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1794. * @param r defines the red component (between 0 and 1, default is 0)
  1795. * @param g defines the green component (between 0 and 1, default is 0)
  1796. * @param b defines the blue component (between 0 and 1, default is 0)
  1797. * @param a defines the alpha component (between 0 and 1, default is 1)
  1798. */
  1799. function Color4(
  1800. /**
  1801. * Defines the red component (between 0 and 1, default is 0)
  1802. */
  1803. r,
  1804. /**
  1805. * Defines the green component (between 0 and 1, default is 0)
  1806. */
  1807. g,
  1808. /**
  1809. * Defines the blue component (between 0 and 1, default is 0)
  1810. */
  1811. b,
  1812. /**
  1813. * Defines the alpha component (between 0 and 1, default is 1)
  1814. */
  1815. a) {
  1816. if (r === void 0) { r = 0; }
  1817. if (g === void 0) { g = 0; }
  1818. if (b === void 0) { b = 0; }
  1819. if (a === void 0) { a = 1; }
  1820. this.r = r;
  1821. this.g = g;
  1822. this.b = b;
  1823. this.a = a;
  1824. }
  1825. // Operators
  1826. /**
  1827. * Adds in place the passed Color4 values to the current Color4 object
  1828. * @param right defines the second operand
  1829. * @returns the current updated Color4 object
  1830. */
  1831. Color4.prototype.addInPlace = function (right) {
  1832. this.r += right.r;
  1833. this.g += right.g;
  1834. this.b += right.b;
  1835. this.a += right.a;
  1836. return this;
  1837. };
  1838. /**
  1839. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1840. * @returns the new array
  1841. */
  1842. Color4.prototype.asArray = function () {
  1843. var result = new Array();
  1844. this.toArray(result, 0);
  1845. return result;
  1846. };
  1847. /**
  1848. * Stores from the starting index in the passed array the Color4 successive values
  1849. * @param array defines the array where to store the r,g,b components
  1850. * @param index defines an optional index in the target array to define where to start storing values
  1851. * @returns the current Color4 object
  1852. */
  1853. Color4.prototype.toArray = function (array, index) {
  1854. if (index === undefined) {
  1855. index = 0;
  1856. }
  1857. array[index] = this.r;
  1858. array[index + 1] = this.g;
  1859. array[index + 2] = this.b;
  1860. array[index + 3] = this.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.add = function (right) {
  1869. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1870. };
  1871. /**
  1872. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1873. * @param right defines the second operand
  1874. * @returns a new Color4 object
  1875. */
  1876. Color4.prototype.subtract = function (right) {
  1877. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1878. };
  1879. /**
  1880. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1881. * @param right defines the second operand
  1882. * @param result defines the Color4 object where to store the result
  1883. * @returns the current Color4 object
  1884. */
  1885. Color4.prototype.subtractToRef = function (right, result) {
  1886. result.r = this.r - right.r;
  1887. result.g = this.g - right.g;
  1888. result.b = this.b - right.b;
  1889. result.a = this.a - right.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 with the current Color4 values multiplied by scale
  1894. * @param scale defines the scaling factor to apply
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.scale = function (scale) {
  1898. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1899. };
  1900. /**
  1901. * Multiplies the current Color4 values by scale and stores the result in "result"
  1902. * @param scale defines the scaling factor to apply
  1903. * @param result defines the Color4 object where to store the result
  1904. * @returns the current unmodified Color4
  1905. */
  1906. Color4.prototype.scaleToRef = function (scale, result) {
  1907. result.r = this.r * scale;
  1908. result.g = this.g * scale;
  1909. result.b = this.b * scale;
  1910. result.a = this.a * scale;
  1911. return this;
  1912. };
  1913. /**
  1914. * Scale the current Color4 values by a factor and add the result to a given Color4
  1915. * @param scale defines the scale factor
  1916. * @param result defines the Color4 object where to store the result
  1917. * @returns the unmodified current Color4
  1918. */
  1919. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1920. result.r += this.r * scale;
  1921. result.g += this.g * scale;
  1922. result.b += this.b * scale;
  1923. result.a += this.a * scale;
  1924. return this;
  1925. };
  1926. /**
  1927. * Clamps the rgb values by the min and max values and stores the result into "result"
  1928. * @param min defines minimum clamping value (default is 0)
  1929. * @param max defines maximum clamping value (default is 1)
  1930. * @param result defines color to store the result into.
  1931. * @returns the cuurent Color4
  1932. */
  1933. Color4.prototype.clampToRef = function (min, max, result) {
  1934. if (min === void 0) { min = 0; }
  1935. if (max === void 0) { max = 1; }
  1936. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1937. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1938. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1939. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1940. return this;
  1941. };
  1942. /**
  1943. * Multipy an Color4 value by another and return a new Color4 object
  1944. * @param color defines the Color4 value to multiply by
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.multiply = function (color) {
  1948. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1949. };
  1950. /**
  1951. * Multipy a Color4 value by another and push the result in a reference value
  1952. * @param color defines the Color4 value to multiply by
  1953. * @param result defines the Color4 to fill the result in
  1954. * @returns the result Color4
  1955. */
  1956. Color4.prototype.multiplyToRef = function (color, result) {
  1957. result.r = this.r * color.r;
  1958. result.g = this.g * color.g;
  1959. result.b = this.b * color.b;
  1960. result.a = this.a * color.a;
  1961. return result;
  1962. };
  1963. /**
  1964. * Creates a string with the Color4 current values
  1965. * @returns the string representation of the Color4 object
  1966. */
  1967. Color4.prototype.toString = function () {
  1968. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1969. };
  1970. /**
  1971. * Returns the string "Color4"
  1972. * @returns "Color4"
  1973. */
  1974. Color4.prototype.getClassName = function () {
  1975. return "Color4";
  1976. };
  1977. /**
  1978. * Compute the Color4 hash code
  1979. * @returns an unique number that can be used to hash Color4 objects
  1980. */
  1981. Color4.prototype.getHashCode = function () {
  1982. var hash = this.r || 0;
  1983. hash = (hash * 397) ^ (this.g || 0);
  1984. hash = (hash * 397) ^ (this.b || 0);
  1985. hash = (hash * 397) ^ (this.a || 0);
  1986. return hash;
  1987. };
  1988. /**
  1989. * Creates a new Color4 copied from the current one
  1990. * @returns a new Color4 object
  1991. */
  1992. Color4.prototype.clone = function () {
  1993. return new Color4(this.r, this.g, this.b, this.a);
  1994. };
  1995. /**
  1996. * Copies the passed Color4 values into the current one
  1997. * @param source defines the source Color4 object
  1998. * @returns the current updated Color4 object
  1999. */
  2000. Color4.prototype.copyFrom = function (source) {
  2001. this.r = source.r;
  2002. this.g = source.g;
  2003. this.b = source.b;
  2004. this.a = source.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Copies the passed float values into the current one
  2009. * @param r defines the red component to read from
  2010. * @param g defines the green component to read from
  2011. * @param b defines the blue component to read from
  2012. * @param a defines the alpha component to read from
  2013. * @returns the current updated Color4 object
  2014. */
  2015. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2016. this.r = r;
  2017. this.g = g;
  2018. this.b = b;
  2019. this.a = a;
  2020. return this;
  2021. };
  2022. /**
  2023. * Copies the passed float values into the current one
  2024. * @param r defines the red component to read from
  2025. * @param g defines the green component to read from
  2026. * @param b defines the blue component to read from
  2027. * @param a defines the alpha component to read from
  2028. * @returns the current updated Color4 object
  2029. */
  2030. Color4.prototype.set = function (r, g, b, a) {
  2031. return this.copyFromFloats(r, g, b, a);
  2032. };
  2033. /**
  2034. * Compute the Color4 hexadecimal code as a string
  2035. * @returns a string containing the hexadecimal representation of the Color4 object
  2036. */
  2037. Color4.prototype.toHexString = function () {
  2038. var intR = (this.r * 255) | 0;
  2039. var intG = (this.g * 255) | 0;
  2040. var intB = (this.b * 255) | 0;
  2041. var intA = (this.a * 255) | 0;
  2042. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to linear space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toLinearSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toLinearSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the linear space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. /**
  2066. * Computes a new Color4 converted from the current one to gamma space
  2067. * @returns a new Color4 object
  2068. */
  2069. Color4.prototype.toGammaSpace = function () {
  2070. var convertedColor = new Color4();
  2071. this.toGammaSpaceToRef(convertedColor);
  2072. return convertedColor;
  2073. };
  2074. /**
  2075. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2076. * @param convertedColor defines the Color4 object where to store the gamma space version
  2077. * @returns the unmodified Color4
  2078. */
  2079. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2080. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2081. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2082. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2083. convertedColor.a = this.a;
  2084. return this;
  2085. };
  2086. // Statics
  2087. /**
  2088. * Creates a new Color4 from the string containing valid hexadecimal values
  2089. * @param hex defines a string containing valid hexadecimal values
  2090. * @returns a new Color4 object
  2091. */
  2092. Color4.FromHexString = function (hex) {
  2093. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2094. return new Color4(0.0, 0.0, 0.0, 0.0);
  2095. }
  2096. var r = parseInt(hex.substring(1, 3), 16);
  2097. var g = parseInt(hex.substring(3, 5), 16);
  2098. var b = parseInt(hex.substring(5, 7), 16);
  2099. var a = parseInt(hex.substring(7, 9), 16);
  2100. return Color4.FromInts(r, g, b, a);
  2101. };
  2102. /**
  2103. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2104. * @param left defines the start value
  2105. * @param right defines the end value
  2106. * @param amount defines the gradient factor
  2107. * @returns a new Color4 object
  2108. */
  2109. Color4.Lerp = function (left, right, amount) {
  2110. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2111. Color4.LerpToRef(left, right, amount, result);
  2112. return result;
  2113. };
  2114. /**
  2115. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2116. * @param left defines the start value
  2117. * @param right defines the end value
  2118. * @param amount defines the gradient factor
  2119. * @param result defines the Color4 object where to store data
  2120. */
  2121. Color4.LerpToRef = function (left, right, amount, result) {
  2122. result.r = left.r + (right.r - left.r) * amount;
  2123. result.g = left.g + (right.g - left.g) * amount;
  2124. result.b = left.b + (right.b - left.b) * amount;
  2125. result.a = left.a + (right.a - left.a) * amount;
  2126. };
  2127. /**
  2128. * Creates a new Color4 from the starting index element of the passed array
  2129. * @param array defines the source array to read from
  2130. * @param offset defines the offset in the source array
  2131. * @returns a new Color4 object
  2132. */
  2133. Color4.FromArray = function (array, offset) {
  2134. if (offset === void 0) { offset = 0; }
  2135. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2136. };
  2137. /**
  2138. * Creates a new Color3 from integer values (< 256)
  2139. * @param r defines the red component to read from (value between 0 and 255)
  2140. * @param g defines the green component to read from (value between 0 and 255)
  2141. * @param b defines the blue component to read from (value between 0 and 255)
  2142. * @param a defines the alpha component to read from (value between 0 and 255)
  2143. * @returns a new Color3 object
  2144. */
  2145. Color4.FromInts = function (r, g, b, a) {
  2146. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2147. };
  2148. /**
  2149. * Check the content of a given array and convert it to an array containing RGBA data
  2150. * If the original array was already containing count * 4 values then it is returned directly
  2151. * @param colors defines the array to check
  2152. * @param count defines the number of RGBA data to expect
  2153. * @returns an array containing count * 4 values (RGBA)
  2154. */
  2155. Color4.CheckColors4 = function (colors, count) {
  2156. // Check if color3 was used
  2157. if (colors.length === count * 3) {
  2158. var colors4 = [];
  2159. for (var index = 0; index < colors.length; index += 3) {
  2160. var newIndex = (index / 3) * 4;
  2161. colors4[newIndex] = colors[index];
  2162. colors4[newIndex + 1] = colors[index + 1];
  2163. colors4[newIndex + 2] = colors[index + 2];
  2164. colors4[newIndex + 3] = 1.0;
  2165. }
  2166. return colors4;
  2167. }
  2168. return colors;
  2169. };
  2170. return Color4;
  2171. }());
  2172. BABYLON.Color4 = Color4;
  2173. var Vector2 = /** @class */ (function () {
  2174. /**
  2175. * Creates a new Vector2 from the passed x and y coordinates.
  2176. */
  2177. function Vector2(x, y) {
  2178. this.x = x;
  2179. this.y = y;
  2180. }
  2181. /**
  2182. * Returns a string with the Vector2 coordinates.
  2183. */
  2184. Vector2.prototype.toString = function () {
  2185. return "{X: " + this.x + " Y:" + this.y + "}";
  2186. };
  2187. /**
  2188. * Returns the string "Vector2"
  2189. */
  2190. Vector2.prototype.getClassName = function () {
  2191. return "Vector2";
  2192. };
  2193. /**
  2194. * Returns the Vector2 hash code as a number.
  2195. */
  2196. Vector2.prototype.getHashCode = function () {
  2197. var hash = this.x || 0;
  2198. hash = (hash * 397) ^ (this.y || 0);
  2199. return hash;
  2200. };
  2201. // Operators
  2202. /**
  2203. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2204. * Returns the Vector2.
  2205. */
  2206. Vector2.prototype.toArray = function (array, index) {
  2207. if (index === void 0) { index = 0; }
  2208. array[index] = this.x;
  2209. array[index + 1] = this.y;
  2210. return this;
  2211. };
  2212. /**
  2213. * Returns a new array with 2 elements : the Vector2 coordinates.
  2214. */
  2215. Vector2.prototype.asArray = function () {
  2216. var result = new Array();
  2217. this.toArray(result, 0);
  2218. return result;
  2219. };
  2220. /**
  2221. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2222. * Returns the updated Vector2.
  2223. */
  2224. Vector2.prototype.copyFrom = function (source) {
  2225. this.x = source.x;
  2226. this.y = source.y;
  2227. return this;
  2228. };
  2229. /**
  2230. * Sets the Vector2 coordinates with the passed floats.
  2231. * Returns the updated Vector2.
  2232. */
  2233. Vector2.prototype.copyFromFloats = function (x, y) {
  2234. this.x = x;
  2235. this.y = y;
  2236. return this;
  2237. };
  2238. /**
  2239. * Sets the Vector2 coordinates with the passed floats.
  2240. * Returns the updated Vector2.
  2241. */
  2242. Vector2.prototype.set = function (x, y) {
  2243. return this.copyFromFloats(x, y);
  2244. };
  2245. /**
  2246. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2247. */
  2248. Vector2.prototype.add = function (otherVector) {
  2249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2250. };
  2251. /**
  2252. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2253. * Returns the Vector2.
  2254. */
  2255. Vector2.prototype.addToRef = function (otherVector, result) {
  2256. result.x = this.x + otherVector.x;
  2257. result.y = this.y + otherVector.y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.addInPlace = function (otherVector) {
  2265. this.x += otherVector.x;
  2266. this.y += otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2271. */
  2272. Vector2.prototype.addVector3 = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2277. */
  2278. Vector2.prototype.subtract = function (otherVector) {
  2279. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2280. };
  2281. /**
  2282. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2283. * Returns the Vector2.
  2284. */
  2285. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2286. result.x = this.x - otherVector.x;
  2287. result.y = this.y - otherVector.y;
  2288. return this;
  2289. };
  2290. /**
  2291. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2292. * Returns the updated Vector2.
  2293. */
  2294. Vector2.prototype.subtractInPlace = function (otherVector) {
  2295. this.x -= otherVector.x;
  2296. this.y -= otherVector.y;
  2297. return this;
  2298. };
  2299. /**
  2300. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2301. * Returns the updated Vector2.
  2302. */
  2303. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2304. this.x *= otherVector.x;
  2305. this.y *= otherVector.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2310. */
  2311. Vector2.prototype.multiply = function (otherVector) {
  2312. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2313. };
  2314. /**
  2315. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2319. result.x = this.x * otherVector.x;
  2320. result.y = this.y * otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2325. */
  2326. Vector2.prototype.multiplyByFloats = function (x, y) {
  2327. return new Vector2(this.x * x, this.y * y);
  2328. };
  2329. /**
  2330. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2331. */
  2332. Vector2.prototype.divide = function (otherVector) {
  2333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2337. * Returns the Vector2.
  2338. */
  2339. Vector2.prototype.divideToRef = function (otherVector, result) {
  2340. result.x = this.x / otherVector.x;
  2341. result.y = this.y / otherVector.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Divides the current Vector3 coordinates by the passed ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector2.prototype.divideInPlace = function (otherVector) {
  2349. return this.divideToRef(otherVector, this);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 with current Vector2 negated coordinates.
  2353. */
  2354. Vector2.prototype.negate = function () {
  2355. return new Vector2(-this.x, -this.y);
  2356. };
  2357. /**
  2358. * Multiply the Vector2 coordinates by scale.
  2359. * Returns the updated Vector2.
  2360. */
  2361. Vector2.prototype.scaleInPlace = function (scale) {
  2362. this.x *= scale;
  2363. this.y *= scale;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2368. */
  2369. Vector2.prototype.scale = function (scale) {
  2370. var result = new Vector2(0, 0);
  2371. this.scaleToRef(scale, result);
  2372. return result;
  2373. };
  2374. /**
  2375. * Scale the current Vector2 values by a factor to a given Vector2
  2376. * @param scale defines the scale factor
  2377. * @param result defines the Vector2 object where to store the result
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.scaleToRef = function (scale, result) {
  2381. result.x = this.x * scale;
  2382. result.y = this.y * scale;
  2383. return this;
  2384. };
  2385. /**
  2386. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2387. * @param scale defines the scale factor
  2388. * @param result defines the Vector2 object where to store the result
  2389. * @returns the unmodified current Vector2
  2390. */
  2391. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2392. result.x += this.x * scale;
  2393. result.y += this.y * scale;
  2394. return this;
  2395. };
  2396. /**
  2397. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2398. */
  2399. Vector2.prototype.equals = function (otherVector) {
  2400. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2401. };
  2402. /**
  2403. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2404. */
  2405. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2406. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2407. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2408. };
  2409. // Properties
  2410. /**
  2411. * Returns the vector length (float).
  2412. */
  2413. Vector2.prototype.length = function () {
  2414. return Math.sqrt(this.x * this.x + this.y * this.y);
  2415. };
  2416. /**
  2417. * Returns the vector squared length (float);
  2418. */
  2419. Vector2.prototype.lengthSquared = function () {
  2420. return (this.x * this.x + this.y * this.y);
  2421. };
  2422. // Methods
  2423. /**
  2424. * Normalize the vector.
  2425. * Returns the updated Vector2.
  2426. */
  2427. Vector2.prototype.normalize = function () {
  2428. var len = this.length();
  2429. if (len === 0)
  2430. return this;
  2431. var num = 1.0 / len;
  2432. this.x *= num;
  2433. this.y *= num;
  2434. return this;
  2435. };
  2436. /**
  2437. * Returns a new Vector2 copied from the Vector2.
  2438. */
  2439. Vector2.prototype.clone = function () {
  2440. return new Vector2(this.x, this.y);
  2441. };
  2442. // Statics
  2443. /**
  2444. * Returns a new Vector2(0, 0)
  2445. */
  2446. Vector2.Zero = function () {
  2447. return new Vector2(0, 0);
  2448. };
  2449. /**
  2450. * Returns a new Vector2(1, 1)
  2451. */
  2452. Vector2.One = function () {
  2453. return new Vector2(1, 1);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 set from the passed index element of the passed array.
  2457. */
  2458. Vector2.FromArray = function (array, offset) {
  2459. if (offset === void 0) { offset = 0; }
  2460. return new Vector2(array[offset], array[offset + 1]);
  2461. };
  2462. /**
  2463. * Sets "result" from the passed index element of the passed array.
  2464. */
  2465. Vector2.FromArrayToRef = function (array, offset, result) {
  2466. result.x = array[offset];
  2467. result.y = array[offset + 1];
  2468. };
  2469. /**
  2470. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2471. */
  2472. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2473. var squared = amount * amount;
  2474. var cubed = amount * squared;
  2475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2481. return new Vector2(x, y);
  2482. };
  2483. /**
  2484. * 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".
  2485. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2486. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2487. */
  2488. Vector2.Clamp = function (value, min, max) {
  2489. var x = value.x;
  2490. x = (x > max.x) ? max.x : x;
  2491. x = (x < min.x) ? min.x : x;
  2492. var y = value.y;
  2493. y = (y > max.y) ? max.y : y;
  2494. y = (y < min.y) ? min.y : y;
  2495. return new Vector2(x, y);
  2496. };
  2497. /**
  2498. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2499. */
  2500. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2501. var squared = amount * amount;
  2502. var cubed = amount * squared;
  2503. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2504. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2505. var part3 = (cubed - (2.0 * squared)) + amount;
  2506. var part4 = cubed - squared;
  2507. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2508. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2509. return new Vector2(x, y);
  2510. };
  2511. /**
  2512. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2513. */
  2514. Vector2.Lerp = function (start, end, amount) {
  2515. var x = start.x + ((end.x - start.x) * amount);
  2516. var y = start.y + ((end.y - start.y) * amount);
  2517. return new Vector2(x, y);
  2518. };
  2519. /**
  2520. * Returns the dot product (float) of the vector "left" and the vector "right".
  2521. */
  2522. Vector2.Dot = function (left, right) {
  2523. return left.x * right.x + left.y * right.y;
  2524. };
  2525. /**
  2526. * Returns a new Vector2 equal to the normalized passed vector.
  2527. */
  2528. Vector2.Normalize = function (vector) {
  2529. var newVector = vector.clone();
  2530. newVector.normalize();
  2531. return newVector;
  2532. };
  2533. /**
  2534. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2535. */
  2536. Vector2.Minimize = function (left, right) {
  2537. var x = (left.x < right.x) ? left.x : right.x;
  2538. var y = (left.y < right.y) ? left.y : right.y;
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2543. */
  2544. Vector2.Maximize = function (left, right) {
  2545. var x = (left.x > right.x) ? left.x : right.x;
  2546. var y = (left.y > right.y) ? left.y : right.y;
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2551. */
  2552. Vector2.Transform = function (vector, transformation) {
  2553. var r = Vector2.Zero();
  2554. Vector2.TransformToRef(vector, transformation, r);
  2555. return r;
  2556. };
  2557. /**
  2558. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2559. */
  2560. Vector2.TransformToRef = function (vector, transformation, result) {
  2561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2563. result.x = x;
  2564. result.y = y;
  2565. };
  2566. /**
  2567. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2568. */
  2569. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2570. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2571. var sign = a < 0 ? -1 : 1;
  2572. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2573. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2574. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2575. };
  2576. /**
  2577. * Returns the distance (float) between the vectors "value1" and "value2".
  2578. */
  2579. Vector2.Distance = function (value1, value2) {
  2580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2581. };
  2582. /**
  2583. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2584. */
  2585. Vector2.DistanceSquared = function (value1, value2) {
  2586. var x = value1.x - value2.x;
  2587. var y = value1.y - value2.y;
  2588. return (x * x) + (y * y);
  2589. };
  2590. /**
  2591. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2592. */
  2593. Vector2.Center = function (value1, value2) {
  2594. var center = value1.add(value2);
  2595. center.scaleInPlace(0.5);
  2596. return center;
  2597. };
  2598. /**
  2599. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2600. */
  2601. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2602. var l2 = Vector2.DistanceSquared(segA, segB);
  2603. if (l2 === 0.0) {
  2604. return Vector2.Distance(p, segA);
  2605. }
  2606. var v = segB.subtract(segA);
  2607. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2608. var proj = segA.add(v.multiplyByFloats(t, t));
  2609. return Vector2.Distance(p, proj);
  2610. };
  2611. return Vector2;
  2612. }());
  2613. BABYLON.Vector2 = Vector2;
  2614. /**
  2615. * Classed used to store (x,y,z) vector representation
  2616. * A Vector3 is the main object used in 3D geometry
  2617. * It can represent etiher the coordinates of a point the space, either a direction
  2618. * Reminder: Babylon.js uses a left handed forward facing system
  2619. */
  2620. var Vector3 = /** @class */ (function () {
  2621. /**
  2622. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2623. * @param x defines the first coordinates (on X axis)
  2624. * @param y defines the second coordinates (on Y axis)
  2625. * @param z defines the third coordinates (on Z axis)
  2626. */
  2627. function Vector3(
  2628. /**
  2629. * Defines the first coordinates (on X axis)
  2630. */
  2631. x,
  2632. /**
  2633. * Defines the second coordinates (on Y axis)
  2634. */
  2635. y,
  2636. /**
  2637. * Defines the third coordinates (on Z axis)
  2638. */
  2639. z) {
  2640. this.x = x;
  2641. this.y = y;
  2642. this.z = z;
  2643. }
  2644. /**
  2645. * Creates a string representation of the Vector3
  2646. * @returns a string with the Vector3 coordinates.
  2647. */
  2648. Vector3.prototype.toString = function () {
  2649. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2650. };
  2651. /**
  2652. * Gets the class name
  2653. * @returns the string "Vector3"
  2654. */
  2655. Vector3.prototype.getClassName = function () {
  2656. return "Vector3";
  2657. };
  2658. /**
  2659. * Creates the Vector3 hash code
  2660. * @returns a number which tends to be unique between Vector3 instances
  2661. */
  2662. Vector3.prototype.getHashCode = function () {
  2663. var hash = this.x || 0;
  2664. hash = (hash * 397) ^ (this.y || 0);
  2665. hash = (hash * 397) ^ (this.z || 0);
  2666. return hash;
  2667. };
  2668. // Operators
  2669. /**
  2670. * Creates an array containing three elements : the coordinates of the Vector3
  2671. * @returns a new array of numbers
  2672. */
  2673. Vector3.prototype.asArray = function () {
  2674. var result = [];
  2675. this.toArray(result, 0);
  2676. return result;
  2677. };
  2678. /**
  2679. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2680. * @param array defines the destination array
  2681. * @param index defines the offset in the destination array
  2682. * @returns the current Vector3
  2683. */
  2684. Vector3.prototype.toArray = function (array, index) {
  2685. if (index === void 0) { index = 0; }
  2686. array[index] = this.x;
  2687. array[index + 1] = this.y;
  2688. array[index + 2] = this.z;
  2689. return this;
  2690. };
  2691. /**
  2692. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2693. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2694. */
  2695. Vector3.prototype.toQuaternion = function () {
  2696. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2697. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2698. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2699. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2700. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2701. var cosy = Math.cos(this.y * 0.5);
  2702. var siny = Math.sin(this.y * 0.5);
  2703. result.x = coszMinusx * siny;
  2704. result.y = -sinzMinusx * siny;
  2705. result.z = sinxPlusz * cosy;
  2706. result.w = cosxPlusz * cosy;
  2707. return result;
  2708. };
  2709. /**
  2710. * Adds the passed vector to the current Vector3
  2711. * @param otherVector defines the second operand
  2712. * @returns the current updated Vector3
  2713. */
  2714. Vector3.prototype.addInPlace = function (otherVector) {
  2715. this.x += otherVector.x;
  2716. this.y += otherVector.y;
  2717. this.z += otherVector.z;
  2718. return this;
  2719. };
  2720. /**
  2721. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2722. * @param otherVector defines the second operand
  2723. * @returns the resulting Vector3
  2724. */
  2725. Vector3.prototype.add = function (otherVector) {
  2726. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2727. };
  2728. /**
  2729. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2730. * @param otherVector defines the second operand
  2731. * @param result defines the Vector3 object where to store the result
  2732. * @returns the current Vector3
  2733. */
  2734. Vector3.prototype.addToRef = function (otherVector, result) {
  2735. result.x = this.x + otherVector.x;
  2736. result.y = this.y + otherVector.y;
  2737. result.z = this.z + otherVector.z;
  2738. return this;
  2739. };
  2740. /**
  2741. * Subtract the passed vector from the current Vector3
  2742. * @param otherVector defines the second operand
  2743. * @returns the current updated Vector3
  2744. */
  2745. Vector3.prototype.subtractInPlace = function (otherVector) {
  2746. this.x -= otherVector.x;
  2747. this.y -= otherVector.y;
  2748. this.z -= otherVector.z;
  2749. return this;
  2750. };
  2751. /**
  2752. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2753. * @param otherVector defines the second operand
  2754. * @returns the resulting Vector3
  2755. */
  2756. Vector3.prototype.subtract = function (otherVector) {
  2757. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2758. };
  2759. /**
  2760. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2761. * @param otherVector defines the second operand
  2762. * @param result defines the Vector3 object where to store the result
  2763. * @returns the current Vector3
  2764. */
  2765. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2766. result.x = this.x - otherVector.x;
  2767. result.y = this.y - otherVector.y;
  2768. result.z = this.z - otherVector.z;
  2769. return this;
  2770. };
  2771. /**
  2772. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2773. * @param x defines the x coordinate of the operand
  2774. * @param y defines the y coordinate of the operand
  2775. * @param z defines the z coordinate of the operand
  2776. * @returns the resulting Vector3
  2777. */
  2778. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2779. return new Vector3(this.x - x, this.y - y, this.z - z);
  2780. };
  2781. /**
  2782. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @param result defines the Vector3 object where to store the result
  2787. * @returns the current Vector3
  2788. */
  2789. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2790. result.x = this.x - x;
  2791. result.y = this.y - y;
  2792. result.z = this.z - z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2797. * @returns a new Vector3
  2798. */
  2799. Vector3.prototype.negate = function () {
  2800. return new Vector3(-this.x, -this.y, -this.z);
  2801. };
  2802. /**
  2803. * Multiplies the Vector3 coordinates by the float "scale"
  2804. * @param scale defines the multiplier factor
  2805. * @returns the current updated Vector3
  2806. */
  2807. Vector3.prototype.scaleInPlace = function (scale) {
  2808. this.x *= scale;
  2809. this.y *= scale;
  2810. this.z *= scale;
  2811. return this;
  2812. };
  2813. /**
  2814. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2815. * @param scale defines the multiplier factor
  2816. * @returns a new Vector3
  2817. */
  2818. Vector3.prototype.scale = function (scale) {
  2819. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2820. };
  2821. /**
  2822. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2823. * @param scale defines the multiplier factor
  2824. * @param result defines the Vector3 object where to store the result
  2825. * @returns the current Vector3
  2826. */
  2827. Vector3.prototype.scaleToRef = function (scale, result) {
  2828. result.x = this.x * scale;
  2829. result.y = this.y * scale;
  2830. result.z = this.z * scale;
  2831. return this;
  2832. };
  2833. /**
  2834. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2835. * @param scale defines the scale factor
  2836. * @param result defines the Vector3 object where to store the result
  2837. * @returns the unmodified current Vector3
  2838. */
  2839. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2840. result.x += this.x * scale;
  2841. result.y += this.y * scale;
  2842. result.z += this.z * scale;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2847. * @param otherVector defines the second operand
  2848. * @returns true if both vectors are equals
  2849. */
  2850. Vector3.prototype.equals = function (otherVector) {
  2851. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2852. };
  2853. /**
  2854. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2855. * @param otherVector defines the second operand
  2856. * @param epsilon defines the minimal distance to define values as equals
  2857. * @returns true if both vectors are distant less than epsilon
  2858. */
  2859. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2860. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2861. 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);
  2862. };
  2863. /**
  2864. * Returns true if the current Vector3 coordinates equals the passed floats
  2865. * @param x defines the x coordinate of the operand
  2866. * @param y defines the y coordinate of the operand
  2867. * @param z defines the z coordinate of the operand
  2868. * @returns true if both vectors are equals
  2869. */
  2870. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2871. return this.x === x && this.y === y && this.z === z;
  2872. };
  2873. /**
  2874. * Multiplies the current Vector3 coordinates by the passed ones
  2875. * @param otherVector defines the second operand
  2876. * @returns the current updated Vector3
  2877. */
  2878. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2879. this.x *= otherVector.x;
  2880. this.y *= otherVector.y;
  2881. this.z *= otherVector.z;
  2882. return this;
  2883. };
  2884. /**
  2885. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2886. * @param otherVector defines the second operand
  2887. * @returns the new Vector3
  2888. */
  2889. Vector3.prototype.multiply = function (otherVector) {
  2890. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2891. };
  2892. /**
  2893. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2894. * @param otherVector defines the second operand
  2895. * @param result defines the Vector3 object where to store the result
  2896. * @returns the current Vector3
  2897. */
  2898. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2899. result.x = this.x * otherVector.x;
  2900. result.y = this.y * otherVector.y;
  2901. result.z = this.z * otherVector.z;
  2902. return this;
  2903. };
  2904. /**
  2905. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2906. * @param x defines the x coordinate of the operand
  2907. * @param y defines the y coordinate of the operand
  2908. * @param z defines the z coordinate of the operand
  2909. * @returns the new Vector3
  2910. */
  2911. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2912. return new Vector3(this.x * x, this.y * y, this.z * z);
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2916. * @param otherVector defines the second operand
  2917. * @returns the new Vector3
  2918. */
  2919. Vector3.prototype.divide = function (otherVector) {
  2920. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2921. };
  2922. /**
  2923. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2924. * @param otherVector defines the second operand
  2925. * @param result defines the Vector3 object where to store the result
  2926. * @returns the current Vector3
  2927. */
  2928. Vector3.prototype.divideToRef = function (otherVector, result) {
  2929. result.x = this.x / otherVector.x;
  2930. result.y = this.y / otherVector.y;
  2931. result.z = this.z / otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.divideInPlace = function (otherVector) {
  2940. return this.divideToRef(otherVector, this);
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.minimizeInPlace = function (other) {
  2948. if (other.x < this.x)
  2949. this.x = other.x;
  2950. if (other.y < this.y)
  2951. this.y = other.y;
  2952. if (other.z < this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2958. * @param other defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.maximizeInPlace = function (other) {
  2962. if (other.x > this.x)
  2963. this.x = other.x;
  2964. if (other.y > this.y)
  2965. this.y = other.y;
  2966. if (other.z > this.z)
  2967. this.z = other.z;
  2968. return this;
  2969. };
  2970. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2971. /**
  2972. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2973. */
  2974. get: function () {
  2975. var absX = Math.abs(this.x);
  2976. var absY = Math.abs(this.y);
  2977. if (absX !== absY) {
  2978. return true;
  2979. }
  2980. var absZ = Math.abs(this.z);
  2981. if (absX !== absZ) {
  2982. return true;
  2983. }
  2984. if (absY !== absZ) {
  2985. return true;
  2986. }
  2987. return false;
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. // Properties
  2993. /**
  2994. * Gets the length of the Vector3
  2995. * @returns the length of the Vecto3
  2996. */
  2997. Vector3.prototype.length = function () {
  2998. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2999. };
  3000. /**
  3001. * Gets the squared length of the Vector3
  3002. * @returns squared length of the Vector3
  3003. */
  3004. Vector3.prototype.lengthSquared = function () {
  3005. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3006. };
  3007. /**
  3008. * Normalize the current Vector3.
  3009. * Please note that this is an in place operation.
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.normalize = function () {
  3013. var len = this.length();
  3014. if (len === 0 || len === 1.0)
  3015. return this;
  3016. var num = 1.0 / len;
  3017. this.x *= num;
  3018. this.y *= num;
  3019. this.z *= num;
  3020. return this;
  3021. };
  3022. /**
  3023. * Normalize the current Vector3 to a new vector
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.normalizeToNew = function () {
  3027. var normalized = new Vector3(0, 0, 0);
  3028. this.normalizeToRef(normalized);
  3029. return normalized;
  3030. };
  3031. /**
  3032. * Normalize the current Vector3 to the reference
  3033. * @param reference define the Vector3 to update
  3034. * @returns the updated Vector3
  3035. */
  3036. Vector3.prototype.normalizeToRef = function (reference) {
  3037. var len = this.length();
  3038. if (len === 0 || len === 1.0) {
  3039. reference.set(this.x, this.y, this.z);
  3040. return reference;
  3041. }
  3042. var scale = 1.0 / len;
  3043. this.scaleToRef(scale, reference);
  3044. return reference;
  3045. };
  3046. /**
  3047. * Creates a new Vector3 copied from the current Vector3
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.clone = function () {
  3051. return new Vector3(this.x, this.y, this.z);
  3052. };
  3053. /**
  3054. * Copies the passed vector coordinates to the current Vector3 ones
  3055. * @param source defines the source Vector3
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.copyFrom = function (source) {
  3059. this.x = source.x;
  3060. this.y = source.y;
  3061. this.z = source.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Copies the passed floats to the current Vector3 coordinates
  3066. * @param x defines the x coordinate of the operand
  3067. * @param y defines the y coordinate of the operand
  3068. * @param z defines the z coordinate of the operand
  3069. * @returns the current updated Vector3
  3070. */
  3071. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3072. this.x = x;
  3073. this.y = y;
  3074. this.z = z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Copies the passed floats to the current Vector3 coordinates
  3079. * @param x defines the x coordinate of the operand
  3080. * @param y defines the y coordinate of the operand
  3081. * @param z defines the z coordinate of the operand
  3082. * @returns the current updated Vector3
  3083. */
  3084. Vector3.prototype.set = function (x, y, z) {
  3085. return this.copyFromFloats(x, y, z);
  3086. };
  3087. // Statics
  3088. /**
  3089. * Get the clip factor between two vectors
  3090. * @param vector0 defines the first operand
  3091. * @param vector1 defines the second operand
  3092. * @param axis defines the axis to use
  3093. * @param size defines the size along the axis
  3094. * @returns the clip factor
  3095. */
  3096. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3097. var d0 = Vector3.Dot(vector0, axis) - size;
  3098. var d1 = Vector3.Dot(vector1, axis) - size;
  3099. var s = d0 / (d0 - d1);
  3100. return s;
  3101. };
  3102. /**
  3103. * Get angle between two vectors
  3104. * @param vector0 angle between vector0 and vector1
  3105. * @param vector1 angle between vector0 and vector1
  3106. * @param normal direction of the normal
  3107. * @return the angle between vector0 and vector1
  3108. */
  3109. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3110. var v0 = vector0.clone().normalize();
  3111. var v1 = vector1.clone().normalize();
  3112. var dot = Vector3.Dot(v0, v1);
  3113. var n = Vector3.Cross(v0, v1);
  3114. if (Vector3.Dot(n, normal) > 0) {
  3115. return Math.acos(dot);
  3116. }
  3117. return -Math.acos(dot);
  3118. };
  3119. /**
  3120. * Returns a new Vector3 set from the index "offset" of the passed array
  3121. * @param array defines the source array
  3122. * @param offset defines the offset in the source array
  3123. * @returns the new Vector3
  3124. */
  3125. Vector3.FromArray = function (array, offset) {
  3126. if (!offset) {
  3127. offset = 0;
  3128. }
  3129. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3133. * This function is deprecated. Use FromArray instead
  3134. * @param array defines the source array
  3135. * @param offset defines the offset in the source array
  3136. * @returns the new Vector3
  3137. */
  3138. Vector3.FromFloatArray = function (array, offset) {
  3139. return Vector3.FromArray(array, offset);
  3140. };
  3141. /**
  3142. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3143. * @param array defines the source array
  3144. * @param offset defines the offset in the source array
  3145. * @param result defines the Vector3 where to store the result
  3146. */
  3147. Vector3.FromArrayToRef = function (array, offset, result) {
  3148. result.x = array[offset];
  3149. result.y = array[offset + 1];
  3150. result.z = array[offset + 2];
  3151. };
  3152. /**
  3153. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3154. * This function is deprecated. Use FromArrayToRef instead.
  3155. * @param array defines the source array
  3156. * @param offset defines the offset in the source array
  3157. * @param result defines the Vector3 where to store the result
  3158. */
  3159. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3160. return Vector3.FromArrayToRef(array, offset, result);
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" with the passed floats.
  3164. * @param x defines the x coordinate of the source
  3165. * @param y defines the y coordinate of the source
  3166. * @param z defines the z coordinate of the source
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3170. result.x = x;
  3171. result.y = y;
  3172. result.z = z;
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3176. * @returns a new empty Vector3
  3177. */
  3178. Vector3.Zero = function () {
  3179. return new Vector3(0.0, 0.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3183. * @returns a new unit Vector3
  3184. */
  3185. Vector3.One = function () {
  3186. return new Vector3(1.0, 1.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3190. * @returns a new up Vector3
  3191. */
  3192. Vector3.Up = function () {
  3193. return new Vector3(0.0, 1.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3197. * @returns a new forward Vector3
  3198. */
  3199. Vector3.Forward = function () {
  3200. return new Vector3(0.0, 0.0, 1.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3204. * @returns a new right Vector3
  3205. */
  3206. Vector3.Right = function () {
  3207. return new Vector3(1.0, 0.0, 0.0);
  3208. };
  3209. /**
  3210. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3211. * @returns a new left Vector3
  3212. */
  3213. Vector3.Left = function () {
  3214. return new Vector3(-1.0, 0.0, 0.0);
  3215. };
  3216. /**
  3217. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3218. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3219. * @param vector defines the Vector3 to transform
  3220. * @param transformation defines the transformation matrix
  3221. * @returns the transformed Vector3
  3222. */
  3223. Vector3.TransformCoordinates = function (vector, transformation) {
  3224. var result = Vector3.Zero();
  3225. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3226. return result;
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3230. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3231. * @param vector defines the Vector3 to transform
  3232. * @param transformation defines the transformation matrix
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3236. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3237. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3238. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3239. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3240. result.x = x / w;
  3241. result.y = y / w;
  3242. result.z = z / w;
  3243. };
  3244. /**
  3245. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3246. * This method computes tranformed coordinates only, not transformed direction vectors
  3247. * @param x define the x coordinate of the source vector
  3248. * @param y define the y coordinate of the source vector
  3249. * @param z define the z coordinate of the source vector
  3250. * @param transformation defines the transformation matrix
  3251. * @param result defines the Vector3 where to store the result
  3252. */
  3253. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3254. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3255. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3256. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3257. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3258. result.x = rx / rw;
  3259. result.y = ry / rw;
  3260. result.z = rz / rw;
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3264. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3265. * @param vector defines the Vector3 to transform
  3266. * @param transformation defines the transformation matrix
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.TransformNormal = function (vector, transformation) {
  3270. var result = Vector3.Zero();
  3271. Vector3.TransformNormalToRef(vector, transformation, result);
  3272. return result;
  3273. };
  3274. /**
  3275. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3276. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3277. * @param vector defines the Vector3 to transform
  3278. * @param transformation defines the transformation matrix
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3282. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3283. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3284. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3285. result.x = x;
  3286. result.y = y;
  3287. result.z = z;
  3288. };
  3289. /**
  3290. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3291. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3292. * @param x define the x coordinate of the source vector
  3293. * @param y define the y coordinate of the source vector
  3294. * @param z define the z coordinate of the source vector
  3295. * @param transformation defines the transformation matrix
  3296. * @param result defines the Vector3 where to store the result
  3297. */
  3298. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3299. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3300. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3301. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3305. * @param value1 defines the first control point
  3306. * @param value2 defines the second control point
  3307. * @param value3 defines the third control point
  3308. * @param value4 defines the fourth control point
  3309. * @param amount defines the amount on the spline to use
  3310. * @returns the new Vector3
  3311. */
  3312. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3313. var squared = amount * amount;
  3314. var cubed = amount * squared;
  3315. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3316. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3317. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3318. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3319. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3320. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3321. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3322. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3323. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3324. return new Vector3(x, y, z);
  3325. };
  3326. /**
  3327. * 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"
  3328. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3329. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3330. * @param value defines the current value
  3331. * @param min defines the lower range value
  3332. * @param max defines the upper range value
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.Clamp = function (value, min, max) {
  3336. var x = value.x;
  3337. x = (x > max.x) ? max.x : x;
  3338. x = (x < min.x) ? min.x : x;
  3339. var y = value.y;
  3340. y = (y > max.y) ? max.y : y;
  3341. y = (y < min.y) ? min.y : y;
  3342. var z = value.z;
  3343. z = (z > max.z) ? max.z : z;
  3344. z = (z < min.z) ? min.z : z;
  3345. return new Vector3(x, y, z);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3349. * @param value1 defines the first control point
  3350. * @param tangent1 defines the first tangent vector
  3351. * @param value2 defines the second control point
  3352. * @param tangent2 defines the second tangent vector
  3353. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3357. var squared = amount * amount;
  3358. var cubed = amount * squared;
  3359. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3360. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3361. var part3 = (cubed - (2.0 * squared)) + amount;
  3362. var part4 = cubed - squared;
  3363. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3364. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3365. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3366. return new Vector3(x, y, z);
  3367. };
  3368. /**
  3369. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3370. * @param start defines the start value
  3371. * @param end defines the end value
  3372. * @param amount max defines amount between both (between 0 and 1)
  3373. * @returns the new Vector3
  3374. */
  3375. Vector3.Lerp = function (start, end, amount) {
  3376. var result = new Vector3(0, 0, 0);
  3377. Vector3.LerpToRef(start, end, amount, result);
  3378. return result;
  3379. };
  3380. /**
  3381. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3382. * @param start defines the start value
  3383. * @param end defines the end value
  3384. * @param amount max defines amount between both (between 0 and 1)
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.LerpToRef = function (start, end, amount, result) {
  3388. result.x = start.x + ((end.x - start.x) * amount);
  3389. result.y = start.y + ((end.y - start.y) * amount);
  3390. result.z = start.z + ((end.z - start.z) * amount);
  3391. };
  3392. /**
  3393. * Returns the dot product (float) between the vectors "left" and "right"
  3394. * @param left defines the left operand
  3395. * @param right defines the right operand
  3396. * @returns the dot product
  3397. */
  3398. Vector3.Dot = function (left, right) {
  3399. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3403. * The cross product is then orthogonal to both "left" and "right"
  3404. * @param left defines the left operand
  3405. * @param right defines the right operand
  3406. * @returns the cross product
  3407. */
  3408. Vector3.Cross = function (left, right) {
  3409. var result = Vector3.Zero();
  3410. Vector3.CrossToRef(left, right, result);
  3411. return result;
  3412. };
  3413. /**
  3414. * Sets the passed vector "result" with the cross product of "left" and "right"
  3415. * The cross product is then orthogonal to both "left" and "right"
  3416. * @param left defines the left operand
  3417. * @param right defines the right operand
  3418. * @param result defines the Vector3 where to store the result
  3419. */
  3420. Vector3.CrossToRef = function (left, right, result) {
  3421. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3422. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3423. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3424. result.copyFrom(MathTmp.Vector3[0]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 as the normalization of the passed vector
  3428. * @param vector defines the Vector3 to normalize
  3429. * @returns the new Vector3
  3430. */
  3431. Vector3.Normalize = function (vector) {
  3432. var result = Vector3.Zero();
  3433. Vector3.NormalizeToRef(vector, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * Sets the passed vector "result" with the normalization of the passed first vector
  3438. * @param vector defines the Vector3 to normalize
  3439. * @param result defines the Vector3 where to store the result
  3440. */
  3441. Vector3.NormalizeToRef = function (vector, result) {
  3442. result.copyFrom(vector);
  3443. result.normalize();
  3444. };
  3445. /**
  3446. * Project a Vector3 onto screen space
  3447. * @param vector defines the Vector3 to project
  3448. * @param world defines the world matrix to use
  3449. * @param transform defines the transform (view x projection) matrix to use
  3450. * @param viewport defines the screen viewport to use
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Project = function (vector, world, transform, viewport) {
  3454. var cw = viewport.width;
  3455. var ch = viewport.height;
  3456. var cx = viewport.x;
  3457. var cy = viewport.y;
  3458. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3459. 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);
  3460. var matrix = MathTmp.Matrix[0];
  3461. world.multiplyToRef(transform, matrix);
  3462. matrix.multiplyToRef(viewportMatrix, matrix);
  3463. return Vector3.TransformCoordinates(vector, matrix);
  3464. };
  3465. /**
  3466. * Unproject from screen space to object space
  3467. * @param source defines the screen space Vector3 to use
  3468. * @param viewportWidth defines the current width of the viewport
  3469. * @param viewportHeight defines the current height of the viewport
  3470. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3471. * @param transform defines the transform (view x projection) matrix to use
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3475. var matrix = MathTmp.Matrix[0];
  3476. world.multiplyToRef(transform, matrix);
  3477. matrix.invert();
  3478. source.x = source.x / viewportWidth * 2 - 1;
  3479. source.y = -(source.y / viewportHeight * 2 - 1);
  3480. var vector = Vector3.TransformCoordinates(source, matrix);
  3481. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3482. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3483. vector = vector.scale(1.0 / num);
  3484. }
  3485. return vector;
  3486. };
  3487. /**
  3488. * Unproject from screen space to object space
  3489. * @param source defines the screen space Vector3 to use
  3490. * @param viewportWidth defines the current width of the viewport
  3491. * @param viewportHeight defines the current height of the viewport
  3492. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3493. * @param view defines the view matrix to use
  3494. * @param projection defines the projection matrix to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3498. var result = Vector3.Zero();
  3499. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Unproject from screen space to object space
  3504. * @param source defines the screen space Vector3 to use
  3505. * @param viewportWidth defines the current width of the viewport
  3506. * @param viewportHeight defines the current height of the viewport
  3507. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3508. * @param view defines the view matrix to use
  3509. * @param projection defines the projection matrix to use
  3510. * @param result defines the Vector3 where to store the result
  3511. */
  3512. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3513. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3514. };
  3515. /**
  3516. * Unproject from screen space to object space
  3517. * @param sourceX defines the screen space x coordinate to use
  3518. * @param sourceY defines the screen space y coordinate to use
  3519. * @param sourceZ defines the screen space z coordinate to use
  3520. * @param viewportWidth defines the current width of the viewport
  3521. * @param viewportHeight defines the current height of the viewport
  3522. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3523. * @param view defines the view matrix to use
  3524. * @param projection defines the projection matrix to use
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3528. var matrix = MathTmp.Matrix[0];
  3529. world.multiplyToRef(view, matrix);
  3530. matrix.multiplyToRef(projection, matrix);
  3531. matrix.invert();
  3532. var screenSource = MathTmp.Vector3[0];
  3533. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3534. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3535. screenSource.z = 2 * sourceZ - 1.0;
  3536. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3537. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3538. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3539. result.scaleInPlace(1.0 / num);
  3540. }
  3541. };
  3542. /**
  3543. * Gets the minimal coordinate values between two Vector3
  3544. * @param left defines the first operand
  3545. * @param right defines the second operand
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Minimize = function (left, right) {
  3549. var min = left.clone();
  3550. min.minimizeInPlace(right);
  3551. return min;
  3552. };
  3553. /**
  3554. * Gets the maximal coordinate values between two Vector3
  3555. * @param left defines the first operand
  3556. * @param right defines the second operand
  3557. * @returns the new Vector3
  3558. */
  3559. Vector3.Maximize = function (left, right) {
  3560. var max = left.clone();
  3561. max.maximizeInPlace(right);
  3562. return max;
  3563. };
  3564. /**
  3565. * Returns the distance between the vectors "value1" and "value2"
  3566. * @param value1 defines the first operand
  3567. * @param value2 defines the second operand
  3568. * @returns the distance
  3569. */
  3570. Vector3.Distance = function (value1, value2) {
  3571. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3572. };
  3573. /**
  3574. * Returns the squared distance between the vectors "value1" and "value2"
  3575. * @param value1 defines the first operand
  3576. * @param value2 defines the second operand
  3577. * @returns the squared distance
  3578. */
  3579. Vector3.DistanceSquared = function (value1, value2) {
  3580. var x = value1.x - value2.x;
  3581. var y = value1.y - value2.y;
  3582. var z = value1.z - value2.z;
  3583. return (x * x) + (y * y) + (z * z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located at the center between "value1" and "value2"
  3587. * @param value1 defines the first operand
  3588. * @param value2 defines the second operand
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Center = function (value1, value2) {
  3592. var center = value1.add(value2);
  3593. center.scaleInPlace(0.5);
  3594. return center;
  3595. };
  3596. /**
  3597. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3598. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3599. * to something in order to rotate it from its local system to the given target system
  3600. * Note: axis1, axis2 and axis3 are normalized during this operation
  3601. * @param axis1 defines the first axis
  3602. * @param axis2 defines the second axis
  3603. * @param axis3 defines the third axis
  3604. * @returns a new Vector3
  3605. */
  3606. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3607. var rotation = Vector3.Zero();
  3608. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3609. return rotation;
  3610. };
  3611. /**
  3612. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3613. * @param axis1 defines the first axis
  3614. * @param axis2 defines the second axis
  3615. * @param axis3 defines the third axis
  3616. * @param ref defines the Vector3 where to store the result
  3617. */
  3618. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3619. var quat = MathTmp.Quaternion[0];
  3620. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3621. quat.toEulerAnglesToRef(ref);
  3622. };
  3623. return Vector3;
  3624. }());
  3625. BABYLON.Vector3 = Vector3;
  3626. //Vector4 class created for EulerAngle class conversion to Quaternion
  3627. var Vector4 = /** @class */ (function () {
  3628. /**
  3629. * Creates a Vector4 object from the passed floats.
  3630. */
  3631. function Vector4(x, y, z, w) {
  3632. this.x = x;
  3633. this.y = y;
  3634. this.z = z;
  3635. this.w = w;
  3636. }
  3637. /**
  3638. * Returns the string with the Vector4 coordinates.
  3639. */
  3640. Vector4.prototype.toString = function () {
  3641. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3642. };
  3643. /**
  3644. * Returns the string "Vector4".
  3645. */
  3646. Vector4.prototype.getClassName = function () {
  3647. return "Vector4";
  3648. };
  3649. /**
  3650. * Returns the Vector4 hash code.
  3651. */
  3652. Vector4.prototype.getHashCode = function () {
  3653. var hash = this.x || 0;
  3654. hash = (hash * 397) ^ (this.y || 0);
  3655. hash = (hash * 397) ^ (this.z || 0);
  3656. hash = (hash * 397) ^ (this.w || 0);
  3657. return hash;
  3658. };
  3659. // Operators
  3660. /**
  3661. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3662. */
  3663. Vector4.prototype.asArray = function () {
  3664. var result = new Array();
  3665. this.toArray(result, 0);
  3666. return result;
  3667. };
  3668. /**
  3669. * Populates the passed array from the passed index with the Vector4 coordinates.
  3670. * Returns the Vector4.
  3671. */
  3672. Vector4.prototype.toArray = function (array, index) {
  3673. if (index === undefined) {
  3674. index = 0;
  3675. }
  3676. array[index] = this.x;
  3677. array[index + 1] = this.y;
  3678. array[index + 2] = this.z;
  3679. array[index + 3] = this.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Adds the passed vector to the current Vector4.
  3684. * Returns the updated Vector4.
  3685. */
  3686. Vector4.prototype.addInPlace = function (otherVector) {
  3687. this.x += otherVector.x;
  3688. this.y += otherVector.y;
  3689. this.z += otherVector.z;
  3690. this.w += otherVector.w;
  3691. return this;
  3692. };
  3693. /**
  3694. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3695. */
  3696. Vector4.prototype.add = function (otherVector) {
  3697. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3698. };
  3699. /**
  3700. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3701. * Returns the current Vector4.
  3702. */
  3703. Vector4.prototype.addToRef = function (otherVector, result) {
  3704. result.x = this.x + otherVector.x;
  3705. result.y = this.y + otherVector.y;
  3706. result.z = this.z + otherVector.z;
  3707. result.w = this.w + otherVector.w;
  3708. return this;
  3709. };
  3710. /**
  3711. * Subtract in place the passed vector from the current Vector4.
  3712. * Returns the updated Vector4.
  3713. */
  3714. Vector4.prototype.subtractInPlace = function (otherVector) {
  3715. this.x -= otherVector.x;
  3716. this.y -= otherVector.y;
  3717. this.z -= otherVector.z;
  3718. this.w -= otherVector.w;
  3719. return this;
  3720. };
  3721. /**
  3722. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3723. */
  3724. Vector4.prototype.subtract = function (otherVector) {
  3725. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3726. };
  3727. /**
  3728. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3729. * Returns the current Vector4.
  3730. */
  3731. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3732. result.x = this.x - otherVector.x;
  3733. result.y = this.y - otherVector.y;
  3734. result.z = this.z - otherVector.z;
  3735. result.w = this.w - otherVector.w;
  3736. return this;
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3740. */
  3741. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3742. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3743. };
  3744. /**
  3745. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3749. result.x = this.x - x;
  3750. result.y = this.y - y;
  3751. result.z = this.z - z;
  3752. result.w = this.w - w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3757. */
  3758. Vector4.prototype.negate = function () {
  3759. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3760. };
  3761. /**
  3762. * Multiplies the current Vector4 coordinates by scale (float).
  3763. * Returns the updated Vector4.
  3764. */
  3765. Vector4.prototype.scaleInPlace = function (scale) {
  3766. this.x *= scale;
  3767. this.y *= scale;
  3768. this.z *= scale;
  3769. this.w *= scale;
  3770. return this;
  3771. };
  3772. /**
  3773. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3774. */
  3775. Vector4.prototype.scale = function (scale) {
  3776. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3777. };
  3778. /**
  3779. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3780. * Returns the current Vector4.
  3781. */
  3782. Vector4.prototype.scaleToRef = function (scale, result) {
  3783. result.x = this.x * scale;
  3784. result.y = this.y * scale;
  3785. result.z = this.z * scale;
  3786. result.w = this.w * scale;
  3787. return this;
  3788. };
  3789. /**
  3790. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3791. * @param scale defines the scale factor
  3792. * @param result defines the Vector4 object where to store the result
  3793. * @returns the unmodified current Vector4
  3794. */
  3795. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3796. result.x += this.x * scale;
  3797. result.y += this.y * scale;
  3798. result.z += this.z * scale;
  3799. result.w += this.w * scale;
  3800. return this;
  3801. };
  3802. /**
  3803. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3804. */
  3805. Vector4.prototype.equals = function (otherVector) {
  3806. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3807. };
  3808. /**
  3809. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3810. */
  3811. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3812. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3813. return otherVector
  3814. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3815. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3816. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3817. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3818. };
  3819. /**
  3820. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3821. */
  3822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3823. return this.x === x && this.y === y && this.z === z && this.w === w;
  3824. };
  3825. /**
  3826. * Multiplies in place the current Vector4 by the passed one.
  3827. * Returns the updated Vector4.
  3828. */
  3829. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3830. this.x *= otherVector.x;
  3831. this.y *= otherVector.y;
  3832. this.z *= otherVector.z;
  3833. this.w *= otherVector.w;
  3834. return this;
  3835. };
  3836. /**
  3837. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3838. */
  3839. Vector4.prototype.multiply = function (otherVector) {
  3840. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3841. };
  3842. /**
  3843. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3844. * Returns the current Vector4.
  3845. */
  3846. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3847. result.x = this.x * otherVector.x;
  3848. result.y = this.y * otherVector.y;
  3849. result.z = this.z * otherVector.z;
  3850. result.w = this.w * otherVector.w;
  3851. return this;
  3852. };
  3853. /**
  3854. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3857. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3861. */
  3862. Vector4.prototype.divide = function (otherVector) {
  3863. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3864. };
  3865. /**
  3866. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.divideToRef = function (otherVector, result) {
  3870. result.x = this.x / otherVector.x;
  3871. result.y = this.y / otherVector.y;
  3872. result.z = this.z / otherVector.z;
  3873. result.w = this.w / otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Divides the current Vector3 coordinates by the passed ones.
  3878. * @returns the updated Vector3.
  3879. */
  3880. Vector4.prototype.divideInPlace = function (otherVector) {
  3881. return this.divideToRef(otherVector, this);
  3882. };
  3883. /**
  3884. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3885. * @param other defines the second operand
  3886. * @returns the current updated Vector4
  3887. */
  3888. Vector4.prototype.minimizeInPlace = function (other) {
  3889. if (other.x < this.x)
  3890. this.x = other.x;
  3891. if (other.y < this.y)
  3892. this.y = other.y;
  3893. if (other.z < this.z)
  3894. this.z = other.z;
  3895. if (other.w < this.w)
  3896. this.w = other.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3901. * @param other defines the second operand
  3902. * @returns the current updated Vector4
  3903. */
  3904. Vector4.prototype.maximizeInPlace = function (other) {
  3905. if (other.x > this.x)
  3906. this.x = other.x;
  3907. if (other.y > this.y)
  3908. this.y = other.y;
  3909. if (other.z > this.z)
  3910. this.z = other.z;
  3911. if (other.w > this.w)
  3912. this.w = other.w;
  3913. return this;
  3914. };
  3915. // Properties
  3916. /**
  3917. * Returns the Vector4 length (float).
  3918. */
  3919. Vector4.prototype.length = function () {
  3920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3921. };
  3922. /**
  3923. * Returns the Vector4 squared length (float).
  3924. */
  3925. Vector4.prototype.lengthSquared = function () {
  3926. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3927. };
  3928. // Methods
  3929. /**
  3930. * Normalizes in place the Vector4.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.normalize = function () {
  3934. var len = this.length();
  3935. if (len === 0)
  3936. return this;
  3937. var num = 1.0 / len;
  3938. this.x *= num;
  3939. this.y *= num;
  3940. this.z *= num;
  3941. this.w *= num;
  3942. return this;
  3943. };
  3944. /**
  3945. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3946. */
  3947. Vector4.prototype.toVector3 = function () {
  3948. return new Vector3(this.x, this.y, this.z);
  3949. };
  3950. /**
  3951. * Returns a new Vector4 copied from the current one.
  3952. */
  3953. Vector4.prototype.clone = function () {
  3954. return new Vector4(this.x, this.y, this.z, this.w);
  3955. };
  3956. /**
  3957. * Updates the current Vector4 with the passed one coordinates.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.copyFrom = function (source) {
  3961. this.x = source.x;
  3962. this.y = source.y;
  3963. this.z = source.z;
  3964. this.w = source.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Updates the current Vector4 coordinates with the passed floats.
  3969. * Returns the updated Vector4.
  3970. */
  3971. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3972. this.x = x;
  3973. this.y = y;
  3974. this.z = z;
  3975. this.w = w;
  3976. return this;
  3977. };
  3978. /**
  3979. * Updates the current Vector4 coordinates with the passed floats.
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.set = function (x, y, z, w) {
  3983. return this.copyFromFloats(x, y, z, w);
  3984. };
  3985. // Statics
  3986. /**
  3987. * Returns a new Vector4 set from the starting index of the passed array.
  3988. */
  3989. Vector4.FromArray = function (array, offset) {
  3990. if (!offset) {
  3991. offset = 0;
  3992. }
  3993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3994. };
  3995. /**
  3996. * Updates the passed vector "result" from the starting index of the passed array.
  3997. */
  3998. Vector4.FromArrayToRef = function (array, offset, result) {
  3999. result.x = array[offset];
  4000. result.y = array[offset + 1];
  4001. result.z = array[offset + 2];
  4002. result.w = array[offset + 3];
  4003. };
  4004. /**
  4005. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4006. */
  4007. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4008. Vector4.FromArrayToRef(array, offset, result);
  4009. };
  4010. /**
  4011. * Updates the passed vector "result" coordinates from the passed floats.
  4012. */
  4013. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4014. result.x = x;
  4015. result.y = y;
  4016. result.z = z;
  4017. result.w = w;
  4018. };
  4019. /**
  4020. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4021. */
  4022. Vector4.Zero = function () {
  4023. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4024. };
  4025. /**
  4026. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4027. */
  4028. Vector4.One = function () {
  4029. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4030. };
  4031. /**
  4032. * Returns a new normalized Vector4 from the passed one.
  4033. */
  4034. Vector4.Normalize = function (vector) {
  4035. var result = Vector4.Zero();
  4036. Vector4.NormalizeToRef(vector, result);
  4037. return result;
  4038. };
  4039. /**
  4040. * Updates the passed vector "result" from the normalization of the passed one.
  4041. */
  4042. Vector4.NormalizeToRef = function (vector, result) {
  4043. result.copyFrom(vector);
  4044. result.normalize();
  4045. };
  4046. Vector4.Minimize = function (left, right) {
  4047. var min = left.clone();
  4048. min.minimizeInPlace(right);
  4049. return min;
  4050. };
  4051. Vector4.Maximize = function (left, right) {
  4052. var max = left.clone();
  4053. max.maximizeInPlace(right);
  4054. return max;
  4055. };
  4056. /**
  4057. * Returns the distance (float) between the vectors "value1" and "value2".
  4058. */
  4059. Vector4.Distance = function (value1, value2) {
  4060. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4061. };
  4062. /**
  4063. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4064. */
  4065. Vector4.DistanceSquared = function (value1, value2) {
  4066. var x = value1.x - value2.x;
  4067. var y = value1.y - value2.y;
  4068. var z = value1.z - value2.z;
  4069. var w = value1.w - value2.w;
  4070. return (x * x) + (y * y) + (z * z) + (w * w);
  4071. };
  4072. /**
  4073. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4074. */
  4075. Vector4.Center = function (value1, value2) {
  4076. var center = value1.add(value2);
  4077. center.scaleInPlace(0.5);
  4078. return center;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4082. * This methods computes transformed normalized direction vectors only.
  4083. */
  4084. Vector4.TransformNormal = function (vector, transformation) {
  4085. var result = Vector4.Zero();
  4086. Vector4.TransformNormalToRef(vector, transformation, result);
  4087. return result;
  4088. };
  4089. /**
  4090. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4091. * This methods computes transformed normalized direction vectors only.
  4092. */
  4093. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4094. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4095. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4096. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4097. result.x = x;
  4098. result.y = y;
  4099. result.z = z;
  4100. result.w = vector.w;
  4101. };
  4102. /**
  4103. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4104. * This methods computes transformed normalized direction vectors only.
  4105. */
  4106. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4107. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4108. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4109. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4110. result.w = w;
  4111. };
  4112. return Vector4;
  4113. }());
  4114. BABYLON.Vector4 = Vector4;
  4115. var Size = /** @class */ (function () {
  4116. /**
  4117. * Creates a Size object from the passed width and height (floats).
  4118. */
  4119. function Size(width, height) {
  4120. this.width = width;
  4121. this.height = height;
  4122. }
  4123. // Returns a string with the Size width and height.
  4124. Size.prototype.toString = function () {
  4125. return "{W: " + this.width + ", H: " + this.height + "}";
  4126. };
  4127. /**
  4128. * Returns the string "Size"
  4129. */
  4130. Size.prototype.getClassName = function () {
  4131. return "Size";
  4132. };
  4133. /**
  4134. * Returns the Size hash code.
  4135. */
  4136. Size.prototype.getHashCode = function () {
  4137. var hash = this.width || 0;
  4138. hash = (hash * 397) ^ (this.height || 0);
  4139. return hash;
  4140. };
  4141. /**
  4142. * Updates the current size from the passed one.
  4143. * Returns the updated Size.
  4144. */
  4145. Size.prototype.copyFrom = function (src) {
  4146. this.width = src.width;
  4147. this.height = src.height;
  4148. };
  4149. /**
  4150. * Updates in place the current Size from the passed floats.
  4151. * Returns the updated Size.
  4152. */
  4153. Size.prototype.copyFromFloats = function (width, height) {
  4154. this.width = width;
  4155. this.height = height;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates in place the current Size from the passed floats.
  4160. * Returns the updated Size.
  4161. */
  4162. Size.prototype.set = function (width, height) {
  4163. return this.copyFromFloats(width, height);
  4164. };
  4165. /**
  4166. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4167. */
  4168. Size.prototype.multiplyByFloats = function (w, h) {
  4169. return new Size(this.width * w, this.height * h);
  4170. };
  4171. /**
  4172. * Returns a new Size copied from the passed one.
  4173. */
  4174. Size.prototype.clone = function () {
  4175. return new Size(this.width, this.height);
  4176. };
  4177. /**
  4178. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4179. */
  4180. Size.prototype.equals = function (other) {
  4181. if (!other) {
  4182. return false;
  4183. }
  4184. return (this.width === other.width) && (this.height === other.height);
  4185. };
  4186. Object.defineProperty(Size.prototype, "surface", {
  4187. /**
  4188. * Returns the surface of the Size : width * height (float).
  4189. */
  4190. get: function () {
  4191. return this.width * this.height;
  4192. },
  4193. enumerable: true,
  4194. configurable: true
  4195. });
  4196. /**
  4197. * Returns a new Size set to (0.0, 0.0)
  4198. */
  4199. Size.Zero = function () {
  4200. return new Size(0.0, 0.0);
  4201. };
  4202. /**
  4203. * Returns a new Size set as the addition result of the current Size and the passed one.
  4204. */
  4205. Size.prototype.add = function (otherSize) {
  4206. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4207. return r;
  4208. };
  4209. /**
  4210. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4211. */
  4212. Size.prototype.subtract = function (otherSize) {
  4213. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4214. return r;
  4215. };
  4216. /**
  4217. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4218. */
  4219. Size.Lerp = function (start, end, amount) {
  4220. var w = start.width + ((end.width - start.width) * amount);
  4221. var h = start.height + ((end.height - start.height) * amount);
  4222. return new Size(w, h);
  4223. };
  4224. return Size;
  4225. }());
  4226. BABYLON.Size = Size;
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the passed floats.
  4230. */
  4231. function Quaternion(x, y, z, w) {
  4232. if (x === void 0) { x = 0.0; }
  4233. if (y === void 0) { y = 0.0; }
  4234. if (z === void 0) { z = 0.0; }
  4235. if (w === void 0) { w = 1.0; }
  4236. this.x = x;
  4237. this.y = y;
  4238. this.z = z;
  4239. this.w = w;
  4240. }
  4241. /**
  4242. * Returns a string with the Quaternion coordinates.
  4243. */
  4244. Quaternion.prototype.toString = function () {
  4245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4246. };
  4247. /**
  4248. * Returns the string "Quaternion".
  4249. */
  4250. Quaternion.prototype.getClassName = function () {
  4251. return "Quaternion";
  4252. };
  4253. /**
  4254. * Returns the Quaternion hash code.
  4255. */
  4256. Quaternion.prototype.getHashCode = function () {
  4257. var hash = this.x || 0;
  4258. hash = (hash * 397) ^ (this.y || 0);
  4259. hash = (hash * 397) ^ (this.z || 0);
  4260. hash = (hash * 397) ^ (this.w || 0);
  4261. return hash;
  4262. };
  4263. /**
  4264. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4265. */
  4266. Quaternion.prototype.asArray = function () {
  4267. return [this.x, this.y, this.z, this.w];
  4268. };
  4269. /**
  4270. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4271. */
  4272. Quaternion.prototype.equals = function (otherQuaternion) {
  4273. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4274. };
  4275. /**
  4276. * Returns a new Quaternion copied from the current one.
  4277. */
  4278. Quaternion.prototype.clone = function () {
  4279. return new Quaternion(this.x, this.y, this.z, this.w);
  4280. };
  4281. /**
  4282. * Updates the current Quaternion from the passed one coordinates.
  4283. * Returns the updated Quaterion.
  4284. */
  4285. Quaternion.prototype.copyFrom = function (other) {
  4286. this.x = other.x;
  4287. this.y = other.y;
  4288. this.z = other.z;
  4289. this.w = other.w;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates the current Quaternion from the passed float coordinates.
  4294. * Returns the updated Quaterion.
  4295. */
  4296. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4297. this.x = x;
  4298. this.y = y;
  4299. this.z = z;
  4300. this.w = w;
  4301. return this;
  4302. };
  4303. /**
  4304. * Updates the current Quaternion from the passed float coordinates.
  4305. * Returns the updated Quaterion.
  4306. */
  4307. Quaternion.prototype.set = function (x, y, z, w) {
  4308. return this.copyFromFloats(x, y, z, w);
  4309. };
  4310. /**
  4311. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4312. */
  4313. Quaternion.prototype.add = function (other) {
  4314. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4315. };
  4316. /**
  4317. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4318. */
  4319. Quaternion.prototype.subtract = function (other) {
  4320. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4321. };
  4322. /**
  4323. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4324. */
  4325. Quaternion.prototype.scale = function (value) {
  4326. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4327. };
  4328. /**
  4329. * Scale the current Quaternion values by a factor to a given Quaternion
  4330. * @param scale defines the scale factor
  4331. * @param result defines the Quaternion object where to store the result
  4332. * @returns the unmodified current Quaternion
  4333. */
  4334. Quaternion.prototype.scaleToRef = function (scale, result) {
  4335. result.x = this.x * scale;
  4336. result.y = this.y * scale;
  4337. result.z = this.z * scale;
  4338. result.w = this.w * scale;
  4339. return this;
  4340. };
  4341. /**
  4342. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4343. * @param scale defines the scale factor
  4344. * @param result defines the Quaternion object where to store the result
  4345. * @returns the unmodified current Quaternion
  4346. */
  4347. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4348. result.x += this.x * scale;
  4349. result.y += this.y * scale;
  4350. result.z += this.z * scale;
  4351. result.w += this.w * scale;
  4352. return this;
  4353. };
  4354. /**
  4355. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4356. */
  4357. Quaternion.prototype.multiply = function (q1) {
  4358. var result = new Quaternion(0, 0, 0, 1.0);
  4359. this.multiplyToRef(q1, result);
  4360. return result;
  4361. };
  4362. /**
  4363. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4364. * Returns the current Quaternion.
  4365. */
  4366. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4367. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4368. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4369. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4370. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4371. result.copyFromFloats(x, y, z, w);
  4372. return this;
  4373. };
  4374. /**
  4375. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4376. * Returns the updated Quaternion.
  4377. */
  4378. Quaternion.prototype.multiplyInPlace = function (q1) {
  4379. this.multiplyToRef(q1, this);
  4380. return this;
  4381. };
  4382. /**
  4383. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4384. * Returns the current Quaternion.
  4385. */
  4386. Quaternion.prototype.conjugateToRef = function (ref) {
  4387. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4388. return this;
  4389. };
  4390. /**
  4391. * Conjugates in place the current Quaternion.
  4392. * Returns the updated Quaternion.
  4393. */
  4394. Quaternion.prototype.conjugateInPlace = function () {
  4395. this.x *= -1;
  4396. this.y *= -1;
  4397. this.z *= -1;
  4398. return this;
  4399. };
  4400. /**
  4401. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4402. */
  4403. Quaternion.prototype.conjugate = function () {
  4404. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4405. return result;
  4406. };
  4407. /**
  4408. * Returns the Quaternion length (float).
  4409. */
  4410. Quaternion.prototype.length = function () {
  4411. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4412. };
  4413. /**
  4414. * Normalize in place the current Quaternion.
  4415. * Returns the updated Quaternion.
  4416. */
  4417. Quaternion.prototype.normalize = function () {
  4418. var length = 1.0 / this.length();
  4419. this.x *= length;
  4420. this.y *= length;
  4421. this.z *= length;
  4422. this.w *= length;
  4423. return this;
  4424. };
  4425. /**
  4426. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4427. * @param order is a reserved parameter and is ignore for now
  4428. * @returns the new Vector3
  4429. */
  4430. Quaternion.prototype.toEulerAngles = function (order) {
  4431. if (order === void 0) { order = "YZX"; }
  4432. var result = Vector3.Zero();
  4433. this.toEulerAnglesToRef(result, order);
  4434. return result;
  4435. };
  4436. /**
  4437. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4438. * @param result defines the vector which will be filled with the Euler angles
  4439. * @param order is a reserved parameter and is ignore for now
  4440. * @returns the current Quaternion
  4441. */
  4442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4443. if (order === void 0) { order = "YZX"; }
  4444. var qz = this.z;
  4445. var qx = this.x;
  4446. var qy = this.y;
  4447. var qw = this.w;
  4448. var sqw = qw * qw;
  4449. var sqz = qz * qz;
  4450. var sqx = qx * qx;
  4451. var sqy = qy * qy;
  4452. var zAxisY = qy * qz - qx * qw;
  4453. var limit = .4999999;
  4454. if (zAxisY < -limit) {
  4455. result.y = 2 * Math.atan2(qy, qw);
  4456. result.x = Math.PI / 2;
  4457. result.z = 0;
  4458. }
  4459. else if (zAxisY > limit) {
  4460. result.y = 2 * Math.atan2(qy, qw);
  4461. result.x = -Math.PI / 2;
  4462. result.z = 0;
  4463. }
  4464. else {
  4465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4468. }
  4469. return this;
  4470. };
  4471. /**
  4472. * Updates the passed rotation matrix with the current Quaternion values.
  4473. * Returns the current Quaternion.
  4474. */
  4475. Quaternion.prototype.toRotationMatrix = function (result) {
  4476. var xx = this.x * this.x;
  4477. var yy = this.y * this.y;
  4478. var zz = this.z * this.z;
  4479. var xy = this.x * this.y;
  4480. var zw = this.z * this.w;
  4481. var zx = this.z * this.x;
  4482. var yw = this.y * this.w;
  4483. var yz = this.y * this.z;
  4484. var xw = this.x * this.w;
  4485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4486. result.m[1] = 2.0 * (xy + zw);
  4487. result.m[2] = 2.0 * (zx - yw);
  4488. result.m[3] = 0;
  4489. result.m[4] = 2.0 * (xy - zw);
  4490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4491. result.m[6] = 2.0 * (yz + xw);
  4492. result.m[7] = 0;
  4493. result.m[8] = 2.0 * (zx + yw);
  4494. result.m[9] = 2.0 * (yz - xw);
  4495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4496. result.m[11] = 0;
  4497. result.m[12] = 0;
  4498. result.m[13] = 0;
  4499. result.m[14] = 0;
  4500. result.m[15] = 1.0;
  4501. result._markAsUpdated();
  4502. return this;
  4503. };
  4504. /**
  4505. * Updates the current Quaternion from the passed rotation matrix values.
  4506. * Returns the updated Quaternion.
  4507. */
  4508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4509. Quaternion.FromRotationMatrixToRef(matrix, this);
  4510. return this;
  4511. };
  4512. // Statics
  4513. /**
  4514. * Returns a new Quaternion set from the passed rotation matrix values.
  4515. */
  4516. Quaternion.FromRotationMatrix = function (matrix) {
  4517. var result = new Quaternion();
  4518. Quaternion.FromRotationMatrixToRef(matrix, result);
  4519. return result;
  4520. };
  4521. /**
  4522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4523. */
  4524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4525. var data = matrix.m;
  4526. var m11 = data[0], m12 = data[4], m13 = data[8];
  4527. var m21 = data[1], m22 = data[5], m23 = data[9];
  4528. var m31 = data[2], m32 = data[6], m33 = data[10];
  4529. var trace = m11 + m22 + m33;
  4530. var s;
  4531. if (trace > 0) {
  4532. s = 0.5 / Math.sqrt(trace + 1.0);
  4533. result.w = 0.25 / s;
  4534. result.x = (m32 - m23) * s;
  4535. result.y = (m13 - m31) * s;
  4536. result.z = (m21 - m12) * s;
  4537. }
  4538. else if (m11 > m22 && m11 > m33) {
  4539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4540. result.w = (m32 - m23) / s;
  4541. result.x = 0.25 * s;
  4542. result.y = (m12 + m21) / s;
  4543. result.z = (m13 + m31) / s;
  4544. }
  4545. else if (m22 > m33) {
  4546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4547. result.w = (m13 - m31) / s;
  4548. result.x = (m12 + m21) / s;
  4549. result.y = 0.25 * s;
  4550. result.z = (m23 + m32) / s;
  4551. }
  4552. else {
  4553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4554. result.w = (m21 - m12) / s;
  4555. result.x = (m13 + m31) / s;
  4556. result.y = (m23 + m32) / s;
  4557. result.z = 0.25 * s;
  4558. }
  4559. };
  4560. /**
  4561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4562. */
  4563. Quaternion.Zero = function () {
  4564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4565. };
  4566. /**
  4567. * Returns a new Quaternion as the inverted current Quaternion.
  4568. */
  4569. Quaternion.Inverse = function (q) {
  4570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4571. };
  4572. /**
  4573. * Returns the identity Quaternion.
  4574. */
  4575. Quaternion.Identity = function () {
  4576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4577. };
  4578. Quaternion.IsIdentity = function (quaternion) {
  4579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4580. };
  4581. /**
  4582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4583. */
  4584. Quaternion.RotationAxis = function (axis, angle) {
  4585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4586. };
  4587. /**
  4588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4589. */
  4590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4591. var sin = Math.sin(angle / 2);
  4592. axis.normalize();
  4593. result.w = Math.cos(angle / 2);
  4594. result.x = axis.x * sin;
  4595. result.y = axis.y * sin;
  4596. result.z = axis.z * sin;
  4597. return result;
  4598. };
  4599. /**
  4600. * Retuns a new Quaternion set from the starting index of the passed array.
  4601. */
  4602. Quaternion.FromArray = function (array, offset) {
  4603. if (!offset) {
  4604. offset = 0;
  4605. }
  4606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4607. };
  4608. /**
  4609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4610. */
  4611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4612. var q = new Quaternion();
  4613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4614. return q;
  4615. };
  4616. /**
  4617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4618. */
  4619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4621. var halfRoll = roll * 0.5;
  4622. var halfPitch = pitch * 0.5;
  4623. var halfYaw = yaw * 0.5;
  4624. var sinRoll = Math.sin(halfRoll);
  4625. var cosRoll = Math.cos(halfRoll);
  4626. var sinPitch = Math.sin(halfPitch);
  4627. var cosPitch = Math.cos(halfPitch);
  4628. var sinYaw = Math.sin(halfYaw);
  4629. var cosYaw = Math.cos(halfYaw);
  4630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4637. */
  4638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4639. var result = new Quaternion();
  4640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4645. */
  4646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4647. // Produces a quaternion from Euler angles in the z-x-z orientation
  4648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4650. var halfBeta = beta * 0.5;
  4651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4655. };
  4656. /**
  4657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4658. * cf to Vector3.RotationFromAxis() documentation.
  4659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4660. */
  4661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4664. return quat;
  4665. };
  4666. /**
  4667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4668. * cf to Vector3.RotationFromAxis() documentation.
  4669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4670. */
  4671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4672. var rotMat = MathTmp.Matrix[0];
  4673. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4674. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4675. };
  4676. Quaternion.Slerp = function (left, right, amount) {
  4677. var result = Quaternion.Identity();
  4678. Quaternion.SlerpToRef(left, right, amount, result);
  4679. return result;
  4680. };
  4681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4682. var num2;
  4683. var num3;
  4684. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4685. var flag = false;
  4686. if (num4 < 0) {
  4687. flag = true;
  4688. num4 = -num4;
  4689. }
  4690. if (num4 > 0.999999) {
  4691. num3 = 1 - amount;
  4692. num2 = flag ? -amount : amount;
  4693. }
  4694. else {
  4695. var num5 = Math.acos(num4);
  4696. var num6 = (1.0 / Math.sin(num5));
  4697. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4698. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4699. }
  4700. result.x = (num3 * left.x) + (num2 * right.x);
  4701. result.y = (num3 * left.y) + (num2 * right.y);
  4702. result.z = (num3 * left.z) + (num2 * right.z);
  4703. result.w = (num3 * left.w) + (num2 * right.w);
  4704. };
  4705. /**
  4706. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4707. */
  4708. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4709. var squared = amount * amount;
  4710. var cubed = amount * squared;
  4711. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4712. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4713. var part3 = (cubed - (2.0 * squared)) + amount;
  4714. var part4 = cubed - squared;
  4715. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4716. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4717. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4718. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4719. return new Quaternion(x, y, z, w);
  4720. };
  4721. return Quaternion;
  4722. }());
  4723. BABYLON.Quaternion = Quaternion;
  4724. /**
  4725. * Class used to store matrix data (4x4)
  4726. */
  4727. var Matrix = /** @class */ (function () {
  4728. /**
  4729. * Creates an empty matrix (filled with zeros)
  4730. */
  4731. function Matrix() {
  4732. this._isIdentity = false;
  4733. this._isIdentityDirty = true;
  4734. /**
  4735. * Gets or sets the internal data of the matrix
  4736. */
  4737. this.m = new Float32Array(16);
  4738. this._markAsUpdated();
  4739. }
  4740. /** @ignore */
  4741. Matrix.prototype._markAsUpdated = function () {
  4742. this.updateFlag = Matrix._updateFlagSeed++;
  4743. this._isIdentityDirty = true;
  4744. };
  4745. // Properties
  4746. /**
  4747. * Check if the current matrix is indentity
  4748. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4749. * @returns true is the matrix is the identity matrix
  4750. */
  4751. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4752. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4753. if (this._isIdentityDirty) {
  4754. this._isIdentityDirty = false;
  4755. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4756. this._isIdentity = false;
  4757. }
  4758. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4759. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4760. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4761. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4762. this._isIdentity = false;
  4763. }
  4764. else {
  4765. this._isIdentity = true;
  4766. }
  4767. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4768. this._isIdentity = false;
  4769. }
  4770. }
  4771. return this._isIdentity;
  4772. };
  4773. /**
  4774. * Gets the determinant of the matrix
  4775. * @returns the matrix determinant
  4776. */
  4777. Matrix.prototype.determinant = function () {
  4778. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4779. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4780. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4781. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4782. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4783. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4784. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4785. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4786. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4787. };
  4788. // Methods
  4789. /**
  4790. * Returns the matrix as a Float32Array
  4791. * @returns the matrix underlying array
  4792. */
  4793. Matrix.prototype.toArray = function () {
  4794. return this.m;
  4795. };
  4796. /**
  4797. * Returns the matrix as a Float32Array
  4798. * @returns the matrix underlying array.
  4799. */
  4800. Matrix.prototype.asArray = function () {
  4801. return this.toArray();
  4802. };
  4803. /**
  4804. * Inverts the current matrix in place
  4805. * @returns the current inverted matrix
  4806. */
  4807. Matrix.prototype.invert = function () {
  4808. this.invertToRef(this);
  4809. return this;
  4810. };
  4811. /**
  4812. * Sets all the matrix elements to zero
  4813. * @returns the current matrix
  4814. */
  4815. Matrix.prototype.reset = function () {
  4816. for (var index = 0; index < 16; index++) {
  4817. this.m[index] = 0.0;
  4818. }
  4819. this._markAsUpdated();
  4820. return this;
  4821. };
  4822. /**
  4823. * Adds the current matrix with a second one
  4824. * @param other defines the matrix to add
  4825. * @returns a new matrix as the addition of the current matrix and the passed one
  4826. */
  4827. Matrix.prototype.add = function (other) {
  4828. var result = new Matrix();
  4829. this.addToRef(other, result);
  4830. return result;
  4831. };
  4832. /**
  4833. * Sets the passed matrix "result" to the addition of the current matrix and the passed one
  4834. * @param other defines the matrix to add
  4835. * @param result defines the target matrix
  4836. * @returns the current matrix
  4837. */
  4838. Matrix.prototype.addToRef = function (other, result) {
  4839. for (var index = 0; index < 16; index++) {
  4840. result.m[index] = this.m[index] + other.m[index];
  4841. }
  4842. result._markAsUpdated();
  4843. return this;
  4844. };
  4845. /**
  4846. * Adds in place the passed matrix to the current matrix
  4847. * @param other defines the second operand
  4848. * @returns the current updated matrix
  4849. */
  4850. Matrix.prototype.addToSelf = function (other) {
  4851. for (var index = 0; index < 16; index++) {
  4852. this.m[index] += other.m[index];
  4853. }
  4854. this._markAsUpdated();
  4855. return this;
  4856. };
  4857. /**
  4858. * Sets the passed matrix to the current inverted Matrix
  4859. * @param other defines the target matrix
  4860. * @returns the unmodified current matrix
  4861. */
  4862. Matrix.prototype.invertToRef = function (other) {
  4863. var l1 = this.m[0];
  4864. var l2 = this.m[1];
  4865. var l3 = this.m[2];
  4866. var l4 = this.m[3];
  4867. var l5 = this.m[4];
  4868. var l6 = this.m[5];
  4869. var l7 = this.m[6];
  4870. var l8 = this.m[7];
  4871. var l9 = this.m[8];
  4872. var l10 = this.m[9];
  4873. var l11 = this.m[10];
  4874. var l12 = this.m[11];
  4875. var l13 = this.m[12];
  4876. var l14 = this.m[13];
  4877. var l15 = this.m[14];
  4878. var l16 = this.m[15];
  4879. var l17 = (l11 * l16) - (l12 * l15);
  4880. var l18 = (l10 * l16) - (l12 * l14);
  4881. var l19 = (l10 * l15) - (l11 * l14);
  4882. var l20 = (l9 * l16) - (l12 * l13);
  4883. var l21 = (l9 * l15) - (l11 * l13);
  4884. var l22 = (l9 * l14) - (l10 * l13);
  4885. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4886. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4887. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4888. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4889. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4890. var l28 = (l7 * l16) - (l8 * l15);
  4891. var l29 = (l6 * l16) - (l8 * l14);
  4892. var l30 = (l6 * l15) - (l7 * l14);
  4893. var l31 = (l5 * l16) - (l8 * l13);
  4894. var l32 = (l5 * l15) - (l7 * l13);
  4895. var l33 = (l5 * l14) - (l6 * l13);
  4896. var l34 = (l7 * l12) - (l8 * l11);
  4897. var l35 = (l6 * l12) - (l8 * l10);
  4898. var l36 = (l6 * l11) - (l7 * l10);
  4899. var l37 = (l5 * l12) - (l8 * l9);
  4900. var l38 = (l5 * l11) - (l7 * l9);
  4901. var l39 = (l5 * l10) - (l6 * l9);
  4902. other.m[0] = l23 * l27;
  4903. other.m[4] = l24 * l27;
  4904. other.m[8] = l25 * l27;
  4905. other.m[12] = l26 * l27;
  4906. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4907. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4908. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4909. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4910. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4911. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4912. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4913. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4914. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4915. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4916. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4917. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4918. other._markAsUpdated();
  4919. return this;
  4920. };
  4921. /**
  4922. * Inserts the translation vector (using 3 floats) in the current matrix
  4923. * @param x defines the 1st component of the translation
  4924. * @param y defines the 2nd component of the translation
  4925. * @param z defines the 3rd component of the translation
  4926. * @returns the current updated matrix
  4927. */
  4928. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4929. this.m[12] = x;
  4930. this.m[13] = y;
  4931. this.m[14] = z;
  4932. this._markAsUpdated();
  4933. return this;
  4934. };
  4935. /**
  4936. * Inserts the translation vector in the current matrix
  4937. * @param vector3 defines the translation to insert
  4938. * @returns the current updated matrix
  4939. */
  4940. Matrix.prototype.setTranslation = function (vector3) {
  4941. this.m[12] = vector3.x;
  4942. this.m[13] = vector3.y;
  4943. this.m[14] = vector3.z;
  4944. this._markAsUpdated();
  4945. return this;
  4946. };
  4947. /**
  4948. * Gets the translation value of the current matrix
  4949. * @returns a new Vector3 as the extracted translation from the matrix
  4950. */
  4951. Matrix.prototype.getTranslation = function () {
  4952. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4953. };
  4954. /**
  4955. * Fill a Vector3 with the extracted translation from the matrix
  4956. * @param result defines the Vector3 where to store the translation
  4957. * @returns the current matrix
  4958. */
  4959. Matrix.prototype.getTranslationToRef = function (result) {
  4960. result.x = this.m[12];
  4961. result.y = this.m[13];
  4962. result.z = this.m[14];
  4963. return this;
  4964. };
  4965. /**
  4966. * Remove rotation and scaling part from the matrix
  4967. * @returns the updated matrix
  4968. */
  4969. Matrix.prototype.removeRotationAndScaling = function () {
  4970. this.setRowFromFloats(0, 1, 0, 0, 0);
  4971. this.setRowFromFloats(1, 0, 1, 0, 0);
  4972. this.setRowFromFloats(2, 0, 0, 1, 0);
  4973. return this;
  4974. };
  4975. /**
  4976. * Multiply two matrices
  4977. * @param other defines the second operand
  4978. * @returns a new matrix set with the multiplication result of the current Matrix and the passed one
  4979. */
  4980. Matrix.prototype.multiply = function (other) {
  4981. var result = new Matrix();
  4982. this.multiplyToRef(other, result);
  4983. return result;
  4984. };
  4985. /**
  4986. * Copy the current matrix from the passed one
  4987. * @param other defines the source matrix
  4988. * @returns the current updated matrix
  4989. */
  4990. Matrix.prototype.copyFrom = function (other) {
  4991. for (var index = 0; index < 16; index++) {
  4992. this.m[index] = other.m[index];
  4993. }
  4994. this._markAsUpdated();
  4995. return this;
  4996. };
  4997. /**
  4998. * Populates the passed array from the starting index with the current matrix values
  4999. * @param array defines the target array
  5000. * @param offset defines the offset in the target array where to start storing values
  5001. * @returns the current matrix
  5002. */
  5003. Matrix.prototype.copyToArray = function (array, offset) {
  5004. if (offset === void 0) { offset = 0; }
  5005. for (var index = 0; index < 16; index++) {
  5006. array[offset + index] = this.m[index];
  5007. }
  5008. return this;
  5009. };
  5010. /**
  5011. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one
  5012. * @param other defines the second operand
  5013. * @param result defines the matrix where to store the multiplication
  5014. * @returns the current matrix
  5015. */
  5016. Matrix.prototype.multiplyToRef = function (other, result) {
  5017. this.multiplyToArray(other, result.m, 0);
  5018. result._markAsUpdated();
  5019. return this;
  5020. };
  5021. /**
  5022. * Sets the Float32Array "result" from the passed index "offset" with the multiplication of the current matrix and the passed one
  5023. * @param other defines the second operand
  5024. * @param result defines the array where to store the multiplication
  5025. * @param offset defines the offset in the target array where to start storing values
  5026. * @returns the current matrix
  5027. */
  5028. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5029. var tm0 = this.m[0];
  5030. var tm1 = this.m[1];
  5031. var tm2 = this.m[2];
  5032. var tm3 = this.m[3];
  5033. var tm4 = this.m[4];
  5034. var tm5 = this.m[5];
  5035. var tm6 = this.m[6];
  5036. var tm7 = this.m[7];
  5037. var tm8 = this.m[8];
  5038. var tm9 = this.m[9];
  5039. var tm10 = this.m[10];
  5040. var tm11 = this.m[11];
  5041. var tm12 = this.m[12];
  5042. var tm13 = this.m[13];
  5043. var tm14 = this.m[14];
  5044. var tm15 = this.m[15];
  5045. var om0 = other.m[0];
  5046. var om1 = other.m[1];
  5047. var om2 = other.m[2];
  5048. var om3 = other.m[3];
  5049. var om4 = other.m[4];
  5050. var om5 = other.m[5];
  5051. var om6 = other.m[6];
  5052. var om7 = other.m[7];
  5053. var om8 = other.m[8];
  5054. var om9 = other.m[9];
  5055. var om10 = other.m[10];
  5056. var om11 = other.m[11];
  5057. var om12 = other.m[12];
  5058. var om13 = other.m[13];
  5059. var om14 = other.m[14];
  5060. var om15 = other.m[15];
  5061. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5062. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5063. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5064. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5065. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5066. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5067. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5068. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5069. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5070. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5071. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5072. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5073. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5074. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5075. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5076. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5077. return this;
  5078. };
  5079. /**
  5080. * Check equality between this matrix and a second one
  5081. * @param value defines the second matrix to compare
  5082. * @returns true is the current matrix and the passed one values are strictly equal
  5083. */
  5084. Matrix.prototype.equals = function (value) {
  5085. return value &&
  5086. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5087. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5088. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5089. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5090. };
  5091. /**
  5092. * Clone the current matrix
  5093. * @returns a new matrix from the current matrix
  5094. */
  5095. Matrix.prototype.clone = function () {
  5096. 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]);
  5097. };
  5098. /**
  5099. * Returns the name of the current matrix class
  5100. * @returns the string "Matrix"
  5101. */
  5102. Matrix.prototype.getClassName = function () {
  5103. return "Matrix";
  5104. };
  5105. /**
  5106. * Gets the hash code of the current matrix
  5107. * @returns the hash code
  5108. */
  5109. Matrix.prototype.getHashCode = function () {
  5110. var hash = this.m[0] || 0;
  5111. for (var i = 1; i < 16; i++) {
  5112. hash = (hash * 397) ^ (this.m[i] || 0);
  5113. }
  5114. return hash;
  5115. };
  5116. /**
  5117. * Decomposes the current Matrix into a translation, rotation and scaling components
  5118. * @param scale defines the scale vector3 passed as a reference to update
  5119. * @param rotation defines the rotation quaternion passed as a reference to update
  5120. * @param translation defines the translation vector3 passed as a reference to update
  5121. * @returns true if operation was successful
  5122. */
  5123. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5124. if (translation) {
  5125. translation.x = this.m[12];
  5126. translation.y = this.m[13];
  5127. translation.z = this.m[14];
  5128. }
  5129. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5130. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5131. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5132. if (this.determinant() <= 0) {
  5133. scale.y *= -1;
  5134. }
  5135. if (rotation) {
  5136. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5137. rotation.x = 0;
  5138. rotation.y = 0;
  5139. rotation.z = 0;
  5140. rotation.w = 1;
  5141. return false;
  5142. }
  5143. 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]);
  5144. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5145. }
  5146. return true;
  5147. };
  5148. /**
  5149. * Gets specific row of the matrix
  5150. * @param index defines the number of the row to get
  5151. * @returns the index-th row of the current matrix as a new Vector4
  5152. */
  5153. Matrix.prototype.getRow = function (index) {
  5154. if (index < 0 || index > 3) {
  5155. return null;
  5156. }
  5157. var i = index * 4;
  5158. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5159. };
  5160. /**
  5161. * Sets the index-th row of the current matrix to the vector4 values
  5162. * @param index defines the number of the row to set
  5163. * @param row defines the target vector4
  5164. * @returns the updated current matrix
  5165. */
  5166. Matrix.prototype.setRow = function (index, row) {
  5167. if (index < 0 || index > 3) {
  5168. return this;
  5169. }
  5170. var i = index * 4;
  5171. this.m[i + 0] = row.x;
  5172. this.m[i + 1] = row.y;
  5173. this.m[i + 2] = row.z;
  5174. this.m[i + 3] = row.w;
  5175. this._markAsUpdated();
  5176. return this;
  5177. };
  5178. /**
  5179. * Compute the transpose of the matrix
  5180. * @returns the new transposed matrix
  5181. */
  5182. Matrix.prototype.transpose = function () {
  5183. return Matrix.Transpose(this);
  5184. };
  5185. /**
  5186. * Compute the transpose of the matrix and store it in a given matrix
  5187. * @param result defines the target matrix
  5188. * @returns the current matrix
  5189. */
  5190. Matrix.prototype.transposeToRef = function (result) {
  5191. Matrix.TransposeToRef(this, result);
  5192. return this;
  5193. };
  5194. /**
  5195. * Sets the index-th row of the current matrix with the passed 4 x float values
  5196. * @param index defines the row index
  5197. * @param x defines the x component to set
  5198. * @param y defines the y component to set
  5199. * @param z defines the z component to set
  5200. * @param w defines the w component to set
  5201. * @returns the updated current matrix
  5202. */
  5203. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5204. if (index < 0 || index > 3) {
  5205. return this;
  5206. }
  5207. var i = index * 4;
  5208. this.m[i + 0] = x;
  5209. this.m[i + 1] = y;
  5210. this.m[i + 2] = z;
  5211. this.m[i + 3] = w;
  5212. this._markAsUpdated();
  5213. return this;
  5214. };
  5215. /**
  5216. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5217. * @param scale defines the scale factor
  5218. * @returns a new matrix
  5219. */
  5220. Matrix.prototype.scale = function (scale) {
  5221. var result = new Matrix();
  5222. this.scaleToRef(scale, result);
  5223. return result;
  5224. };
  5225. /**
  5226. * Scale the current matrix values by a factor to a given result matrix
  5227. * @param scale defines the scale factor
  5228. * @param result defines the matrix to store the result
  5229. * @returns the current matrix
  5230. */
  5231. Matrix.prototype.scaleToRef = function (scale, result) {
  5232. for (var index = 0; index < 16; index++) {
  5233. result.m[index] = this.m[index] * scale;
  5234. }
  5235. result._markAsUpdated();
  5236. return this;
  5237. };
  5238. /**
  5239. * Scale the current matrix values by a factor and add the result to a given matrix
  5240. * @param scale defines the scale factor
  5241. * @param result defines the Matrix to store the result
  5242. * @returns the current matrix
  5243. */
  5244. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5245. for (var index = 0; index < 16; index++) {
  5246. result.m[index] += this.m[index] * scale;
  5247. }
  5248. result._markAsUpdated();
  5249. return this;
  5250. };
  5251. /**
  5252. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5253. * @param ref matrix to store the result
  5254. */
  5255. Matrix.prototype.toNormalMatrix = function (ref) {
  5256. this.invertToRef(ref);
  5257. ref.transpose();
  5258. var m = ref.m;
  5259. 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);
  5260. };
  5261. /**
  5262. * Gets only rotation part of the current matrix
  5263. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5264. */
  5265. Matrix.prototype.getRotationMatrix = function () {
  5266. var result = Matrix.Identity();
  5267. this.getRotationMatrixToRef(result);
  5268. return result;
  5269. };
  5270. /**
  5271. * Extracts the rotation matrix from the current one and sets it as the passed "result"
  5272. * @param result defines the target matrix to store data to
  5273. * @returns the current matrix
  5274. */
  5275. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5276. var m = this.m;
  5277. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5278. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5279. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5280. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5281. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5282. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5283. 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);
  5284. return this;
  5285. };
  5286. // Statics
  5287. /**
  5288. * Creates a matrix from an array
  5289. * @param array defines the source array
  5290. * @param offset defines an offset in the source array
  5291. * @returns a new Matrix set from the starting index of the passed array
  5292. */
  5293. Matrix.FromArray = function (array, offset) {
  5294. var result = new Matrix();
  5295. if (!offset) {
  5296. offset = 0;
  5297. }
  5298. Matrix.FromArrayToRef(array, offset, result);
  5299. return result;
  5300. };
  5301. /**
  5302. * Copy the content of an array into a given matrix
  5303. * @param array defines the source array
  5304. * @param offset defines an offset in the source array
  5305. * @param result defines the target matrix
  5306. */
  5307. Matrix.FromArrayToRef = function (array, offset, result) {
  5308. for (var index = 0; index < 16; index++) {
  5309. result.m[index] = array[index + offset];
  5310. }
  5311. result._markAsUpdated();
  5312. };
  5313. /**
  5314. * Stores an array into a matrix after having multiplied each component by a given factor
  5315. * @param array defines the source array
  5316. * @param offset defines the offset in the source array
  5317. * @param scale defines the scaling factor
  5318. * @param result defines the target matrix
  5319. */
  5320. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5321. for (var index = 0; index < 16; index++) {
  5322. result.m[index] = array[index + offset] * scale;
  5323. }
  5324. result._markAsUpdated();
  5325. };
  5326. /**
  5327. * Stores a list of values (16) inside a given matrix
  5328. * @param initialM11 defines 1st value of 1st row
  5329. * @param initialM12 defines 2nd value of 1st row
  5330. * @param initialM13 defines 3rd value of 1st row
  5331. * @param initialM14 defines 4th value of 1st row
  5332. * @param initialM21 defines 1st value of 2nd row
  5333. * @param initialM22 defines 2nd value of 2nd row
  5334. * @param initialM23 defines 3rd value of 2nd row
  5335. * @param initialM24 defines 4th value of 2nd row
  5336. * @param initialM31 defines 1st value of 3rd row
  5337. * @param initialM32 defines 2nd value of 3rd row
  5338. * @param initialM33 defines 3rd value of 3rd row
  5339. * @param initialM34 defines 4th value of 3rd row
  5340. * @param initialM41 defines 1st value of 4th row
  5341. * @param initialM42 defines 2nd value of 4th row
  5342. * @param initialM43 defines 3rd value of 4th row
  5343. * @param initialM44 defines 4th value of 4th row
  5344. * @param result defines the target matrix
  5345. */
  5346. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5347. result.m[0] = initialM11;
  5348. result.m[1] = initialM12;
  5349. result.m[2] = initialM13;
  5350. result.m[3] = initialM14;
  5351. result.m[4] = initialM21;
  5352. result.m[5] = initialM22;
  5353. result.m[6] = initialM23;
  5354. result.m[7] = initialM24;
  5355. result.m[8] = initialM31;
  5356. result.m[9] = initialM32;
  5357. result.m[10] = initialM33;
  5358. result.m[11] = initialM34;
  5359. result.m[12] = initialM41;
  5360. result.m[13] = initialM42;
  5361. result.m[14] = initialM43;
  5362. result.m[15] = initialM44;
  5363. result._markAsUpdated();
  5364. };
  5365. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5366. /**
  5367. * Gets an identity matrix that must not be updated
  5368. */
  5369. get: function () {
  5370. return Matrix._identityReadOnly;
  5371. },
  5372. enumerable: true,
  5373. configurable: true
  5374. });
  5375. /**
  5376. * Creates new matrix from a list of values (16)
  5377. * @param initialM11 defines 1st value of 1st row
  5378. * @param initialM12 defines 2nd value of 1st row
  5379. * @param initialM13 defines 3rd value of 1st row
  5380. * @param initialM14 defines 4th value of 1st row
  5381. * @param initialM21 defines 1st value of 2nd row
  5382. * @param initialM22 defines 2nd value of 2nd row
  5383. * @param initialM23 defines 3rd value of 2nd row
  5384. * @param initialM24 defines 4th value of 2nd row
  5385. * @param initialM31 defines 1st value of 3rd row
  5386. * @param initialM32 defines 2nd value of 3rd row
  5387. * @param initialM33 defines 3rd value of 3rd row
  5388. * @param initialM34 defines 4th value of 3rd row
  5389. * @param initialM41 defines 1st value of 4th row
  5390. * @param initialM42 defines 2nd value of 4th row
  5391. * @param initialM43 defines 3rd value of 4th row
  5392. * @param initialM44 defines 4th value of 4th row
  5393. * @returns the new matrix
  5394. */
  5395. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5396. var result = new Matrix();
  5397. result.m[0] = initialM11;
  5398. result.m[1] = initialM12;
  5399. result.m[2] = initialM13;
  5400. result.m[3] = initialM14;
  5401. result.m[4] = initialM21;
  5402. result.m[5] = initialM22;
  5403. result.m[6] = initialM23;
  5404. result.m[7] = initialM24;
  5405. result.m[8] = initialM31;
  5406. result.m[9] = initialM32;
  5407. result.m[10] = initialM33;
  5408. result.m[11] = initialM34;
  5409. result.m[12] = initialM41;
  5410. result.m[13] = initialM42;
  5411. result.m[14] = initialM43;
  5412. result.m[15] = initialM44;
  5413. return result;
  5414. };
  5415. /**
  5416. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5417. * @param scale defines the scale vector3
  5418. * @param rotation defines the rotation quaternion
  5419. * @param translation defines the translation vector3
  5420. * @returns a new matrix
  5421. */
  5422. Matrix.Compose = function (scale, rotation, translation) {
  5423. var result = Matrix.Identity();
  5424. Matrix.ComposeToRef(scale, rotation, translation, result);
  5425. return result;
  5426. };
  5427. /**
  5428. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5429. * @param scale defines the scale vector3
  5430. * @param rotation defines the rotation quaternion
  5431. * @param translation defines the translation vector3
  5432. * @param result defines the target matrix
  5433. */
  5434. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5435. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5436. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5437. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5438. result.setTranslation(translation);
  5439. };
  5440. /**
  5441. * Creates a new identity matrix
  5442. * @returns a new identity matrix
  5443. */
  5444. Matrix.Identity = function () {
  5445. 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);
  5446. };
  5447. /**
  5448. * Creates a new identity matrix and stores the result in a given matrix
  5449. * @param result defines the target matrix
  5450. */
  5451. Matrix.IdentityToRef = function (result) {
  5452. 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);
  5453. };
  5454. /**
  5455. * Creates a new zero matrix
  5456. * @returns a new zero matrix
  5457. */
  5458. Matrix.Zero = function () {
  5459. 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);
  5460. };
  5461. /**
  5462. * Creates a new rotation matrix for "angle" radians around the X axis
  5463. * @param angle defines the angle (in radians) to use
  5464. * @return the new matrix
  5465. */
  5466. Matrix.RotationX = function (angle) {
  5467. var result = new Matrix();
  5468. Matrix.RotationXToRef(angle, result);
  5469. return result;
  5470. };
  5471. /**
  5472. * Creates a new matrix as the invert of a given matrix
  5473. * @param source defines the source matrix
  5474. * @returns the new matrix
  5475. */
  5476. Matrix.Invert = function (source) {
  5477. var result = new Matrix();
  5478. source.invertToRef(result);
  5479. return result;
  5480. };
  5481. /**
  5482. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5483. * @param angle defines the angle (in radians) to use
  5484. * @param result defines the target matrix
  5485. */
  5486. Matrix.RotationXToRef = function (angle, result) {
  5487. var s = Math.sin(angle);
  5488. var c = Math.cos(angle);
  5489. result.m[0] = 1.0;
  5490. result.m[15] = 1.0;
  5491. result.m[5] = c;
  5492. result.m[10] = c;
  5493. result.m[9] = -s;
  5494. result.m[6] = s;
  5495. result.m[1] = 0.0;
  5496. result.m[2] = 0.0;
  5497. result.m[3] = 0.0;
  5498. result.m[4] = 0.0;
  5499. result.m[7] = 0.0;
  5500. result.m[8] = 0.0;
  5501. result.m[11] = 0.0;
  5502. result.m[12] = 0.0;
  5503. result.m[13] = 0.0;
  5504. result.m[14] = 0.0;
  5505. result._markAsUpdated();
  5506. };
  5507. /**
  5508. * Creates a new rotation matrix for "angle" radians around the Y axis
  5509. * @param angle defines the angle (in radians) to use
  5510. * @return the new matrix
  5511. */
  5512. Matrix.RotationY = function (angle) {
  5513. var result = new Matrix();
  5514. Matrix.RotationYToRef(angle, result);
  5515. return result;
  5516. };
  5517. /**
  5518. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5519. * @param angle defines the angle (in radians) to use
  5520. * @param result defines the target matrix
  5521. */
  5522. Matrix.RotationYToRef = function (angle, result) {
  5523. var s = Math.sin(angle);
  5524. var c = Math.cos(angle);
  5525. result.m[5] = 1.0;
  5526. result.m[15] = 1.0;
  5527. result.m[0] = c;
  5528. result.m[2] = -s;
  5529. result.m[8] = s;
  5530. result.m[10] = c;
  5531. result.m[1] = 0.0;
  5532. result.m[3] = 0.0;
  5533. result.m[4] = 0.0;
  5534. result.m[6] = 0.0;
  5535. result.m[7] = 0.0;
  5536. result.m[9] = 0.0;
  5537. result.m[11] = 0.0;
  5538. result.m[12] = 0.0;
  5539. result.m[13] = 0.0;
  5540. result.m[14] = 0.0;
  5541. result._markAsUpdated();
  5542. };
  5543. /**
  5544. * Creates a new rotation matrix for "angle" radians around the Z axis
  5545. * @param angle defines the angle (in radians) to use
  5546. * @return the new matrix
  5547. */
  5548. Matrix.RotationZ = function (angle) {
  5549. var result = new Matrix();
  5550. Matrix.RotationZToRef(angle, result);
  5551. return result;
  5552. };
  5553. /**
  5554. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5555. * @param angle defines the angle (in radians) to use
  5556. * @param result defines the target matrix
  5557. */
  5558. Matrix.RotationZToRef = function (angle, result) {
  5559. var s = Math.sin(angle);
  5560. var c = Math.cos(angle);
  5561. result.m[10] = 1.0;
  5562. result.m[15] = 1.0;
  5563. result.m[0] = c;
  5564. result.m[1] = s;
  5565. result.m[4] = -s;
  5566. result.m[5] = c;
  5567. result.m[2] = 0.0;
  5568. result.m[3] = 0.0;
  5569. result.m[6] = 0.0;
  5570. result.m[7] = 0.0;
  5571. result.m[8] = 0.0;
  5572. result.m[9] = 0.0;
  5573. result.m[11] = 0.0;
  5574. result.m[12] = 0.0;
  5575. result.m[13] = 0.0;
  5576. result.m[14] = 0.0;
  5577. result._markAsUpdated();
  5578. };
  5579. /**
  5580. * Creates a new rotation matrix for "angle" radians around the given axis
  5581. * @param axis defines the axis to use
  5582. * @param angle defines the angle (in radians) to use
  5583. * @return the new matrix
  5584. */
  5585. Matrix.RotationAxis = function (axis, angle) {
  5586. var result = Matrix.Zero();
  5587. Matrix.RotationAxisToRef(axis, angle, result);
  5588. return result;
  5589. };
  5590. /**
  5591. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5592. * @param axis defines the axis to use
  5593. * @param angle defines the angle (in radians) to use
  5594. * @param result defines the target matrix
  5595. */
  5596. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5597. var s = Math.sin(-angle);
  5598. var c = Math.cos(-angle);
  5599. var c1 = 1 - c;
  5600. axis.normalize();
  5601. result.m[0] = (axis.x * axis.x) * c1 + c;
  5602. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5603. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5604. result.m[3] = 0.0;
  5605. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5606. result.m[5] = (axis.y * axis.y) * c1 + c;
  5607. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5608. result.m[7] = 0.0;
  5609. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5610. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5611. result.m[10] = (axis.z * axis.z) * c1 + c;
  5612. result.m[11] = 0.0;
  5613. result.m[15] = 1.0;
  5614. result._markAsUpdated();
  5615. };
  5616. /**
  5617. * Creates a rotation matrix
  5618. * @param yaw defines the yaw angle in radians (Y axis)
  5619. * @param pitch defines the pitch angle in radians (X axis)
  5620. * @param roll defines the roll angle in radians (X axis)
  5621. * @returns the new rotation matrix
  5622. */
  5623. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5624. var result = new Matrix();
  5625. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5626. return result;
  5627. };
  5628. /**
  5629. * Creates a rotation matrix and stores it in a given matrix
  5630. * @param yaw defines the yaw angle in radians (Y axis)
  5631. * @param pitch defines the pitch angle in radians (X axis)
  5632. * @param roll defines the roll angle in radians (X axis)
  5633. * @param result defines the target matrix
  5634. */
  5635. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5636. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5637. this._tempQuaternion.toRotationMatrix(result);
  5638. };
  5639. /**
  5640. * Creates a scaling matrix
  5641. * @param x defines the scale factor on X axis
  5642. * @param y defines the scale factor on Y axis
  5643. * @param z defines the scale factor on Z axis
  5644. * @returns the new matrix
  5645. */
  5646. Matrix.Scaling = function (x, y, z) {
  5647. var result = Matrix.Zero();
  5648. Matrix.ScalingToRef(x, y, z, result);
  5649. return result;
  5650. };
  5651. /**
  5652. * Creates a scaling matrix and stores it in a given matrix
  5653. * @param x defines the scale factor on X axis
  5654. * @param y defines the scale factor on Y axis
  5655. * @param z defines the scale factor on Z axis
  5656. * @param result defines the target matrix
  5657. */
  5658. Matrix.ScalingToRef = function (x, y, z, result) {
  5659. result.m[0] = x;
  5660. result.m[1] = 0.0;
  5661. result.m[2] = 0.0;
  5662. result.m[3] = 0.0;
  5663. result.m[4] = 0.0;
  5664. result.m[5] = y;
  5665. result.m[6] = 0.0;
  5666. result.m[7] = 0.0;
  5667. result.m[8] = 0.0;
  5668. result.m[9] = 0.0;
  5669. result.m[10] = z;
  5670. result.m[11] = 0.0;
  5671. result.m[12] = 0.0;
  5672. result.m[13] = 0.0;
  5673. result.m[14] = 0.0;
  5674. result.m[15] = 1.0;
  5675. result._markAsUpdated();
  5676. };
  5677. /**
  5678. * Creates a translation matrix
  5679. * @param x defines the translation on X axis
  5680. * @param y defines the translation on Y axis
  5681. * @param z defines the translationon Z axis
  5682. * @returns the new matrix
  5683. */
  5684. Matrix.Translation = function (x, y, z) {
  5685. var result = Matrix.Identity();
  5686. Matrix.TranslationToRef(x, y, z, result);
  5687. return result;
  5688. };
  5689. /**
  5690. * Creates a translation matrix and stores it in a given matrix
  5691. * @param x defines the translation on X axis
  5692. * @param y defines the translation on Y axis
  5693. * @param z defines the translationon Z axis
  5694. * @param result defines the target matrix
  5695. */
  5696. Matrix.TranslationToRef = function (x, y, z, result) {
  5697. 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);
  5698. };
  5699. /**
  5700. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5701. * @param startValue defines the start value
  5702. * @param endValue defines the end value
  5703. * @param gradient defines the gradient factor
  5704. * @returns the new matrix
  5705. */
  5706. Matrix.Lerp = function (startValue, endValue, gradient) {
  5707. var result = Matrix.Zero();
  5708. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5709. return result;
  5710. };
  5711. /**
  5712. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5713. * @param startValue defines the start value
  5714. * @param endValue defines the end value
  5715. * @param gradient defines the gradient factor
  5716. * @param result defines the Matrix object where to store data
  5717. */
  5718. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5719. for (var index = 0; index < 16; index++) {
  5720. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5721. }
  5722. result._markAsUpdated();
  5723. };
  5724. /**
  5725. * Builds a new matrix whose values are computed by:
  5726. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5727. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5728. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5729. * @param startValue defines the first matrix
  5730. * @param endValue defines the second matrix
  5731. * @param gradient defines the gradient between the two matrices
  5732. * @returns the new matrix
  5733. */
  5734. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5735. var result = Matrix.Zero();
  5736. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5737. return result;
  5738. };
  5739. /**
  5740. * Update a matrix to values which are computed by:
  5741. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5742. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5743. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5744. * @param startValue defines the first matrix
  5745. * @param endValue defines the second matrix
  5746. * @param gradient defines the gradient between the two matrices
  5747. * @param result defines the target matrix
  5748. */
  5749. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5750. var startScale = MathTmp.Vector3[0];
  5751. var startRotation = MathTmp.Quaternion[0];
  5752. var startTranslation = MathTmp.Vector3[1];
  5753. startValue.decompose(startScale, startRotation, startTranslation);
  5754. var endScale = MathTmp.Vector3[2];
  5755. var endRotation = MathTmp.Quaternion[1];
  5756. var endTranslation = MathTmp.Vector3[3];
  5757. endValue.decompose(endScale, endRotation, endTranslation);
  5758. var resultScale = MathTmp.Vector3[4];
  5759. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  5760. var resultRotation = MathTmp.Quaternion[2];
  5761. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  5762. var resultTranslation = MathTmp.Vector3[5];
  5763. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  5764. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  5765. };
  5766. /**
  5767. * 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"
  5768. * This function works in left handed mode
  5769. * @param eye defines the final position of the entity
  5770. * @param target defines where the entity should look at
  5771. * @param up defines the up vector for the entity
  5772. * @returns the new matrix
  5773. */
  5774. Matrix.LookAtLH = function (eye, target, up) {
  5775. var result = Matrix.Zero();
  5776. Matrix.LookAtLHToRef(eye, target, up, result);
  5777. return result;
  5778. };
  5779. /**
  5780. * 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".
  5781. * This function works in left handed mode
  5782. * @param eye defines the final position of the entity
  5783. * @param target defines where the entity should look at
  5784. * @param up defines the up vector for the entity
  5785. * @param result defines the target matrix
  5786. */
  5787. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5788. // Z axis
  5789. target.subtractToRef(eye, this._zAxis);
  5790. this._zAxis.normalize();
  5791. // X axis
  5792. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5793. if (this._xAxis.lengthSquared() === 0) {
  5794. this._xAxis.x = 1.0;
  5795. }
  5796. else {
  5797. this._xAxis.normalize();
  5798. }
  5799. // Y axis
  5800. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5801. this._yAxis.normalize();
  5802. // Eye angles
  5803. var ex = -Vector3.Dot(this._xAxis, eye);
  5804. var ey = -Vector3.Dot(this._yAxis, eye);
  5805. var ez = -Vector3.Dot(this._zAxis, eye);
  5806. 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);
  5807. };
  5808. /**
  5809. * 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"
  5810. * This function works in right handed mode
  5811. * @param eye defines the final position of the entity
  5812. * @param target defines where the entity should look at
  5813. * @param up defines the up vector for the entity
  5814. * @returns the new matrix
  5815. */
  5816. Matrix.LookAtRH = function (eye, target, up) {
  5817. var result = Matrix.Zero();
  5818. Matrix.LookAtRHToRef(eye, target, up, result);
  5819. return result;
  5820. };
  5821. /**
  5822. * 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".
  5823. * This function works in right handed mode
  5824. * @param eye defines the final position of the entity
  5825. * @param target defines where the entity should look at
  5826. * @param up defines the up vector for the entity
  5827. * @param result defines the target matrix
  5828. */
  5829. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5830. // Z axis
  5831. eye.subtractToRef(target, this._zAxis);
  5832. this._zAxis.normalize();
  5833. // X axis
  5834. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5835. if (this._xAxis.lengthSquared() === 0) {
  5836. this._xAxis.x = 1.0;
  5837. }
  5838. else {
  5839. this._xAxis.normalize();
  5840. }
  5841. // Y axis
  5842. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5843. this._yAxis.normalize();
  5844. // Eye angles
  5845. var ex = -Vector3.Dot(this._xAxis, eye);
  5846. var ey = -Vector3.Dot(this._yAxis, eye);
  5847. var ez = -Vector3.Dot(this._zAxis, eye);
  5848. 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);
  5849. };
  5850. /**
  5851. * Create a left-handed orthographic projection matrix
  5852. * @param width defines the viewport width
  5853. * @param height defines the viewport height
  5854. * @param znear defines the near clip plane
  5855. * @param zfar defines the far clip plane
  5856. * @returns a new matrix as a left-handed orthographic projection matrix
  5857. */
  5858. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5859. var matrix = Matrix.Zero();
  5860. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5861. return matrix;
  5862. };
  5863. /**
  5864. * Store a left-handed orthographic projection to a given matrix
  5865. * @param width defines the viewport width
  5866. * @param height defines the viewport height
  5867. * @param znear defines the near clip plane
  5868. * @param zfar defines the far clip plane
  5869. * @param result defines the target matrix
  5870. */
  5871. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5872. var n = znear;
  5873. var f = zfar;
  5874. var a = 2.0 / width;
  5875. var b = 2.0 / height;
  5876. var c = 2.0 / (f - n);
  5877. var d = -(f + n) / (f - n);
  5878. 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);
  5879. };
  5880. /**
  5881. * Create a left-handed orthographic projection matrix
  5882. * @param left defines the viewport left coordinate
  5883. * @param right defines the viewport right coordinate
  5884. * @param bottom defines the viewport bottom coordinate
  5885. * @param top defines the viewport top coordinate
  5886. * @param znear defines the near clip plane
  5887. * @param zfar defines the far clip plane
  5888. * @returns a new matrix as a left-handed orthographic projection matrix
  5889. */
  5890. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5891. var matrix = Matrix.Zero();
  5892. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5893. return matrix;
  5894. };
  5895. /**
  5896. * Stores a left-handed orthographic projection into a given matrix
  5897. * @param left defines the viewport left coordinate
  5898. * @param right defines the viewport right coordinate
  5899. * @param bottom defines the viewport bottom coordinate
  5900. * @param top defines the viewport top coordinate
  5901. * @param znear defines the near clip plane
  5902. * @param zfar defines the far clip plane
  5903. * @param result defines the target matrix
  5904. */
  5905. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5906. var n = znear;
  5907. var f = zfar;
  5908. var a = 2.0 / (right - left);
  5909. var b = 2.0 / (top - bottom);
  5910. var c = 2.0 / (f - n);
  5911. var d = -(f + n) / (f - n);
  5912. var i0 = (left + right) / (left - right);
  5913. var i1 = (top + bottom) / (bottom - top);
  5914. 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);
  5915. };
  5916. /**
  5917. * Creates a right-handed orthographic projection matrix
  5918. * @param left defines the viewport left coordinate
  5919. * @param right defines the viewport right coordinate
  5920. * @param bottom defines the viewport bottom coordinate
  5921. * @param top defines the viewport top coordinate
  5922. * @param znear defines the near clip plane
  5923. * @param zfar defines the far clip plane
  5924. * @returns a new matrix as a right-handed orthographic projection matrix
  5925. */
  5926. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5927. var matrix = Matrix.Zero();
  5928. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5929. return matrix;
  5930. };
  5931. /**
  5932. * Stores a right-handed orthographic projection into a given matrix
  5933. * @param left defines the viewport left coordinate
  5934. * @param right defines the viewport right coordinate
  5935. * @param bottom defines the viewport bottom coordinate
  5936. * @param top defines the viewport top coordinate
  5937. * @param znear defines the near clip plane
  5938. * @param zfar defines the far clip plane
  5939. * @param result defines the target matrix
  5940. */
  5941. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5942. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5943. result.m[10] *= -1.0;
  5944. };
  5945. /**
  5946. * Creates a left-handed perspective projection matrix
  5947. * @param width defines the viewport width
  5948. * @param height defines the viewport height
  5949. * @param znear defines the near clip plane
  5950. * @param zfar defines the far clip plane
  5951. * @returns a new matrix as a left-handed perspective projection matrix
  5952. */
  5953. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5954. var matrix = Matrix.Zero();
  5955. var n = znear;
  5956. var f = zfar;
  5957. var a = 2.0 * n / width;
  5958. var b = 2.0 * n / height;
  5959. var c = (f + n) / (f - n);
  5960. var d = -2.0 * f * n / (f - n);
  5961. 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);
  5962. return matrix;
  5963. };
  5964. /**
  5965. * Creates a left-handed perspective projection matrix
  5966. * @param fov defines the horizontal field of view
  5967. * @param aspect defines the aspect ratio
  5968. * @param znear defines the near clip plane
  5969. * @param zfar defines the far clip plane
  5970. * @returns a new matrix as a left-handed perspective projection matrix
  5971. */
  5972. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5973. var matrix = Matrix.Zero();
  5974. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5975. return matrix;
  5976. };
  5977. /**
  5978. * Stores a left-handed perspective projection into a given matrix
  5979. * @param fov defines the horizontal field of view
  5980. * @param aspect defines the aspect ratio
  5981. * @param znear defines the near clip plane
  5982. * @param zfar defines the far clip plane
  5983. * @param result defines the target matrix
  5984. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  5985. */
  5986. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5987. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5988. var n = znear;
  5989. var f = zfar;
  5990. var t = 1.0 / (Math.tan(fov * 0.5));
  5991. var a = isVerticalFovFixed ? (t / aspect) : t;
  5992. var b = isVerticalFovFixed ? t : (t * aspect);
  5993. var c = (f + n) / (f - n);
  5994. var d = -2.0 * f * n / (f - n);
  5995. 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);
  5996. };
  5997. /**
  5998. * Creates a right-handed perspective projection matrix
  5999. * @param fov defines the horizontal field of view
  6000. * @param aspect defines the aspect ratio
  6001. * @param znear defines the near clip plane
  6002. * @param zfar defines the far clip plane
  6003. * @returns a new matrix as a right-handed perspective projection matrix
  6004. */
  6005. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6006. var matrix = Matrix.Zero();
  6007. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6008. return matrix;
  6009. };
  6010. /**
  6011. * Stores a right-handed perspective projection into a given matrix
  6012. * @param fov defines the horizontal field of view
  6013. * @param aspect defines the aspect ratio
  6014. * @param znear defines the near clip plane
  6015. * @param zfar defines the far clip plane
  6016. * @param result defines the target matrix
  6017. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6018. */
  6019. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6020. //alternatively this could be expressed as:
  6021. // m = PerspectiveFovLHToRef
  6022. // m[10] *= -1.0;
  6023. // m[11] *= -1.0;
  6024. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6025. var n = znear;
  6026. var f = zfar;
  6027. var t = 1.0 / (Math.tan(fov * 0.5));
  6028. var a = isVerticalFovFixed ? (t / aspect) : t;
  6029. var b = isVerticalFovFixed ? t : (t * aspect);
  6030. var c = -(f + n) / (f - n);
  6031. var d = -2 * f * n / (f - n);
  6032. 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);
  6033. };
  6034. /**
  6035. * Stores a perspective projection for WebVR info a given matrix
  6036. * @param fov defines the field of view
  6037. * @param znear defines the near clip plane
  6038. * @param zfar defines the far clip plane
  6039. * @param result defines the target matrix
  6040. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6041. */
  6042. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6043. if (rightHanded === void 0) { rightHanded = false; }
  6044. var rightHandedFactor = rightHanded ? -1 : 1;
  6045. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6046. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6047. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6048. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6049. var xScale = 2.0 / (leftTan + rightTan);
  6050. var yScale = 2.0 / (upTan + downTan);
  6051. result.m[0] = xScale;
  6052. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6053. result.m[5] = yScale;
  6054. result.m[6] = result.m[7] = 0.0;
  6055. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6056. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6057. result.m[10] = -zfar / (znear - zfar);
  6058. result.m[11] = 1.0 * rightHandedFactor;
  6059. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6060. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6061. result._markAsUpdated();
  6062. };
  6063. /**
  6064. * Computes a complete transformation matrix
  6065. * @param viewport defines the viewport to use
  6066. * @param world defines the world matrix
  6067. * @param view defines the view matrix
  6068. * @param projection defines the projection matrix
  6069. * @param zmin defines the near clip plane
  6070. * @param zmax defines the far clip plane
  6071. * @returns the transformation matrix
  6072. */
  6073. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6074. var cw = viewport.width;
  6075. var ch = viewport.height;
  6076. var cx = viewport.x;
  6077. var cy = viewport.y;
  6078. 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);
  6079. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6080. };
  6081. /**
  6082. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6083. * @param matrix defines the matrix to use
  6084. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed matrix
  6085. */
  6086. Matrix.GetAsMatrix2x2 = function (matrix) {
  6087. return new Float32Array([
  6088. matrix.m[0], matrix.m[1],
  6089. matrix.m[4], matrix.m[5]
  6090. ]);
  6091. };
  6092. /**
  6093. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6094. * @param matrix defines the matrix to use
  6095. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed matrix
  6096. */
  6097. Matrix.GetAsMatrix3x3 = function (matrix) {
  6098. return new Float32Array([
  6099. matrix.m[0], matrix.m[1], matrix.m[2],
  6100. matrix.m[4], matrix.m[5], matrix.m[6],
  6101. matrix.m[8], matrix.m[9], matrix.m[10]
  6102. ]);
  6103. };
  6104. /**
  6105. * Compute the transpose of a given matrix
  6106. * @param matrix defines the matrix to transpose
  6107. * @returns the new matrix
  6108. */
  6109. Matrix.Transpose = function (matrix) {
  6110. var result = new Matrix();
  6111. Matrix.TransposeToRef(matrix, result);
  6112. return result;
  6113. };
  6114. /**
  6115. * Compute the transpose of a matrix and store it in a target matrix
  6116. * @param matrix defines the matrix to transpose
  6117. * @param result defines the target matrix
  6118. */
  6119. Matrix.TransposeToRef = function (matrix, result) {
  6120. result.m[0] = matrix.m[0];
  6121. result.m[1] = matrix.m[4];
  6122. result.m[2] = matrix.m[8];
  6123. result.m[3] = matrix.m[12];
  6124. result.m[4] = matrix.m[1];
  6125. result.m[5] = matrix.m[5];
  6126. result.m[6] = matrix.m[9];
  6127. result.m[7] = matrix.m[13];
  6128. result.m[8] = matrix.m[2];
  6129. result.m[9] = matrix.m[6];
  6130. result.m[10] = matrix.m[10];
  6131. result.m[11] = matrix.m[14];
  6132. result.m[12] = matrix.m[3];
  6133. result.m[13] = matrix.m[7];
  6134. result.m[14] = matrix.m[11];
  6135. result.m[15] = matrix.m[15];
  6136. };
  6137. /**
  6138. * Computes a reflection matrix from a plane
  6139. * @param plane defines the reflection plane
  6140. * @returns a new matrix
  6141. */
  6142. Matrix.Reflection = function (plane) {
  6143. var matrix = new Matrix();
  6144. Matrix.ReflectionToRef(plane, matrix);
  6145. return matrix;
  6146. };
  6147. /**
  6148. * Computes a reflection matrix from a plane
  6149. * @param plane defines the reflection plane
  6150. * @param result defines the target matrix
  6151. */
  6152. Matrix.ReflectionToRef = function (plane, result) {
  6153. plane.normalize();
  6154. var x = plane.normal.x;
  6155. var y = plane.normal.y;
  6156. var z = plane.normal.z;
  6157. var temp = -2 * x;
  6158. var temp2 = -2 * y;
  6159. var temp3 = -2 * z;
  6160. result.m[0] = (temp * x) + 1;
  6161. result.m[1] = temp2 * x;
  6162. result.m[2] = temp3 * x;
  6163. result.m[3] = 0.0;
  6164. result.m[4] = temp * y;
  6165. result.m[5] = (temp2 * y) + 1;
  6166. result.m[6] = temp3 * y;
  6167. result.m[7] = 0.0;
  6168. result.m[8] = temp * z;
  6169. result.m[9] = temp2 * z;
  6170. result.m[10] = (temp3 * z) + 1;
  6171. result.m[11] = 0.0;
  6172. result.m[12] = temp * plane.d;
  6173. result.m[13] = temp2 * plane.d;
  6174. result.m[14] = temp3 * plane.d;
  6175. result.m[15] = 1.0;
  6176. result._markAsUpdated();
  6177. };
  6178. /**
  6179. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6180. * @param xaxis defines the value of the 1st axis
  6181. * @param yaxis defines the value of the 2nd axis
  6182. * @param zaxis defines the value of the 3rd axis
  6183. * @param result defines the target matrix
  6184. */
  6185. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6186. result.m[0] = xaxis.x;
  6187. result.m[1] = xaxis.y;
  6188. result.m[2] = xaxis.z;
  6189. result.m[3] = 0.0;
  6190. result.m[4] = yaxis.x;
  6191. result.m[5] = yaxis.y;
  6192. result.m[6] = yaxis.z;
  6193. result.m[7] = 0.0;
  6194. result.m[8] = zaxis.x;
  6195. result.m[9] = zaxis.y;
  6196. result.m[10] = zaxis.z;
  6197. result.m[11] = 0.0;
  6198. result.m[12] = 0.0;
  6199. result.m[13] = 0.0;
  6200. result.m[14] = 0.0;
  6201. result.m[15] = 1.0;
  6202. result._markAsUpdated();
  6203. };
  6204. /**
  6205. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6206. * @param quat defines the quaternion to use
  6207. * @param result defines the target matrix
  6208. */
  6209. Matrix.FromQuaternionToRef = function (quat, result) {
  6210. var xx = quat.x * quat.x;
  6211. var yy = quat.y * quat.y;
  6212. var zz = quat.z * quat.z;
  6213. var xy = quat.x * quat.y;
  6214. var zw = quat.z * quat.w;
  6215. var zx = quat.z * quat.x;
  6216. var yw = quat.y * quat.w;
  6217. var yz = quat.y * quat.z;
  6218. var xw = quat.x * quat.w;
  6219. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6220. result.m[1] = 2.0 * (xy + zw);
  6221. result.m[2] = 2.0 * (zx - yw);
  6222. result.m[3] = 0.0;
  6223. result.m[4] = 2.0 * (xy - zw);
  6224. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6225. result.m[6] = 2.0 * (yz + xw);
  6226. result.m[7] = 0.0;
  6227. result.m[8] = 2.0 * (zx + yw);
  6228. result.m[9] = 2.0 * (yz - xw);
  6229. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6230. result.m[11] = 0.0;
  6231. result.m[12] = 0.0;
  6232. result.m[13] = 0.0;
  6233. result.m[14] = 0.0;
  6234. result.m[15] = 1.0;
  6235. result._markAsUpdated();
  6236. };
  6237. Matrix._tempQuaternion = new Quaternion();
  6238. Matrix._xAxis = Vector3.Zero();
  6239. Matrix._yAxis = Vector3.Zero();
  6240. Matrix._zAxis = Vector3.Zero();
  6241. Matrix._updateFlagSeed = 0;
  6242. Matrix._identityReadOnly = Matrix.Identity();
  6243. return Matrix;
  6244. }());
  6245. BABYLON.Matrix = Matrix;
  6246. var Plane = /** @class */ (function () {
  6247. /**
  6248. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6249. */
  6250. function Plane(a, b, c, d) {
  6251. this.normal = new Vector3(a, b, c);
  6252. this.d = d;
  6253. }
  6254. /**
  6255. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6256. */
  6257. Plane.prototype.asArray = function () {
  6258. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6259. };
  6260. // Methods
  6261. /**
  6262. * Returns a new plane copied from the current Plane.
  6263. */
  6264. Plane.prototype.clone = function () {
  6265. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6266. };
  6267. /**
  6268. * Returns the string "Plane".
  6269. */
  6270. Plane.prototype.getClassName = function () {
  6271. return "Plane";
  6272. };
  6273. /**
  6274. * Returns the Plane hash code.
  6275. */
  6276. Plane.prototype.getHashCode = function () {
  6277. var hash = this.normal.getHashCode();
  6278. hash = (hash * 397) ^ (this.d || 0);
  6279. return hash;
  6280. };
  6281. /**
  6282. * Normalize the current Plane in place.
  6283. * Returns the updated Plane.
  6284. */
  6285. Plane.prototype.normalize = function () {
  6286. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6287. var magnitude = 0.0;
  6288. if (norm !== 0) {
  6289. magnitude = 1.0 / norm;
  6290. }
  6291. this.normal.x *= magnitude;
  6292. this.normal.y *= magnitude;
  6293. this.normal.z *= magnitude;
  6294. this.d *= magnitude;
  6295. return this;
  6296. };
  6297. /**
  6298. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6299. */
  6300. Plane.prototype.transform = function (transformation) {
  6301. var transposedMatrix = Matrix.Transpose(transformation);
  6302. var x = this.normal.x;
  6303. var y = this.normal.y;
  6304. var z = this.normal.z;
  6305. var d = this.d;
  6306. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6307. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6308. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6309. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6310. return new Plane(normalX, normalY, normalZ, finalD);
  6311. };
  6312. /**
  6313. * Returns the dot product (float) of the point coordinates and the plane normal.
  6314. */
  6315. Plane.prototype.dotCoordinate = function (point) {
  6316. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6317. };
  6318. /**
  6319. * Updates the current Plane from the plane defined by the three passed points.
  6320. * Returns the updated Plane.
  6321. */
  6322. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6323. var x1 = point2.x - point1.x;
  6324. var y1 = point2.y - point1.y;
  6325. var z1 = point2.z - point1.z;
  6326. var x2 = point3.x - point1.x;
  6327. var y2 = point3.y - point1.y;
  6328. var z2 = point3.z - point1.z;
  6329. var yz = (y1 * z2) - (z1 * y2);
  6330. var xz = (z1 * x2) - (x1 * z2);
  6331. var xy = (x1 * y2) - (y1 * x2);
  6332. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6333. var invPyth;
  6334. if (pyth !== 0) {
  6335. invPyth = 1.0 / pyth;
  6336. }
  6337. else {
  6338. invPyth = 0.0;
  6339. }
  6340. this.normal.x = yz * invPyth;
  6341. this.normal.y = xz * invPyth;
  6342. this.normal.z = xy * invPyth;
  6343. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6344. return this;
  6345. };
  6346. /**
  6347. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6348. */
  6349. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6350. var dot = Vector3.Dot(this.normal, direction);
  6351. return (dot <= epsilon);
  6352. };
  6353. /**
  6354. * Returns the signed distance (float) from the passed point to the Plane.
  6355. */
  6356. Plane.prototype.signedDistanceTo = function (point) {
  6357. return Vector3.Dot(point, this.normal) + this.d;
  6358. };
  6359. // Statics
  6360. /**
  6361. * Returns a new Plane from the passed array.
  6362. */
  6363. Plane.FromArray = function (array) {
  6364. return new Plane(array[0], array[1], array[2], array[3]);
  6365. };
  6366. /**
  6367. * Returns a new Plane defined by the three passed points.
  6368. */
  6369. Plane.FromPoints = function (point1, point2, point3) {
  6370. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6371. result.copyFromPoints(point1, point2, point3);
  6372. return result;
  6373. };
  6374. /**
  6375. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6376. * Note : the vector "normal" is updated because normalized.
  6377. */
  6378. Plane.FromPositionAndNormal = function (origin, normal) {
  6379. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6380. normal.normalize();
  6381. result.normal = normal;
  6382. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6383. return result;
  6384. };
  6385. /**
  6386. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6387. */
  6388. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6389. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6390. return Vector3.Dot(point, normal) + d;
  6391. };
  6392. return Plane;
  6393. }());
  6394. BABYLON.Plane = Plane;
  6395. var Viewport = /** @class */ (function () {
  6396. /**
  6397. * Creates a Viewport object located at (x, y) and sized (width, height).
  6398. */
  6399. function Viewport(x, y, width, height) {
  6400. this.x = x;
  6401. this.y = y;
  6402. this.width = width;
  6403. this.height = height;
  6404. }
  6405. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6406. if (renderWidthOrEngine.getRenderWidth) {
  6407. var engine = renderWidthOrEngine;
  6408. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6409. }
  6410. var renderWidth = renderWidthOrEngine;
  6411. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6412. };
  6413. /**
  6414. * Returns a new Viewport copied from the current one.
  6415. */
  6416. Viewport.prototype.clone = function () {
  6417. return new Viewport(this.x, this.y, this.width, this.height);
  6418. };
  6419. return Viewport;
  6420. }());
  6421. BABYLON.Viewport = Viewport;
  6422. var Frustum = /** @class */ (function () {
  6423. function Frustum() {
  6424. }
  6425. /**
  6426. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6427. */
  6428. Frustum.GetPlanes = function (transform) {
  6429. var frustumPlanes = [];
  6430. for (var index = 0; index < 6; index++) {
  6431. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6432. }
  6433. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6434. return frustumPlanes;
  6435. };
  6436. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6437. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6438. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6439. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6440. frustumPlane.d = transform.m[15] + transform.m[14];
  6441. frustumPlane.normalize();
  6442. };
  6443. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6444. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6445. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6446. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6447. frustumPlane.d = transform.m[15] - transform.m[14];
  6448. frustumPlane.normalize();
  6449. };
  6450. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6451. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6452. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6453. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6454. frustumPlane.d = transform.m[15] + transform.m[12];
  6455. frustumPlane.normalize();
  6456. };
  6457. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6458. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6459. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6460. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6461. frustumPlane.d = transform.m[15] - transform.m[12];
  6462. frustumPlane.normalize();
  6463. };
  6464. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6465. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6466. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6467. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6468. frustumPlane.d = transform.m[15] - transform.m[13];
  6469. frustumPlane.normalize();
  6470. };
  6471. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6472. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6473. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6474. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6475. frustumPlane.d = transform.m[15] + transform.m[13];
  6476. frustumPlane.normalize();
  6477. };
  6478. /**
  6479. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6480. */
  6481. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6482. // Near
  6483. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6484. // Far
  6485. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6486. // Left
  6487. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6488. // Right
  6489. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6490. // Top
  6491. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6492. // Bottom
  6493. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6494. };
  6495. return Frustum;
  6496. }());
  6497. BABYLON.Frustum = Frustum;
  6498. var Space;
  6499. (function (Space) {
  6500. Space[Space["LOCAL"] = 0] = "LOCAL";
  6501. Space[Space["WORLD"] = 1] = "WORLD";
  6502. Space[Space["BONE"] = 2] = "BONE";
  6503. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6504. var Axis = /** @class */ (function () {
  6505. function Axis() {
  6506. }
  6507. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6508. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6509. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6510. return Axis;
  6511. }());
  6512. BABYLON.Axis = Axis;
  6513. ;
  6514. var BezierCurve = /** @class */ (function () {
  6515. function BezierCurve() {
  6516. }
  6517. /**
  6518. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6519. */
  6520. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6521. // Extract X (which is equal to time here)
  6522. var f0 = 1 - 3 * x2 + 3 * x1;
  6523. var f1 = 3 * x2 - 6 * x1;
  6524. var f2 = 3 * x1;
  6525. var refinedT = t;
  6526. for (var i = 0; i < 5; i++) {
  6527. var refinedT2 = refinedT * refinedT;
  6528. var refinedT3 = refinedT2 * refinedT;
  6529. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6530. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6531. refinedT -= (x - t) * slope;
  6532. refinedT = Math.min(1, Math.max(0, refinedT));
  6533. }
  6534. // Resolve cubic bezier for the given x
  6535. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6536. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6537. Math.pow(refinedT, 3);
  6538. };
  6539. return BezierCurve;
  6540. }());
  6541. BABYLON.BezierCurve = BezierCurve;
  6542. var Orientation;
  6543. (function (Orientation) {
  6544. Orientation[Orientation["CW"] = 0] = "CW";
  6545. Orientation[Orientation["CCW"] = 1] = "CCW";
  6546. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6547. var Angle = /** @class */ (function () {
  6548. /**
  6549. * Creates an Angle object of "radians" radians (float).
  6550. */
  6551. function Angle(radians) {
  6552. var _this = this;
  6553. /**
  6554. * Returns the Angle value in degrees (float).
  6555. */
  6556. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6557. /**
  6558. * Returns the Angle value in radians (float).
  6559. */
  6560. this.radians = function () { return _this._radians; };
  6561. this._radians = radians;
  6562. if (this._radians < 0.0)
  6563. this._radians += (2.0 * Math.PI);
  6564. }
  6565. /**
  6566. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6567. */
  6568. Angle.BetweenTwoPoints = function (a, b) {
  6569. var delta = b.subtract(a);
  6570. var theta = Math.atan2(delta.y, delta.x);
  6571. return new Angle(theta);
  6572. };
  6573. /**
  6574. * Returns a new Angle object from the passed float in radians.
  6575. */
  6576. Angle.FromRadians = function (radians) {
  6577. return new Angle(radians);
  6578. };
  6579. /**
  6580. * Returns a new Angle object from the passed float in degrees.
  6581. */
  6582. Angle.FromDegrees = function (degrees) {
  6583. return new Angle(degrees * Math.PI / 180.0);
  6584. };
  6585. return Angle;
  6586. }());
  6587. BABYLON.Angle = Angle;
  6588. var Arc2 = /** @class */ (function () {
  6589. /**
  6590. * Creates an Arc object from the three passed points : start, middle and end.
  6591. */
  6592. function Arc2(startPoint, midPoint, endPoint) {
  6593. this.startPoint = startPoint;
  6594. this.midPoint = midPoint;
  6595. this.endPoint = endPoint;
  6596. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6597. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6598. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6599. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6600. 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);
  6601. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6602. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6603. var a1 = this.startAngle.degrees();
  6604. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6605. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6606. // angles correction
  6607. if (a2 - a1 > +180.0)
  6608. a2 -= 360.0;
  6609. if (a2 - a1 < -180.0)
  6610. a2 += 360.0;
  6611. if (a3 - a2 > +180.0)
  6612. a3 -= 360.0;
  6613. if (a3 - a2 < -180.0)
  6614. a3 += 360.0;
  6615. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6616. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6617. }
  6618. return Arc2;
  6619. }());
  6620. BABYLON.Arc2 = Arc2;
  6621. var Path2 = /** @class */ (function () {
  6622. /**
  6623. * Creates a Path2 object from the starting 2D coordinates x and y.
  6624. */
  6625. function Path2(x, y) {
  6626. this._points = new Array();
  6627. this._length = 0.0;
  6628. this.closed = false;
  6629. this._points.push(new Vector2(x, y));
  6630. }
  6631. /**
  6632. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6633. * Returns the updated Path2.
  6634. */
  6635. Path2.prototype.addLineTo = function (x, y) {
  6636. if (this.closed) {
  6637. return this;
  6638. }
  6639. var newPoint = new Vector2(x, y);
  6640. var previousPoint = this._points[this._points.length - 1];
  6641. this._points.push(newPoint);
  6642. this._length += newPoint.subtract(previousPoint).length();
  6643. return this;
  6644. };
  6645. /**
  6646. * 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.
  6647. * Returns the updated Path2.
  6648. */
  6649. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6650. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6651. if (this.closed) {
  6652. return this;
  6653. }
  6654. var startPoint = this._points[this._points.length - 1];
  6655. var midPoint = new Vector2(midX, midY);
  6656. var endPoint = new Vector2(endX, endY);
  6657. var arc = new Arc2(startPoint, midPoint, endPoint);
  6658. var increment = arc.angle.radians() / numberOfSegments;
  6659. if (arc.orientation === Orientation.CW)
  6660. increment *= -1;
  6661. var currentAngle = arc.startAngle.radians() + increment;
  6662. for (var i = 0; i < numberOfSegments; i++) {
  6663. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6664. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6665. this.addLineTo(x, y);
  6666. currentAngle += increment;
  6667. }
  6668. return this;
  6669. };
  6670. /**
  6671. * Closes the Path2.
  6672. * Returns the Path2.
  6673. */
  6674. Path2.prototype.close = function () {
  6675. this.closed = true;
  6676. return this;
  6677. };
  6678. /**
  6679. * Returns the Path2 total length (float).
  6680. */
  6681. Path2.prototype.length = function () {
  6682. var result = this._length;
  6683. if (!this.closed) {
  6684. var lastPoint = this._points[this._points.length - 1];
  6685. var firstPoint = this._points[0];
  6686. result += (firstPoint.subtract(lastPoint).length());
  6687. }
  6688. return result;
  6689. };
  6690. /**
  6691. * Returns the Path2 internal array of points.
  6692. */
  6693. Path2.prototype.getPoints = function () {
  6694. return this._points;
  6695. };
  6696. /**
  6697. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6698. */
  6699. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6700. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6701. return Vector2.Zero();
  6702. }
  6703. var lengthPosition = normalizedLengthPosition * this.length();
  6704. var previousOffset = 0;
  6705. for (var i = 0; i < this._points.length; i++) {
  6706. var j = (i + 1) % this._points.length;
  6707. var a = this._points[i];
  6708. var b = this._points[j];
  6709. var bToA = b.subtract(a);
  6710. var nextOffset = (bToA.length() + previousOffset);
  6711. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6712. var dir = bToA.normalize();
  6713. var localOffset = lengthPosition - previousOffset;
  6714. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6715. }
  6716. previousOffset = nextOffset;
  6717. }
  6718. return Vector2.Zero();
  6719. };
  6720. /**
  6721. * Returns a new Path2 starting at the coordinates (x, y).
  6722. */
  6723. Path2.StartingAt = function (x, y) {
  6724. return new Path2(x, y);
  6725. };
  6726. return Path2;
  6727. }());
  6728. BABYLON.Path2 = Path2;
  6729. var Path3D = /** @class */ (function () {
  6730. /**
  6731. * new Path3D(path, normal, raw)
  6732. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6733. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6734. * path : an array of Vector3, the curve axis of the Path3D
  6735. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6736. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6737. */
  6738. function Path3D(path, firstNormal, raw) {
  6739. if (firstNormal === void 0) { firstNormal = null; }
  6740. this.path = path;
  6741. this._curve = new Array();
  6742. this._distances = new Array();
  6743. this._tangents = new Array();
  6744. this._normals = new Array();
  6745. this._binormals = new Array();
  6746. for (var p = 0; p < path.length; p++) {
  6747. this._curve[p] = path[p].clone(); // hard copy
  6748. }
  6749. this._raw = raw || false;
  6750. this._compute(firstNormal);
  6751. }
  6752. /**
  6753. * Returns the Path3D array of successive Vector3 designing its curve.
  6754. */
  6755. Path3D.prototype.getCurve = function () {
  6756. return this._curve;
  6757. };
  6758. /**
  6759. * Returns an array populated with tangent vectors on each Path3D curve point.
  6760. */
  6761. Path3D.prototype.getTangents = function () {
  6762. return this._tangents;
  6763. };
  6764. /**
  6765. * Returns an array populated with normal vectors on each Path3D curve point.
  6766. */
  6767. Path3D.prototype.getNormals = function () {
  6768. return this._normals;
  6769. };
  6770. /**
  6771. * Returns an array populated with binormal vectors on each Path3D curve point.
  6772. */
  6773. Path3D.prototype.getBinormals = function () {
  6774. return this._binormals;
  6775. };
  6776. /**
  6777. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6778. */
  6779. Path3D.prototype.getDistances = function () {
  6780. return this._distances;
  6781. };
  6782. /**
  6783. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6784. * Returns the same object updated.
  6785. */
  6786. Path3D.prototype.update = function (path, firstNormal) {
  6787. if (firstNormal === void 0) { firstNormal = null; }
  6788. for (var p = 0; p < path.length; p++) {
  6789. this._curve[p].x = path[p].x;
  6790. this._curve[p].y = path[p].y;
  6791. this._curve[p].z = path[p].z;
  6792. }
  6793. this._compute(firstNormal);
  6794. return this;
  6795. };
  6796. // private function compute() : computes tangents, normals and binormals
  6797. Path3D.prototype._compute = function (firstNormal) {
  6798. var l = this._curve.length;
  6799. // first and last tangents
  6800. this._tangents[0] = this._getFirstNonNullVector(0);
  6801. if (!this._raw) {
  6802. this._tangents[0].normalize();
  6803. }
  6804. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6805. if (!this._raw) {
  6806. this._tangents[l - 1].normalize();
  6807. }
  6808. // normals and binormals at first point : arbitrary vector with _normalVector()
  6809. var tg0 = this._tangents[0];
  6810. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6811. this._normals[0] = pp0;
  6812. if (!this._raw) {
  6813. this._normals[0].normalize();
  6814. }
  6815. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6816. if (!this._raw) {
  6817. this._binormals[0].normalize();
  6818. }
  6819. this._distances[0] = 0.0;
  6820. // normals and binormals : next points
  6821. var prev; // previous vector (segment)
  6822. var cur; // current vector (segment)
  6823. var curTang; // current tangent
  6824. // previous normal
  6825. var prevBinor; // previous binormal
  6826. for (var i = 1; i < l; i++) {
  6827. // tangents
  6828. prev = this._getLastNonNullVector(i);
  6829. if (i < l - 1) {
  6830. cur = this._getFirstNonNullVector(i);
  6831. this._tangents[i] = prev.add(cur);
  6832. this._tangents[i].normalize();
  6833. }
  6834. this._distances[i] = this._distances[i - 1] + prev.length();
  6835. // normals and binormals
  6836. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6837. curTang = this._tangents[i];
  6838. prevBinor = this._binormals[i - 1];
  6839. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6840. if (!this._raw) {
  6841. this._normals[i].normalize();
  6842. }
  6843. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6844. if (!this._raw) {
  6845. this._binormals[i].normalize();
  6846. }
  6847. }
  6848. };
  6849. // private function getFirstNonNullVector(index)
  6850. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6851. Path3D.prototype._getFirstNonNullVector = function (index) {
  6852. var i = 1;
  6853. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6854. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6855. i++;
  6856. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6857. }
  6858. return nNVector;
  6859. };
  6860. // private function getLastNonNullVector(index)
  6861. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6862. Path3D.prototype._getLastNonNullVector = function (index) {
  6863. var i = 1;
  6864. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6865. while (nLVector.length() === 0 && index > i + 1) {
  6866. i++;
  6867. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6868. }
  6869. return nLVector;
  6870. };
  6871. // private function normalVector(v0, vt, va) :
  6872. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6873. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6874. Path3D.prototype._normalVector = function (v0, vt, va) {
  6875. var normal0;
  6876. var tgl = vt.length();
  6877. if (tgl === 0.0) {
  6878. tgl = 1.0;
  6879. }
  6880. if (va === undefined || va === null) {
  6881. var point;
  6882. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6883. point = new Vector3(0.0, -1.0, 0.0);
  6884. }
  6885. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6886. point = new Vector3(1.0, 0.0, 0.0);
  6887. }
  6888. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6889. point = new Vector3(0.0, 0.0, 1.0);
  6890. }
  6891. else {
  6892. point = Vector3.Zero();
  6893. }
  6894. normal0 = Vector3.Cross(vt, point);
  6895. }
  6896. else {
  6897. normal0 = Vector3.Cross(vt, va);
  6898. Vector3.CrossToRef(normal0, vt, normal0);
  6899. }
  6900. normal0.normalize();
  6901. return normal0;
  6902. };
  6903. return Path3D;
  6904. }());
  6905. BABYLON.Path3D = Path3D;
  6906. var Curve3 = /** @class */ (function () {
  6907. /**
  6908. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6909. * A Curve3 is designed from a series of successive Vector3.
  6910. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6911. */
  6912. function Curve3(points) {
  6913. this._length = 0.0;
  6914. this._points = points;
  6915. this._length = this._computeLength(points);
  6916. }
  6917. /**
  6918. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6919. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6920. * @param v1 (Vector3) the control point
  6921. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6922. * @param nbPoints (integer) the wanted number of points in the curve
  6923. */
  6924. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6925. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6926. var bez = new Array();
  6927. var equation = function (t, val0, val1, val2) {
  6928. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6929. return res;
  6930. };
  6931. for (var i = 0; i <= nbPoints; i++) {
  6932. 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)));
  6933. }
  6934. return new Curve3(bez);
  6935. };
  6936. /**
  6937. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6938. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6939. * @param v1 (Vector3) the first control point
  6940. * @param v2 (Vector3) the second control point
  6941. * @param v3 (Vector3) the end point of the Cubic Bezier
  6942. * @param nbPoints (integer) the wanted number of points in the curve
  6943. */
  6944. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6945. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6946. var bez = new Array();
  6947. var equation = function (t, val0, val1, val2, val3) {
  6948. 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;
  6949. return res;
  6950. };
  6951. for (var i = 0; i <= nbPoints; i++) {
  6952. 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)));
  6953. }
  6954. return new Curve3(bez);
  6955. };
  6956. /**
  6957. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6958. * @param p1 (Vector3) the origin point of the Hermite Spline
  6959. * @param t1 (Vector3) the tangent vector at the origin point
  6960. * @param p2 (Vector3) the end point of the Hermite Spline
  6961. * @param t2 (Vector3) the tangent vector at the end point
  6962. * @param nbPoints (integer) the wanted number of points in the curve
  6963. */
  6964. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6965. var hermite = new Array();
  6966. var step = 1.0 / nbPoints;
  6967. for (var i = 0; i <= nbPoints; i++) {
  6968. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6969. }
  6970. return new Curve3(hermite);
  6971. };
  6972. /**
  6973. * Returns a Curve3 object along a CatmullRom Spline curve :
  6974. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6975. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6976. */
  6977. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6978. var totalPoints = new Array();
  6979. totalPoints.push(points[0].clone());
  6980. Array.prototype.push.apply(totalPoints, points);
  6981. totalPoints.push(points[points.length - 1].clone());
  6982. var catmullRom = new Array();
  6983. var step = 1.0 / nbPoints;
  6984. var amount = 0.0;
  6985. for (var i = 0; i < totalPoints.length - 3; i++) {
  6986. amount = 0;
  6987. for (var c = 0; c < nbPoints; c++) {
  6988. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6989. amount += step;
  6990. }
  6991. }
  6992. i--;
  6993. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6994. return new Curve3(catmullRom);
  6995. };
  6996. /**
  6997. * Returns the Curve3 stored array of successive Vector3
  6998. */
  6999. Curve3.prototype.getPoints = function () {
  7000. return this._points;
  7001. };
  7002. /**
  7003. * Returns the computed length (float) of the curve.
  7004. */
  7005. Curve3.prototype.length = function () {
  7006. return this._length;
  7007. };
  7008. /**
  7009. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7010. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7011. * curveA and curveB keep unchanged.
  7012. */
  7013. Curve3.prototype.continue = function (curve) {
  7014. var lastPoint = this._points[this._points.length - 1];
  7015. var continuedPoints = this._points.slice();
  7016. var curvePoints = curve.getPoints();
  7017. for (var i = 1; i < curvePoints.length; i++) {
  7018. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7019. }
  7020. var continuedCurve = new Curve3(continuedPoints);
  7021. return continuedCurve;
  7022. };
  7023. Curve3.prototype._computeLength = function (path) {
  7024. var l = 0;
  7025. for (var i = 1; i < path.length; i++) {
  7026. l += (path[i].subtract(path[i - 1])).length();
  7027. }
  7028. return l;
  7029. };
  7030. return Curve3;
  7031. }());
  7032. BABYLON.Curve3 = Curve3;
  7033. // Vertex formats
  7034. var PositionNormalVertex = /** @class */ (function () {
  7035. function PositionNormalVertex(position, normal) {
  7036. if (position === void 0) { position = Vector3.Zero(); }
  7037. if (normal === void 0) { normal = Vector3.Up(); }
  7038. this.position = position;
  7039. this.normal = normal;
  7040. }
  7041. PositionNormalVertex.prototype.clone = function () {
  7042. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7043. };
  7044. return PositionNormalVertex;
  7045. }());
  7046. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7047. var PositionNormalTextureVertex = /** @class */ (function () {
  7048. function PositionNormalTextureVertex(position, normal, uv) {
  7049. if (position === void 0) { position = Vector3.Zero(); }
  7050. if (normal === void 0) { normal = Vector3.Up(); }
  7051. if (uv === void 0) { uv = Vector2.Zero(); }
  7052. this.position = position;
  7053. this.normal = normal;
  7054. this.uv = uv;
  7055. }
  7056. PositionNormalTextureVertex.prototype.clone = function () {
  7057. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7058. };
  7059. return PositionNormalTextureVertex;
  7060. }());
  7061. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7062. // Temporary pre-allocated objects for engine internal use
  7063. // usage in any internal function :
  7064. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7065. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7066. var Tmp = /** @class */ (function () {
  7067. function Tmp() {
  7068. }
  7069. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7070. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7071. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7072. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7073. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7074. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7075. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7076. Matrix.Zero(), Matrix.Zero(),
  7077. Matrix.Zero(), Matrix.Zero(),
  7078. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7079. return Tmp;
  7080. }());
  7081. BABYLON.Tmp = Tmp;
  7082. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  7083. var MathTmp = /** @class */ (function () {
  7084. function MathTmp() {
  7085. }
  7086. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7087. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7088. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7089. return MathTmp;
  7090. }());
  7091. })(BABYLON || (BABYLON = {}));
  7092. //# sourceMappingURL=babylon.math.js.map
  7093. "use strict";
  7094. var BABYLON;
  7095. (function (BABYLON) {
  7096. var Scalar = /** @class */ (function () {
  7097. function Scalar() {
  7098. }
  7099. /**
  7100. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7101. */
  7102. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7103. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7104. var num = a - b;
  7105. return -epsilon <= num && num <= epsilon;
  7106. };
  7107. /**
  7108. * Returns a string : the upper case translation of the number i to hexadecimal.
  7109. */
  7110. Scalar.ToHex = function (i) {
  7111. var str = i.toString(16);
  7112. if (i <= 15) {
  7113. return ("0" + str).toUpperCase();
  7114. }
  7115. return str.toUpperCase();
  7116. };
  7117. /**
  7118. * Returns -1 if value is negative and +1 is value is positive.
  7119. * Returns the value itself if it's equal to zero.
  7120. */
  7121. Scalar.Sign = function (value) {
  7122. value = +value; // convert to a number
  7123. if (value === 0 || isNaN(value))
  7124. return value;
  7125. return value > 0 ? 1 : -1;
  7126. };
  7127. /**
  7128. * Returns the value itself if it's between min and max.
  7129. * Returns min if the value is lower than min.
  7130. * Returns max if the value is greater than max.
  7131. */
  7132. Scalar.Clamp = function (value, min, max) {
  7133. if (min === void 0) { min = 0; }
  7134. if (max === void 0) { max = 1; }
  7135. return Math.min(max, Math.max(min, value));
  7136. };
  7137. /**
  7138. * Returns the log2 of value.
  7139. */
  7140. Scalar.Log2 = function (value) {
  7141. return Math.log(value) * Math.LOG2E;
  7142. };
  7143. /**
  7144. * Loops the value, so that it is never larger than length and never smaller than 0.
  7145. *
  7146. * This is similar to the modulo operator but it works with floating point numbers.
  7147. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7148. * With t = 5 and length = 2.5, the result would be 0.0.
  7149. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7150. */
  7151. Scalar.Repeat = function (value, length) {
  7152. return value - Math.floor(value / length) * length;
  7153. };
  7154. /**
  7155. * Normalize the value between 0.0 and 1.0 using min and max values
  7156. */
  7157. Scalar.Normalize = function (value, min, max) {
  7158. return (value - min) / (max - min);
  7159. };
  7160. /**
  7161. * Denormalize the value from 0.0 and 1.0 using min and max values
  7162. */
  7163. Scalar.Denormalize = function (normalized, min, max) {
  7164. return (normalized * (max - min) + min);
  7165. };
  7166. /**
  7167. * Calculates the shortest difference between two given angles given in degrees.
  7168. */
  7169. Scalar.DeltaAngle = function (current, target) {
  7170. var num = Scalar.Repeat(target - current, 360.0);
  7171. if (num > 180.0) {
  7172. num -= 360.0;
  7173. }
  7174. return num;
  7175. };
  7176. /**
  7177. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7178. *
  7179. * The returned value will move back and forth between 0 and length
  7180. */
  7181. Scalar.PingPong = function (tx, length) {
  7182. var t = Scalar.Repeat(tx, length * 2.0);
  7183. return length - Math.abs(t - length);
  7184. };
  7185. /**
  7186. * Interpolates between min and max with smoothing at the limits.
  7187. *
  7188. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7189. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7190. */
  7191. Scalar.SmoothStep = function (from, to, tx) {
  7192. var t = Scalar.Clamp(tx);
  7193. t = -2.0 * t * t * t + 3.0 * t * t;
  7194. return to * t + from * (1.0 - t);
  7195. };
  7196. /**
  7197. * Moves a value current towards target.
  7198. *
  7199. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7200. * Negative values of maxDelta pushes the value away from target.
  7201. */
  7202. Scalar.MoveTowards = function (current, target, maxDelta) {
  7203. var result = 0;
  7204. if (Math.abs(target - current) <= maxDelta) {
  7205. result = target;
  7206. }
  7207. else {
  7208. result = current + Scalar.Sign(target - current) * maxDelta;
  7209. }
  7210. return result;
  7211. };
  7212. /**
  7213. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7214. *
  7215. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7216. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7217. */
  7218. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7219. var num = Scalar.DeltaAngle(current, target);
  7220. var result = 0;
  7221. if (-maxDelta < num && num < maxDelta) {
  7222. result = target;
  7223. }
  7224. else {
  7225. target = current + num;
  7226. result = Scalar.MoveTowards(current, target, maxDelta);
  7227. }
  7228. return result;
  7229. };
  7230. /**
  7231. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7232. */
  7233. Scalar.Lerp = function (start, end, amount) {
  7234. return start + ((end - start) * amount);
  7235. };
  7236. /**
  7237. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7238. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7239. */
  7240. Scalar.LerpAngle = function (start, end, amount) {
  7241. var num = Scalar.Repeat(end - start, 360.0);
  7242. if (num > 180.0) {
  7243. num -= 360.0;
  7244. }
  7245. return start + num * Scalar.Clamp(amount);
  7246. };
  7247. /**
  7248. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7249. */
  7250. Scalar.InverseLerp = function (a, b, value) {
  7251. var result = 0;
  7252. if (a != b) {
  7253. result = Scalar.Clamp((value - a) / (b - a));
  7254. }
  7255. else {
  7256. result = 0.0;
  7257. }
  7258. return result;
  7259. };
  7260. /**
  7261. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7262. */
  7263. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7264. var squared = amount * amount;
  7265. var cubed = amount * squared;
  7266. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7267. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7268. var part3 = (cubed - (2.0 * squared)) + amount;
  7269. var part4 = cubed - squared;
  7270. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7271. };
  7272. /**
  7273. * Returns a random float number between and min and max values
  7274. */
  7275. Scalar.RandomRange = function (min, max) {
  7276. if (min === max)
  7277. return min;
  7278. return ((Math.random() * (max - min)) + min);
  7279. };
  7280. /**
  7281. * This function returns percentage of a number in a given range.
  7282. *
  7283. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7284. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7285. */
  7286. Scalar.RangeToPercent = function (number, min, max) {
  7287. return ((number - min) / (max - min));
  7288. };
  7289. /**
  7290. * This function returns number that corresponds to the percentage in a given range.
  7291. *
  7292. * PercentToRange(0.34,0,100) will return 34.
  7293. */
  7294. Scalar.PercentToRange = function (percent, min, max) {
  7295. return ((max - min) * percent + min);
  7296. };
  7297. /**
  7298. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7299. * @param angle The angle to normalize in radian.
  7300. * @return The converted angle.
  7301. */
  7302. Scalar.NormalizeRadians = function (angle) {
  7303. // More precise but slower version kept for reference.
  7304. // angle = angle % Tools.TwoPi;
  7305. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7306. //if (angle > Math.PI) {
  7307. // angle -= Tools.TwoPi;
  7308. //}
  7309. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7310. return angle;
  7311. };
  7312. /**
  7313. * Two pi constants convenient for computation.
  7314. */
  7315. Scalar.TwoPi = Math.PI * 2;
  7316. return Scalar;
  7317. }());
  7318. BABYLON.Scalar = Scalar;
  7319. })(BABYLON || (BABYLON = {}));
  7320. //# sourceMappingURL=babylon.math.scalar.js.map
  7321. "use strict";
  7322. //# sourceMappingURL=babylon.mixins.js.map
  7323. "use strict";
  7324. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7325. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7326. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7327. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7328. //# sourceMappingURL=babylon.webgl2.js.map
  7329. "use strict";
  7330. var BABYLON;
  7331. (function (BABYLON) {
  7332. var __decoratorInitialStore = {};
  7333. var __mergedStore = {};
  7334. var _copySource = function (creationFunction, source, instanciate) {
  7335. var destination = creationFunction();
  7336. // Tags
  7337. if (BABYLON.Tags) {
  7338. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7339. }
  7340. var classStore = getMergedStore(destination);
  7341. // Properties
  7342. for (var property in classStore) {
  7343. var propertyDescriptor = classStore[property];
  7344. var sourceProperty = source[property];
  7345. var propertyType = propertyDescriptor.type;
  7346. if (sourceProperty !== undefined && sourceProperty !== null) {
  7347. switch (propertyType) {
  7348. case 0: // Value
  7349. case 6: // Mesh reference
  7350. case 11:// Camera reference
  7351. destination[property] = sourceProperty;
  7352. break;
  7353. case 1:// Texture
  7354. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7355. break;
  7356. case 2: // Color3
  7357. case 3: // FresnelParameters
  7358. case 4: // Vector2
  7359. case 5: // Vector3
  7360. case 7: // Color Curves
  7361. case 10:// Quaternion
  7362. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7363. break;
  7364. }
  7365. }
  7366. }
  7367. return destination;
  7368. };
  7369. function getDirectStore(target) {
  7370. var classKey = target.getClassName();
  7371. if (!__decoratorInitialStore[classKey]) {
  7372. __decoratorInitialStore[classKey] = {};
  7373. }
  7374. return __decoratorInitialStore[classKey];
  7375. }
  7376. /**
  7377. * Return the list of properties flagged as serializable
  7378. * @param target: host object
  7379. */
  7380. function getMergedStore(target) {
  7381. var classKey = target.getClassName();
  7382. if (__mergedStore[classKey]) {
  7383. return __mergedStore[classKey];
  7384. }
  7385. __mergedStore[classKey] = {};
  7386. var store = __mergedStore[classKey];
  7387. var currentTarget = target;
  7388. var currentKey = classKey;
  7389. while (currentKey) {
  7390. var initialStore = __decoratorInitialStore[currentKey];
  7391. for (var property in initialStore) {
  7392. store[property] = initialStore[property];
  7393. }
  7394. var parent_1 = void 0;
  7395. var done = false;
  7396. do {
  7397. parent_1 = Object.getPrototypeOf(currentTarget);
  7398. if (!parent_1.getClassName) {
  7399. done = true;
  7400. break;
  7401. }
  7402. if (parent_1.getClassName() !== currentKey) {
  7403. break;
  7404. }
  7405. currentTarget = parent_1;
  7406. } while (parent_1);
  7407. if (done) {
  7408. break;
  7409. }
  7410. currentKey = parent_1.getClassName();
  7411. currentTarget = parent_1;
  7412. }
  7413. return store;
  7414. }
  7415. function generateSerializableMember(type, sourceName) {
  7416. return function (target, propertyKey) {
  7417. var classStore = getDirectStore(target);
  7418. if (!classStore[propertyKey]) {
  7419. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7420. }
  7421. };
  7422. }
  7423. function generateExpandMember(setCallback, targetKey) {
  7424. if (targetKey === void 0) { targetKey = null; }
  7425. return function (target, propertyKey) {
  7426. var key = targetKey || ("_" + propertyKey);
  7427. Object.defineProperty(target, propertyKey, {
  7428. get: function () {
  7429. return this[key];
  7430. },
  7431. set: function (value) {
  7432. if (this[key] === value) {
  7433. return;
  7434. }
  7435. this[key] = value;
  7436. target[setCallback].apply(this);
  7437. },
  7438. enumerable: true,
  7439. configurable: true
  7440. });
  7441. };
  7442. }
  7443. function expandToProperty(callback, targetKey) {
  7444. if (targetKey === void 0) { targetKey = null; }
  7445. return generateExpandMember(callback, targetKey);
  7446. }
  7447. BABYLON.expandToProperty = expandToProperty;
  7448. function serialize(sourceName) {
  7449. return generateSerializableMember(0, sourceName); // value member
  7450. }
  7451. BABYLON.serialize = serialize;
  7452. function serializeAsTexture(sourceName) {
  7453. return generateSerializableMember(1, sourceName); // texture member
  7454. }
  7455. BABYLON.serializeAsTexture = serializeAsTexture;
  7456. function serializeAsColor3(sourceName) {
  7457. return generateSerializableMember(2, sourceName); // color3 member
  7458. }
  7459. BABYLON.serializeAsColor3 = serializeAsColor3;
  7460. function serializeAsFresnelParameters(sourceName) {
  7461. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7462. }
  7463. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7464. function serializeAsVector2(sourceName) {
  7465. return generateSerializableMember(4, sourceName); // vector2 member
  7466. }
  7467. BABYLON.serializeAsVector2 = serializeAsVector2;
  7468. function serializeAsVector3(sourceName) {
  7469. return generateSerializableMember(5, sourceName); // vector3 member
  7470. }
  7471. BABYLON.serializeAsVector3 = serializeAsVector3;
  7472. function serializeAsMeshReference(sourceName) {
  7473. return generateSerializableMember(6, sourceName); // mesh reference member
  7474. }
  7475. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7476. function serializeAsColorCurves(sourceName) {
  7477. return generateSerializableMember(7, sourceName); // color curves
  7478. }
  7479. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7480. function serializeAsColor4(sourceName) {
  7481. return generateSerializableMember(8, sourceName); // color 4
  7482. }
  7483. BABYLON.serializeAsColor4 = serializeAsColor4;
  7484. function serializeAsImageProcessingConfiguration(sourceName) {
  7485. return generateSerializableMember(9, sourceName); // image processing
  7486. }
  7487. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7488. function serializeAsQuaternion(sourceName) {
  7489. return generateSerializableMember(10, sourceName); // quaternion member
  7490. }
  7491. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7492. /**
  7493. * Decorator used to define property that can be serialized as reference to a camera
  7494. * @param sourceName defines the name of the property to decorate
  7495. */
  7496. function serializeAsCameraReference(sourceName) {
  7497. return generateSerializableMember(11, sourceName); // camera reference member
  7498. }
  7499. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7500. var SerializationHelper = /** @class */ (function () {
  7501. function SerializationHelper() {
  7502. }
  7503. SerializationHelper.Serialize = function (entity, serializationObject) {
  7504. if (!serializationObject) {
  7505. serializationObject = {};
  7506. }
  7507. // Tags
  7508. if (BABYLON.Tags) {
  7509. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7510. }
  7511. var serializedProperties = getMergedStore(entity);
  7512. // Properties
  7513. for (var property in serializedProperties) {
  7514. var propertyDescriptor = serializedProperties[property];
  7515. var targetPropertyName = propertyDescriptor.sourceName || property;
  7516. var propertyType = propertyDescriptor.type;
  7517. var sourceProperty = entity[property];
  7518. if (sourceProperty !== undefined && sourceProperty !== null) {
  7519. switch (propertyType) {
  7520. case 0:// Value
  7521. serializationObject[targetPropertyName] = sourceProperty;
  7522. break;
  7523. case 1:// Texture
  7524. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7525. break;
  7526. case 2:// Color3
  7527. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7528. break;
  7529. case 3:// FresnelParameters
  7530. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7531. break;
  7532. case 4:// Vector2
  7533. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7534. break;
  7535. case 5:// Vector3
  7536. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7537. break;
  7538. case 6:// Mesh reference
  7539. serializationObject[targetPropertyName] = sourceProperty.id;
  7540. break;
  7541. case 7:// Color Curves
  7542. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7543. break;
  7544. case 8:// Color 4
  7545. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7546. break;
  7547. case 9:// Image Processing
  7548. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7549. break;
  7550. case 10:// Quaternion
  7551. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7552. break;
  7553. case 11:// Camera reference
  7554. serializationObject[targetPropertyName] = sourceProperty.id;
  7555. break;
  7556. }
  7557. }
  7558. }
  7559. return serializationObject;
  7560. };
  7561. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7562. if (rootUrl === void 0) { rootUrl = null; }
  7563. var destination = creationFunction();
  7564. if (!rootUrl) {
  7565. rootUrl = "";
  7566. }
  7567. // Tags
  7568. if (BABYLON.Tags) {
  7569. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7570. }
  7571. var classStore = getMergedStore(destination);
  7572. // Properties
  7573. for (var property in classStore) {
  7574. var propertyDescriptor = classStore[property];
  7575. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7576. var propertyType = propertyDescriptor.type;
  7577. if (sourceProperty !== undefined && sourceProperty !== null) {
  7578. var dest = destination;
  7579. switch (propertyType) {
  7580. case 0:// Value
  7581. dest[property] = sourceProperty;
  7582. break;
  7583. case 1:// Texture
  7584. if (scene) {
  7585. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7586. }
  7587. break;
  7588. case 2:// Color3
  7589. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7590. break;
  7591. case 3:// FresnelParameters
  7592. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7593. break;
  7594. case 4:// Vector2
  7595. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7596. break;
  7597. case 5:// Vector3
  7598. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7599. break;
  7600. case 6:// Mesh reference
  7601. if (scene) {
  7602. dest[property] = scene.getLastMeshByID(sourceProperty);
  7603. }
  7604. break;
  7605. case 7:// Color Curves
  7606. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7607. break;
  7608. case 8:// Color 4
  7609. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7610. break;
  7611. case 9:// Image Processing
  7612. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7613. break;
  7614. case 10:// Quaternion
  7615. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7616. break;
  7617. case 11:// Camera reference
  7618. if (scene) {
  7619. dest[property] = scene.getCameraByID(sourceProperty);
  7620. }
  7621. break;
  7622. }
  7623. }
  7624. }
  7625. return destination;
  7626. };
  7627. SerializationHelper.Clone = function (creationFunction, source) {
  7628. return _copySource(creationFunction, source, false);
  7629. };
  7630. SerializationHelper.Instanciate = function (creationFunction, source) {
  7631. return _copySource(creationFunction, source, true);
  7632. };
  7633. return SerializationHelper;
  7634. }());
  7635. BABYLON.SerializationHelper = SerializationHelper;
  7636. })(BABYLON || (BABYLON = {}));
  7637. //# sourceMappingURL=babylon.decorators.js.map
  7638. "use strict";
  7639. var BABYLON;
  7640. (function (BABYLON) {
  7641. /**
  7642. * Wrapper class for promise with external resolve and reject.
  7643. */
  7644. var Deferred = /** @class */ (function () {
  7645. /**
  7646. * Constructor for this deferred object.
  7647. */
  7648. function Deferred() {
  7649. var _this = this;
  7650. this.promise = new Promise(function (resolve, reject) {
  7651. _this._resolve = resolve;
  7652. _this._reject = reject;
  7653. });
  7654. }
  7655. Object.defineProperty(Deferred.prototype, "resolve", {
  7656. /**
  7657. * The resolve method of the promise associated with this deferred object.
  7658. */
  7659. get: function () {
  7660. return this._resolve;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. Object.defineProperty(Deferred.prototype, "reject", {
  7666. /**
  7667. * The reject method of the promise associated with this deferred object.
  7668. */
  7669. get: function () {
  7670. return this._reject;
  7671. },
  7672. enumerable: true,
  7673. configurable: true
  7674. });
  7675. return Deferred;
  7676. }());
  7677. BABYLON.Deferred = Deferred;
  7678. })(BABYLON || (BABYLON = {}));
  7679. //# sourceMappingURL=babylon.deferred.js.map
  7680. "use strict";
  7681. var BABYLON;
  7682. (function (BABYLON) {
  7683. /**
  7684. * A class serves as a medium between the observable and its observers
  7685. */
  7686. var EventState = /** @class */ (function () {
  7687. /**
  7688. * Create a new EventState
  7689. * @param mask defines the mask associated with this state
  7690. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7691. * @param target defines the original target of the state
  7692. * @param currentTarget defines the current target of the state
  7693. */
  7694. function EventState(mask, skipNextObservers, target, currentTarget) {
  7695. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7696. this.initalize(mask, skipNextObservers, target, currentTarget);
  7697. }
  7698. /**
  7699. * Initialize the current event state
  7700. * @param mask defines the mask associated with this state
  7701. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7702. * @param target defines the original target of the state
  7703. * @param currentTarget defines the current target of the state
  7704. * @returns the current event state
  7705. */
  7706. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7707. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7708. this.mask = mask;
  7709. this.skipNextObservers = skipNextObservers;
  7710. this.target = target;
  7711. this.currentTarget = currentTarget;
  7712. return this;
  7713. };
  7714. return EventState;
  7715. }());
  7716. BABYLON.EventState = EventState;
  7717. /**
  7718. * Represent an Observer registered to a given Observable object.
  7719. */
  7720. var Observer = /** @class */ (function () {
  7721. /**
  7722. * Creates a new observer
  7723. * @param callback defines the callback to call when the observer is notified
  7724. * @param mask defines the mask of the observer (used to filter notifications)
  7725. * @param scope defines the current scope used to restore the JS context
  7726. */
  7727. function Observer(
  7728. /**
  7729. * Defines the callback to call when the observer is notified
  7730. */
  7731. callback,
  7732. /**
  7733. * Defines the mask of the observer (used to filter notifications)
  7734. */
  7735. mask,
  7736. /**
  7737. * Defines the current scope used to restore the JS context
  7738. */
  7739. scope) {
  7740. if (scope === void 0) { scope = null; }
  7741. this.callback = callback;
  7742. this.mask = mask;
  7743. this.scope = scope;
  7744. /** @ignore */
  7745. this._willBeUnregistered = false;
  7746. /**
  7747. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7748. */
  7749. this.unregisterOnNextCall = false;
  7750. }
  7751. return Observer;
  7752. }());
  7753. BABYLON.Observer = Observer;
  7754. /**
  7755. * Represent a list of observers registered to multiple Observables object.
  7756. */
  7757. var MultiObserver = /** @class */ (function () {
  7758. function MultiObserver() {
  7759. }
  7760. /**
  7761. * Release associated resources
  7762. */
  7763. MultiObserver.prototype.dispose = function () {
  7764. if (this._observers && this._observables) {
  7765. for (var index = 0; index < this._observers.length; index++) {
  7766. this._observables[index].remove(this._observers[index]);
  7767. }
  7768. }
  7769. this._observers = null;
  7770. this._observables = null;
  7771. };
  7772. /**
  7773. * Raise a callback when one of the observable will notify
  7774. * @param observables defines a list of observables to watch
  7775. * @param callback defines the callback to call on notification
  7776. * @param mask defines the mask used to filter notifications
  7777. * @param scope defines the current scope used to restore the JS context
  7778. * @returns the new MultiObserver
  7779. */
  7780. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7781. if (mask === void 0) { mask = -1; }
  7782. if (scope === void 0) { scope = null; }
  7783. var result = new MultiObserver();
  7784. result._observers = new Array();
  7785. result._observables = observables;
  7786. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7787. var observable = observables_1[_i];
  7788. var observer = observable.add(callback, mask, false, scope);
  7789. if (observer) {
  7790. result._observers.push(observer);
  7791. }
  7792. }
  7793. return result;
  7794. };
  7795. return MultiObserver;
  7796. }());
  7797. BABYLON.MultiObserver = MultiObserver;
  7798. /**
  7799. * The Observable class is a simple implementation of the Observable pattern.
  7800. *
  7801. * 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.
  7802. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7803. * 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).
  7804. * 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.
  7805. */
  7806. var Observable = /** @class */ (function () {
  7807. /**
  7808. * Creates a new observable
  7809. * @param onObserverAdded defines a callback to call when a new observer is added
  7810. */
  7811. function Observable(onObserverAdded) {
  7812. this._observers = new Array();
  7813. this._eventState = new EventState(0);
  7814. if (onObserverAdded) {
  7815. this._onObserverAdded = onObserverAdded;
  7816. }
  7817. }
  7818. /**
  7819. * Create a new Observer with the specified callback
  7820. * @param callback the callback that will be executed for that Observer
  7821. * @param mask the mask used to filter observers
  7822. * @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.
  7823. * @param scope optional scope for the callback to be called from
  7824. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7825. * @returns the new observer created for the callback
  7826. */
  7827. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7828. if (mask === void 0) { mask = -1; }
  7829. if (insertFirst === void 0) { insertFirst = false; }
  7830. if (scope === void 0) { scope = null; }
  7831. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7832. if (!callback) {
  7833. return null;
  7834. }
  7835. var observer = new Observer(callback, mask, scope);
  7836. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7837. if (insertFirst) {
  7838. this._observers.unshift(observer);
  7839. }
  7840. else {
  7841. this._observers.push(observer);
  7842. }
  7843. if (this._onObserverAdded) {
  7844. this._onObserverAdded(observer);
  7845. }
  7846. return observer;
  7847. };
  7848. /**
  7849. * Remove an Observer from the Observable object
  7850. * @param observer the instance of the Observer to remove
  7851. * @returns false if it doesn't belong to this Observable
  7852. */
  7853. Observable.prototype.remove = function (observer) {
  7854. if (!observer) {
  7855. return false;
  7856. }
  7857. var index = this._observers.indexOf(observer);
  7858. if (index !== -1) {
  7859. this._observers.splice(index, 1);
  7860. return true;
  7861. }
  7862. return false;
  7863. };
  7864. /**
  7865. * Remove a callback from the Observable object
  7866. * @param callback the callback to remove
  7867. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7868. * @returns false if it doesn't belong to this Observable
  7869. */
  7870. Observable.prototype.removeCallback = function (callback, scope) {
  7871. for (var index = 0; index < this._observers.length; index++) {
  7872. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7873. this._observers.splice(index, 1);
  7874. return true;
  7875. }
  7876. }
  7877. return false;
  7878. };
  7879. Observable.prototype._deferUnregister = function (observer) {
  7880. var _this = this;
  7881. observer.unregisterOnNextCall = false;
  7882. observer._willBeUnregistered = true;
  7883. BABYLON.Tools.SetImmediate(function () {
  7884. _this.remove(observer);
  7885. });
  7886. };
  7887. /**
  7888. * Notify all Observers by calling their respective callback with the given data
  7889. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7890. * @param eventData defines the data to send to all observers
  7891. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7892. * @param target defines the original target of the state
  7893. * @param currentTarget defines the current target of the state
  7894. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7895. */
  7896. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7897. if (mask === void 0) { mask = -1; }
  7898. if (!this._observers.length) {
  7899. return true;
  7900. }
  7901. var state = this._eventState;
  7902. state.mask = mask;
  7903. state.target = target;
  7904. state.currentTarget = currentTarget;
  7905. state.skipNextObservers = false;
  7906. state.lastReturnValue = eventData;
  7907. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7908. var obs = _a[_i];
  7909. if (obs._willBeUnregistered) {
  7910. continue;
  7911. }
  7912. if (obs.mask & mask) {
  7913. if (obs.scope) {
  7914. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7915. }
  7916. else {
  7917. state.lastReturnValue = obs.callback(eventData, state);
  7918. }
  7919. if (obs.unregisterOnNextCall) {
  7920. this._deferUnregister(obs);
  7921. }
  7922. }
  7923. if (state.skipNextObservers) {
  7924. return false;
  7925. }
  7926. }
  7927. return true;
  7928. };
  7929. /**
  7930. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7931. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7932. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7933. * and it is crucial that all callbacks will be executed.
  7934. * The order of the callbacks is kept, callbacks are not executed parallel.
  7935. *
  7936. * @param eventData The data to be sent to each callback
  7937. * @param mask is used to filter observers defaults to -1
  7938. * @param target defines the callback target (see EventState)
  7939. * @param currentTarget defines he current object in the bubbling phase
  7940. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7941. */
  7942. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7943. var _this = this;
  7944. if (mask === void 0) { mask = -1; }
  7945. // create an empty promise
  7946. var p = Promise.resolve(eventData);
  7947. // no observers? return this promise.
  7948. if (!this._observers.length) {
  7949. return p;
  7950. }
  7951. var state = this._eventState;
  7952. state.mask = mask;
  7953. state.target = target;
  7954. state.currentTarget = currentTarget;
  7955. state.skipNextObservers = false;
  7956. // execute one callback after another (not using Promise.all, the order is important)
  7957. this._observers.forEach(function (obs) {
  7958. if (state.skipNextObservers) {
  7959. return;
  7960. }
  7961. if (obs._willBeUnregistered) {
  7962. return;
  7963. }
  7964. if (obs.mask & mask) {
  7965. if (obs.scope) {
  7966. p = p.then(function (lastReturnedValue) {
  7967. state.lastReturnValue = lastReturnedValue;
  7968. return obs.callback.apply(obs.scope, [eventData, state]);
  7969. });
  7970. }
  7971. else {
  7972. p = p.then(function (lastReturnedValue) {
  7973. state.lastReturnValue = lastReturnedValue;
  7974. return obs.callback(eventData, state);
  7975. });
  7976. }
  7977. if (obs.unregisterOnNextCall) {
  7978. _this._deferUnregister(obs);
  7979. }
  7980. }
  7981. });
  7982. // return the eventData
  7983. return p.then(function () { return eventData; });
  7984. };
  7985. /**
  7986. * Notify a specific observer
  7987. * @param observer defines the observer to notify
  7988. * @param eventData defines the data to be sent to each callback
  7989. * @param mask is used to filter observers defaults to -1
  7990. */
  7991. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7992. if (mask === void 0) { mask = -1; }
  7993. var state = this._eventState;
  7994. state.mask = mask;
  7995. state.skipNextObservers = false;
  7996. observer.callback(eventData, state);
  7997. };
  7998. /**
  7999. * Gets a boolean indicating if the observable has at least one observer
  8000. * @returns true is the Observable has at least one Observer registered
  8001. */
  8002. Observable.prototype.hasObservers = function () {
  8003. return this._observers.length > 0;
  8004. };
  8005. /**
  8006. * Clear the list of observers
  8007. */
  8008. Observable.prototype.clear = function () {
  8009. this._observers = new Array();
  8010. this._onObserverAdded = null;
  8011. };
  8012. /**
  8013. * Clone the current observable
  8014. * @returns a new observable
  8015. */
  8016. Observable.prototype.clone = function () {
  8017. var result = new Observable();
  8018. result._observers = this._observers.slice(0);
  8019. return result;
  8020. };
  8021. /**
  8022. * Does this observable handles observer registered with a given mask
  8023. * @param mask defines the mask to be tested
  8024. * @return whether or not one observer registered with the given mask is handeled
  8025. **/
  8026. Observable.prototype.hasSpecificMask = function (mask) {
  8027. if (mask === void 0) { mask = -1; }
  8028. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8029. var obs = _a[_i];
  8030. if (obs.mask & mask || obs.mask === mask) {
  8031. return true;
  8032. }
  8033. }
  8034. return false;
  8035. };
  8036. return Observable;
  8037. }());
  8038. BABYLON.Observable = Observable;
  8039. })(BABYLON || (BABYLON = {}));
  8040. //# sourceMappingURL=babylon.observable.js.map
  8041. "use strict";
  8042. var BABYLON;
  8043. (function (BABYLON) {
  8044. var SmartArray = /** @class */ (function () {
  8045. function SmartArray(capacity) {
  8046. this.length = 0;
  8047. this.data = new Array(capacity);
  8048. this._id = SmartArray._GlobalId++;
  8049. }
  8050. SmartArray.prototype.push = function (value) {
  8051. this.data[this.length++] = value;
  8052. if (this.length > this.data.length) {
  8053. this.data.length *= 2;
  8054. }
  8055. };
  8056. SmartArray.prototype.forEach = function (func) {
  8057. for (var index = 0; index < this.length; index++) {
  8058. func(this.data[index]);
  8059. }
  8060. };
  8061. SmartArray.prototype.sort = function (compareFn) {
  8062. this.data.sort(compareFn);
  8063. };
  8064. SmartArray.prototype.reset = function () {
  8065. this.length = 0;
  8066. };
  8067. SmartArray.prototype.dispose = function () {
  8068. this.reset();
  8069. if (this.data) {
  8070. this.data.length = 0;
  8071. this.data = [];
  8072. }
  8073. };
  8074. SmartArray.prototype.concat = function (array) {
  8075. if (array.length === 0) {
  8076. return;
  8077. }
  8078. if (this.length + array.length > this.data.length) {
  8079. this.data.length = (this.length + array.length) * 2;
  8080. }
  8081. for (var index = 0; index < array.length; index++) {
  8082. this.data[this.length++] = (array.data || array)[index];
  8083. }
  8084. };
  8085. SmartArray.prototype.indexOf = function (value) {
  8086. var position = this.data.indexOf(value);
  8087. if (position >= this.length) {
  8088. return -1;
  8089. }
  8090. return position;
  8091. };
  8092. SmartArray.prototype.contains = function (value) {
  8093. return this.data.indexOf(value) !== -1;
  8094. };
  8095. // Statics
  8096. SmartArray._GlobalId = 0;
  8097. return SmartArray;
  8098. }());
  8099. BABYLON.SmartArray = SmartArray;
  8100. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8101. __extends(SmartArrayNoDuplicate, _super);
  8102. function SmartArrayNoDuplicate() {
  8103. var _this = _super !== null && _super.apply(this, arguments) || this;
  8104. _this._duplicateId = 0;
  8105. return _this;
  8106. }
  8107. SmartArrayNoDuplicate.prototype.push = function (value) {
  8108. _super.prototype.push.call(this, value);
  8109. if (!value.__smartArrayFlags) {
  8110. value.__smartArrayFlags = {};
  8111. }
  8112. value.__smartArrayFlags[this._id] = this._duplicateId;
  8113. };
  8114. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8115. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8116. return false;
  8117. }
  8118. this.push(value);
  8119. return true;
  8120. };
  8121. SmartArrayNoDuplicate.prototype.reset = function () {
  8122. _super.prototype.reset.call(this);
  8123. this._duplicateId++;
  8124. };
  8125. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8126. if (array.length === 0) {
  8127. return;
  8128. }
  8129. if (this.length + array.length > this.data.length) {
  8130. this.data.length = (this.length + array.length) * 2;
  8131. }
  8132. for (var index = 0; index < array.length; index++) {
  8133. var item = (array.data || array)[index];
  8134. this.pushNoDuplicate(item);
  8135. }
  8136. };
  8137. return SmartArrayNoDuplicate;
  8138. }(SmartArray));
  8139. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8140. })(BABYLON || (BABYLON = {}));
  8141. //# sourceMappingURL=babylon.smartArray.js.map
  8142. "use strict";
  8143. var BABYLON;
  8144. (function (BABYLON) {
  8145. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8146. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8147. var LoadFileError = /** @class */ (function (_super) {
  8148. __extends(LoadFileError, _super);
  8149. function LoadFileError(message, request) {
  8150. var _this = _super.call(this, message) || this;
  8151. _this.request = request;
  8152. _this.name = "LoadFileError";
  8153. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8154. return _this;
  8155. }
  8156. // Polyfill for Object.setPrototypeOf if necessary.
  8157. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8158. return LoadFileError;
  8159. }(Error));
  8160. BABYLON.LoadFileError = LoadFileError;
  8161. var RetryStrategy = /** @class */ (function () {
  8162. function RetryStrategy() {
  8163. }
  8164. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8165. if (maxRetries === void 0) { maxRetries = 3; }
  8166. if (baseInterval === void 0) { baseInterval = 500; }
  8167. return function (url, request, retryIndex) {
  8168. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8169. return -1;
  8170. }
  8171. return Math.pow(2, retryIndex) * baseInterval;
  8172. };
  8173. };
  8174. return RetryStrategy;
  8175. }());
  8176. BABYLON.RetryStrategy = RetryStrategy;
  8177. // Screenshots
  8178. var screenshotCanvas;
  8179. var cloneValue = function (source, destinationObject) {
  8180. if (!source)
  8181. return null;
  8182. if (source instanceof BABYLON.Mesh) {
  8183. return null;
  8184. }
  8185. if (source instanceof BABYLON.SubMesh) {
  8186. return source.clone(destinationObject);
  8187. }
  8188. else if (source.clone) {
  8189. return source.clone();
  8190. }
  8191. return null;
  8192. };
  8193. var Tools = /** @class */ (function () {
  8194. function Tools() {
  8195. }
  8196. /**
  8197. * Interpolates between a and b via alpha
  8198. * @param a The lower value (returned when alpha = 0)
  8199. * @param b The upper value (returned when alpha = 1)
  8200. * @param alpha The interpolation-factor
  8201. * @return The mixed value
  8202. */
  8203. Tools.Mix = function (a, b, alpha) {
  8204. return a * (1 - alpha) + b * alpha;
  8205. };
  8206. Tools.Instantiate = function (className) {
  8207. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8208. return Tools.RegisteredExternalClasses[className];
  8209. }
  8210. var arr = className.split(".");
  8211. var fn = (window || this);
  8212. for (var i = 0, len = arr.length; i < len; i++) {
  8213. fn = fn[arr[i]];
  8214. }
  8215. if (typeof fn !== "function") {
  8216. return null;
  8217. }
  8218. return fn;
  8219. };
  8220. /**
  8221. * Provides a slice function that will work even on IE
  8222. * @param data defines the array to slice
  8223. * @param start defines the start of the data (optional)
  8224. * @param end defines the end of the data (optional)
  8225. * @returns the new sliced array
  8226. */
  8227. Tools.Slice = function (data, start, end) {
  8228. if (data.slice) {
  8229. return data.slice(start, end);
  8230. }
  8231. return Array.prototype.slice.call(data, start, end);
  8232. };
  8233. Tools.SetImmediate = function (action) {
  8234. if (window.setImmediate) {
  8235. window.setImmediate(action);
  8236. }
  8237. else {
  8238. setTimeout(action, 1);
  8239. }
  8240. };
  8241. Tools.IsExponentOfTwo = function (value) {
  8242. var count = 1;
  8243. do {
  8244. count *= 2;
  8245. } while (count < value);
  8246. return count === value;
  8247. };
  8248. /**
  8249. * Find the next highest power of two.
  8250. * @param x Number to start search from.
  8251. * @return Next highest power of two.
  8252. */
  8253. Tools.CeilingPOT = function (x) {
  8254. x--;
  8255. x |= x >> 1;
  8256. x |= x >> 2;
  8257. x |= x >> 4;
  8258. x |= x >> 8;
  8259. x |= x >> 16;
  8260. x++;
  8261. return x;
  8262. };
  8263. /**
  8264. * Find the next lowest power of two.
  8265. * @param x Number to start search from.
  8266. * @return Next lowest power of two.
  8267. */
  8268. Tools.FloorPOT = function (x) {
  8269. x = x | (x >> 1);
  8270. x = x | (x >> 2);
  8271. x = x | (x >> 4);
  8272. x = x | (x >> 8);
  8273. x = x | (x >> 16);
  8274. return x - (x >> 1);
  8275. };
  8276. /**
  8277. * Find the nearest power of two.
  8278. * @param x Number to start search from.
  8279. * @return Next nearest power of two.
  8280. */
  8281. Tools.NearestPOT = function (x) {
  8282. var c = Tools.CeilingPOT(x);
  8283. var f = Tools.FloorPOT(x);
  8284. return (c - x) > (x - f) ? f : c;
  8285. };
  8286. Tools.GetExponentOfTwo = function (value, max, mode) {
  8287. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8288. var pot;
  8289. switch (mode) {
  8290. case BABYLON.Engine.SCALEMODE_FLOOR:
  8291. pot = Tools.FloorPOT(value);
  8292. break;
  8293. case BABYLON.Engine.SCALEMODE_NEAREST:
  8294. pot = Tools.NearestPOT(value);
  8295. break;
  8296. case BABYLON.Engine.SCALEMODE_CEILING:
  8297. default:
  8298. pot = Tools.CeilingPOT(value);
  8299. break;
  8300. }
  8301. return Math.min(pot, max);
  8302. };
  8303. Tools.GetFilename = function (path) {
  8304. var index = path.lastIndexOf("/");
  8305. if (index < 0)
  8306. return path;
  8307. return path.substring(index + 1);
  8308. };
  8309. /**
  8310. * Extracts the "folder" part of a path (everything before the filename).
  8311. * @param uri The URI to extract the info from
  8312. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8313. * @returns The "folder" part of the path
  8314. */
  8315. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8316. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8317. var index = uri.lastIndexOf("/");
  8318. if (index < 0) {
  8319. if (returnUnchangedIfNoSlash) {
  8320. return uri;
  8321. }
  8322. return "";
  8323. }
  8324. return uri.substring(0, index + 1);
  8325. };
  8326. Tools.GetDOMTextContent = function (element) {
  8327. var result = "";
  8328. var child = element.firstChild;
  8329. while (child) {
  8330. if (child.nodeType === 3) {
  8331. result += child.textContent;
  8332. }
  8333. child = child.nextSibling;
  8334. }
  8335. return result;
  8336. };
  8337. Tools.ToDegrees = function (angle) {
  8338. return angle * 180 / Math.PI;
  8339. };
  8340. Tools.ToRadians = function (angle) {
  8341. return angle * Math.PI / 180;
  8342. };
  8343. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8344. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8345. var output = "";
  8346. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8347. var i = 0;
  8348. var bytes = new Uint8Array(buffer);
  8349. while (i < bytes.length) {
  8350. chr1 = bytes[i++];
  8351. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8352. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8353. enc1 = chr1 >> 2;
  8354. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8355. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8356. enc4 = chr3 & 63;
  8357. if (isNaN(chr2)) {
  8358. enc3 = enc4 = 64;
  8359. }
  8360. else if (isNaN(chr3)) {
  8361. enc4 = 64;
  8362. }
  8363. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8364. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8365. }
  8366. return "data:image/png;base64," + output;
  8367. };
  8368. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8369. if (bias === void 0) { bias = null; }
  8370. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8371. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8372. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8373. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8374. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8375. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8376. }
  8377. if (bias) {
  8378. minimum.x -= minimum.x * bias.x + bias.y;
  8379. minimum.y -= minimum.y * bias.x + bias.y;
  8380. minimum.z -= minimum.z * bias.x + bias.y;
  8381. maximum.x += maximum.x * bias.x + bias.y;
  8382. maximum.y += maximum.y * bias.x + bias.y;
  8383. maximum.z += maximum.z * bias.x + bias.y;
  8384. }
  8385. return {
  8386. minimum: minimum,
  8387. maximum: maximum
  8388. };
  8389. };
  8390. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8391. if (bias === void 0) { bias = null; }
  8392. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8393. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8394. if (!stride) {
  8395. stride = 3;
  8396. }
  8397. for (var index = start; index < start + count; index++) {
  8398. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8399. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8400. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8401. }
  8402. if (bias) {
  8403. minimum.x -= minimum.x * bias.x + bias.y;
  8404. minimum.y -= minimum.y * bias.x + bias.y;
  8405. minimum.z -= minimum.z * bias.x + bias.y;
  8406. maximum.x += maximum.x * bias.x + bias.y;
  8407. maximum.y += maximum.y * bias.x + bias.y;
  8408. maximum.z += maximum.z * bias.x + bias.y;
  8409. }
  8410. return {
  8411. minimum: minimum,
  8412. maximum: maximum
  8413. };
  8414. };
  8415. Tools.Vector2ArrayFeeder = function (array) {
  8416. return function (index) {
  8417. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8418. var length = isFloatArray ? array.length / 2 : array.length;
  8419. if (index >= length) {
  8420. return null;
  8421. }
  8422. if (isFloatArray) {
  8423. var fa = array;
  8424. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8425. }
  8426. var a = array;
  8427. return a[index];
  8428. };
  8429. };
  8430. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8431. if (bias === void 0) { bias = null; }
  8432. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8433. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8434. var i = 0;
  8435. var cur = feeder(i++);
  8436. while (cur) {
  8437. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8438. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8439. cur = feeder(i++);
  8440. }
  8441. if (bias) {
  8442. minimum.x -= minimum.x * bias.x + bias.y;
  8443. minimum.y -= minimum.y * bias.x + bias.y;
  8444. maximum.x += maximum.x * bias.x + bias.y;
  8445. maximum.y += maximum.y * bias.x + bias.y;
  8446. }
  8447. return {
  8448. minimum: minimum,
  8449. maximum: maximum
  8450. };
  8451. };
  8452. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8453. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8454. return null;
  8455. return Array.isArray(obj) ? obj : [obj];
  8456. };
  8457. // Misc.
  8458. Tools.GetPointerPrefix = function () {
  8459. var eventPrefix = "pointer";
  8460. // Check if pointer events are supported
  8461. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8462. eventPrefix = "mouse";
  8463. }
  8464. return eventPrefix;
  8465. };
  8466. /**
  8467. * @param func - the function to be called
  8468. * @param requester - the object that will request the next frame. Falls back to window.
  8469. */
  8470. Tools.QueueNewFrame = function (func, requester) {
  8471. if (!Tools.IsWindowObjectExist()) {
  8472. return setTimeout(func, 16);
  8473. }
  8474. if (!requester) {
  8475. requester = window;
  8476. }
  8477. if (requester.requestAnimationFrame) {
  8478. return requester.requestAnimationFrame(func);
  8479. }
  8480. else if (requester.msRequestAnimationFrame) {
  8481. return requester.msRequestAnimationFrame(func);
  8482. }
  8483. else if (requester.webkitRequestAnimationFrame) {
  8484. return requester.webkitRequestAnimationFrame(func);
  8485. }
  8486. else if (requester.mozRequestAnimationFrame) {
  8487. return requester.mozRequestAnimationFrame(func);
  8488. }
  8489. else if (requester.oRequestAnimationFrame) {
  8490. return requester.oRequestAnimationFrame(func);
  8491. }
  8492. else {
  8493. return window.setTimeout(func, 16);
  8494. }
  8495. };
  8496. Tools.RequestFullscreen = function (element) {
  8497. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8498. if (!requestFunction)
  8499. return;
  8500. requestFunction.call(element);
  8501. };
  8502. Tools.ExitFullscreen = function () {
  8503. if (document.exitFullscreen) {
  8504. document.exitFullscreen();
  8505. }
  8506. else if (document.mozCancelFullScreen) {
  8507. document.mozCancelFullScreen();
  8508. }
  8509. else if (document.webkitCancelFullScreen) {
  8510. document.webkitCancelFullScreen();
  8511. }
  8512. else if (document.msCancelFullScreen) {
  8513. document.msCancelFullScreen();
  8514. }
  8515. };
  8516. Tools.SetCorsBehavior = function (url, element) {
  8517. if (url && url.indexOf("data:") === 0) {
  8518. return;
  8519. }
  8520. if (Tools.CorsBehavior) {
  8521. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8522. element.crossOrigin = Tools.CorsBehavior;
  8523. }
  8524. else {
  8525. var result = Tools.CorsBehavior(url);
  8526. if (result) {
  8527. element.crossOrigin = result;
  8528. }
  8529. }
  8530. }
  8531. };
  8532. // External files
  8533. Tools.CleanUrl = function (url) {
  8534. url = url.replace(/#/mg, "%23");
  8535. return url;
  8536. };
  8537. Tools.LoadImage = function (url, onLoad, onError, database) {
  8538. if (url instanceof ArrayBuffer) {
  8539. url = Tools.EncodeArrayBufferTobase64(url);
  8540. }
  8541. url = Tools.CleanUrl(url);
  8542. url = Tools.PreprocessUrl(url);
  8543. var img = new Image();
  8544. Tools.SetCorsBehavior(url, img);
  8545. var loadHandler = function () {
  8546. img.removeEventListener("load", loadHandler);
  8547. img.removeEventListener("error", errorHandler);
  8548. onLoad(img);
  8549. };
  8550. var errorHandler = function (err) {
  8551. img.removeEventListener("load", loadHandler);
  8552. img.removeEventListener("error", errorHandler);
  8553. Tools.Error("Error while trying to load image: " + url);
  8554. if (onError) {
  8555. onError("Error while trying to load image: " + url, err);
  8556. }
  8557. };
  8558. img.addEventListener("load", loadHandler);
  8559. img.addEventListener("error", errorHandler);
  8560. var noIndexedDB = function () {
  8561. img.src = url;
  8562. };
  8563. var loadFromIndexedDB = function () {
  8564. if (database) {
  8565. database.loadImageFromDB(url, img);
  8566. }
  8567. };
  8568. //ANY database to do!
  8569. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8570. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8571. }
  8572. else {
  8573. if (url.indexOf("file:") !== -1) {
  8574. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8575. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8576. try {
  8577. var blobURL;
  8578. try {
  8579. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8580. }
  8581. catch (ex) {
  8582. // Chrome doesn't support oneTimeOnly parameter
  8583. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8584. }
  8585. img.src = blobURL;
  8586. }
  8587. catch (e) {
  8588. img.src = "";
  8589. }
  8590. return img;
  8591. }
  8592. }
  8593. noIndexedDB();
  8594. }
  8595. return img;
  8596. };
  8597. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8598. url = Tools.CleanUrl(url);
  8599. url = Tools.PreprocessUrl(url);
  8600. // If file and file input are set
  8601. if (url.indexOf("file:") !== -1) {
  8602. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8603. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8604. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8605. }
  8606. }
  8607. var loadUrl = Tools.BaseUrl + url;
  8608. var aborted = false;
  8609. var fileRequest = {
  8610. onCompleteObservable: new BABYLON.Observable(),
  8611. abort: function () { return aborted = true; },
  8612. };
  8613. var requestFile = function () {
  8614. var request = new XMLHttpRequest();
  8615. var retryHandle = null;
  8616. fileRequest.abort = function () {
  8617. aborted = true;
  8618. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8619. request.abort();
  8620. }
  8621. if (retryHandle !== null) {
  8622. clearTimeout(retryHandle);
  8623. retryHandle = null;
  8624. }
  8625. };
  8626. var retryLoop = function (retryIndex) {
  8627. request.open('GET', loadUrl, true);
  8628. if (useArrayBuffer) {
  8629. request.responseType = "arraybuffer";
  8630. }
  8631. if (onProgress) {
  8632. request.addEventListener("progress", onProgress);
  8633. }
  8634. var onLoadEnd = function () {
  8635. request.removeEventListener("loadend", onLoadEnd);
  8636. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8637. fileRequest.onCompleteObservable.clear();
  8638. };
  8639. request.addEventListener("loadend", onLoadEnd);
  8640. var onReadyStateChange = function () {
  8641. if (aborted) {
  8642. return;
  8643. }
  8644. // In case of undefined state in some browsers.
  8645. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8646. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8647. request.removeEventListener("readystatechange", onReadyStateChange);
  8648. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8649. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8650. return;
  8651. }
  8652. var retryStrategy = Tools.DefaultRetryStrategy;
  8653. if (retryStrategy) {
  8654. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8655. if (waitTime !== -1) {
  8656. // Prevent the request from completing for retry.
  8657. request.removeEventListener("loadend", onLoadEnd);
  8658. request = new XMLHttpRequest();
  8659. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8660. return;
  8661. }
  8662. }
  8663. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8664. if (onError) {
  8665. onError(request, e);
  8666. }
  8667. else {
  8668. throw e;
  8669. }
  8670. }
  8671. };
  8672. request.addEventListener("readystatechange", onReadyStateChange);
  8673. request.send();
  8674. };
  8675. retryLoop(0);
  8676. };
  8677. // Caching all files
  8678. if (database && database.enableSceneOffline) {
  8679. var noIndexedDB_1 = function () {
  8680. if (!aborted) {
  8681. requestFile();
  8682. }
  8683. };
  8684. var loadFromIndexedDB = function () {
  8685. // TODO: database needs to support aborting and should return a IFileRequest
  8686. if (aborted) {
  8687. return;
  8688. }
  8689. if (database) {
  8690. database.loadFileFromDB(url, function (data) {
  8691. if (!aborted) {
  8692. onSuccess(data);
  8693. }
  8694. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8695. }, onProgress ? function (event) {
  8696. if (!aborted) {
  8697. onProgress(event);
  8698. }
  8699. } : undefined, noIndexedDB_1, useArrayBuffer);
  8700. }
  8701. };
  8702. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8703. }
  8704. else {
  8705. requestFile();
  8706. }
  8707. return fileRequest;
  8708. };
  8709. /**
  8710. * Load a script (identified by an url). When the url returns, the
  8711. * content of this file is added into a new script element, attached to the DOM (body element)
  8712. */
  8713. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8714. var head = document.getElementsByTagName('head')[0];
  8715. var script = document.createElement('script');
  8716. script.type = 'text/javascript';
  8717. script.src = scriptUrl;
  8718. script.onload = function () {
  8719. if (onSuccess) {
  8720. onSuccess();
  8721. }
  8722. };
  8723. script.onerror = function (e) {
  8724. if (onError) {
  8725. onError("Unable to load script", e);
  8726. }
  8727. };
  8728. head.appendChild(script);
  8729. };
  8730. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8731. var reader = new FileReader();
  8732. var request = {
  8733. onCompleteObservable: new BABYLON.Observable(),
  8734. abort: function () { return reader.abort(); },
  8735. };
  8736. reader.onloadend = function (e) {
  8737. request.onCompleteObservable.notifyObservers(request);
  8738. };
  8739. reader.onload = function (e) {
  8740. //target doesn't have result from ts 1.3
  8741. callback(e.target['result']);
  8742. };
  8743. reader.onprogress = progressCallback;
  8744. reader.readAsDataURL(fileToLoad);
  8745. return request;
  8746. };
  8747. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8748. var reader = new FileReader();
  8749. var request = {
  8750. onCompleteObservable: new BABYLON.Observable(),
  8751. abort: function () { return reader.abort(); },
  8752. };
  8753. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8754. reader.onerror = function (e) {
  8755. Tools.Log("Error while reading file: " + fileToLoad.name);
  8756. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8757. };
  8758. reader.onload = function (e) {
  8759. //target doesn't have result from ts 1.3
  8760. callback(e.target['result']);
  8761. };
  8762. if (progressCallBack) {
  8763. reader.onprogress = progressCallBack;
  8764. }
  8765. if (!useArrayBuffer) {
  8766. // Asynchronous read
  8767. reader.readAsText(fileToLoad);
  8768. }
  8769. else {
  8770. reader.readAsArrayBuffer(fileToLoad);
  8771. }
  8772. return request;
  8773. };
  8774. //returns a downloadable url to a file content.
  8775. Tools.FileAsURL = function (content) {
  8776. var fileBlob = new Blob([content]);
  8777. var url = window.URL || window.webkitURL;
  8778. var link = url.createObjectURL(fileBlob);
  8779. return link;
  8780. };
  8781. // Misc.
  8782. Tools.Format = function (value, decimals) {
  8783. if (decimals === void 0) { decimals = 2; }
  8784. return value.toFixed(decimals);
  8785. };
  8786. Tools.CheckExtends = function (v, min, max) {
  8787. if (v.x < min.x)
  8788. min.x = v.x;
  8789. if (v.y < min.y)
  8790. min.y = v.y;
  8791. if (v.z < min.z)
  8792. min.z = v.z;
  8793. if (v.x > max.x)
  8794. max.x = v.x;
  8795. if (v.y > max.y)
  8796. max.y = v.y;
  8797. if (v.z > max.z)
  8798. max.z = v.z;
  8799. };
  8800. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8801. for (var prop in source) {
  8802. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8803. continue;
  8804. }
  8805. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8806. continue;
  8807. }
  8808. var sourceValue = source[prop];
  8809. var typeOfSourceValue = typeof sourceValue;
  8810. if (typeOfSourceValue === "function") {
  8811. continue;
  8812. }
  8813. try {
  8814. if (typeOfSourceValue === "object") {
  8815. if (sourceValue instanceof Array) {
  8816. destination[prop] = [];
  8817. if (sourceValue.length > 0) {
  8818. if (typeof sourceValue[0] == "object") {
  8819. for (var index = 0; index < sourceValue.length; index++) {
  8820. var clonedValue = cloneValue(sourceValue[index], destination);
  8821. if (destination[prop].indexOf(clonedValue) === -1) {
  8822. destination[prop].push(clonedValue);
  8823. }
  8824. }
  8825. }
  8826. else {
  8827. destination[prop] = sourceValue.slice(0);
  8828. }
  8829. }
  8830. }
  8831. else {
  8832. destination[prop] = cloneValue(sourceValue, destination);
  8833. }
  8834. }
  8835. else {
  8836. destination[prop] = sourceValue;
  8837. }
  8838. }
  8839. catch (e) {
  8840. // Just ignore error (it could be because of a read-only property)
  8841. }
  8842. }
  8843. };
  8844. Tools.IsEmpty = function (obj) {
  8845. for (var i in obj) {
  8846. if (obj.hasOwnProperty(i)) {
  8847. return false;
  8848. }
  8849. }
  8850. return true;
  8851. };
  8852. Tools.RegisterTopRootEvents = function (events) {
  8853. for (var index = 0; index < events.length; index++) {
  8854. var event = events[index];
  8855. window.addEventListener(event.name, event.handler, false);
  8856. try {
  8857. if (window.parent) {
  8858. window.parent.addEventListener(event.name, event.handler, false);
  8859. }
  8860. }
  8861. catch (e) {
  8862. // Silently fails...
  8863. }
  8864. }
  8865. };
  8866. Tools.UnregisterTopRootEvents = function (events) {
  8867. for (var index = 0; index < events.length; index++) {
  8868. var event = events[index];
  8869. window.removeEventListener(event.name, event.handler);
  8870. try {
  8871. if (window.parent) {
  8872. window.parent.removeEventListener(event.name, event.handler);
  8873. }
  8874. }
  8875. catch (e) {
  8876. // Silently fails...
  8877. }
  8878. }
  8879. };
  8880. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8881. if (mimeType === void 0) { mimeType = "image/png"; }
  8882. // Read the contents of the framebuffer
  8883. var numberOfChannelsByLine = width * 4;
  8884. var halfHeight = height / 2;
  8885. //Reading datas from WebGL
  8886. var data = engine.readPixels(0, 0, width, height);
  8887. //To flip image on Y axis.
  8888. for (var i = 0; i < halfHeight; i++) {
  8889. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8890. var currentCell = j + i * numberOfChannelsByLine;
  8891. var targetLine = height - i - 1;
  8892. var targetCell = j + targetLine * numberOfChannelsByLine;
  8893. var temp = data[currentCell];
  8894. data[currentCell] = data[targetCell];
  8895. data[targetCell] = temp;
  8896. }
  8897. }
  8898. // Create a 2D canvas to store the result
  8899. if (!screenshotCanvas) {
  8900. screenshotCanvas = document.createElement('canvas');
  8901. }
  8902. screenshotCanvas.width = width;
  8903. screenshotCanvas.height = height;
  8904. var context = screenshotCanvas.getContext('2d');
  8905. if (context) {
  8906. // Copy the pixels to a 2D canvas
  8907. var imageData = context.createImageData(width, height);
  8908. var castData = (imageData.data);
  8909. castData.set(data);
  8910. context.putImageData(imageData, 0, 0);
  8911. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8912. }
  8913. };
  8914. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8915. if (mimeType === void 0) { mimeType = "image/png"; }
  8916. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8917. if (successCallback) {
  8918. successCallback(base64Image);
  8919. }
  8920. else {
  8921. // We need HTMLCanvasElement.toBlob for HD screenshots
  8922. if (!screenshotCanvas.toBlob) {
  8923. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8924. screenshotCanvas.toBlob = function (callback, type, quality) {
  8925. var _this = this;
  8926. setTimeout(function () {
  8927. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8928. for (var i = 0; i < len; i++) {
  8929. arr[i] = binStr.charCodeAt(i);
  8930. }
  8931. callback(new Blob([arr], { type: type || 'image/png' }));
  8932. });
  8933. };
  8934. }
  8935. screenshotCanvas.toBlob(function (blob) {
  8936. var url = URL.createObjectURL(blob);
  8937. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8938. if (("download" in document.createElement("a"))) {
  8939. var a = window.document.createElement("a");
  8940. a.href = url;
  8941. if (fileName) {
  8942. a.setAttribute("download", fileName);
  8943. }
  8944. else {
  8945. var date = new Date();
  8946. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8947. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8948. }
  8949. window.document.body.appendChild(a);
  8950. a.addEventListener("click", function () {
  8951. if (a.parentElement) {
  8952. a.parentElement.removeChild(a);
  8953. }
  8954. });
  8955. a.click();
  8956. }
  8957. else {
  8958. var newWindow = window.open("");
  8959. if (!newWindow)
  8960. return;
  8961. var img = newWindow.document.createElement("img");
  8962. img.onload = function () {
  8963. // no longer need to read the blob so it's revoked
  8964. URL.revokeObjectURL(url);
  8965. };
  8966. img.src = url;
  8967. newWindow.document.body.appendChild(img);
  8968. }
  8969. });
  8970. }
  8971. };
  8972. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8973. if (mimeType === void 0) { mimeType = "image/png"; }
  8974. var width;
  8975. var height;
  8976. // If a precision value is specified
  8977. if (size.precision) {
  8978. width = Math.round(engine.getRenderWidth() * size.precision);
  8979. height = Math.round(width / engine.getAspectRatio(camera));
  8980. }
  8981. else if (size.width && size.height) {
  8982. width = size.width;
  8983. height = size.height;
  8984. }
  8985. else if (size.width && !size.height) {
  8986. width = size.width;
  8987. height = Math.round(width / engine.getAspectRatio(camera));
  8988. }
  8989. else if (size.height && !size.width) {
  8990. height = size.height;
  8991. width = Math.round(height * engine.getAspectRatio(camera));
  8992. }
  8993. else if (!isNaN(size)) {
  8994. height = size;
  8995. width = size;
  8996. }
  8997. else {
  8998. Tools.Error("Invalid 'size' parameter !");
  8999. return;
  9000. }
  9001. if (!screenshotCanvas) {
  9002. screenshotCanvas = document.createElement('canvas');
  9003. }
  9004. screenshotCanvas.width = width;
  9005. screenshotCanvas.height = height;
  9006. var renderContext = screenshotCanvas.getContext("2d");
  9007. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9008. var newWidth = width;
  9009. var newHeight = newWidth / ratio;
  9010. if (newHeight > height) {
  9011. newHeight = height;
  9012. newWidth = newHeight * ratio;
  9013. }
  9014. var offsetX = Math.max(0, width - newWidth) / 2;
  9015. var offsetY = Math.max(0, height - newHeight) / 2;
  9016. var renderingCanvas = engine.getRenderingCanvas();
  9017. if (renderContext && renderingCanvas) {
  9018. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9019. }
  9020. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9021. };
  9022. /**
  9023. * Generates an image screenshot from the specified camera.
  9024. *
  9025. * @param engine The engine to use for rendering
  9026. * @param camera The camera to use for rendering
  9027. * @param size This parameter can be set to a single number or to an object with the
  9028. * following (optional) properties: precision, width, height. If a single number is passed,
  9029. * it will be used for both width and height. If an object is passed, the screenshot size
  9030. * will be derived from the parameters. The precision property is a multiplier allowing
  9031. * rendering at a higher or lower resolution.
  9032. * @param successCallback The callback receives a single parameter which contains the
  9033. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9034. * src parameter of an <img> to display it.
  9035. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9036. * Check your browser for supported MIME types.
  9037. * @param samples Texture samples (default: 1)
  9038. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9039. * @param fileName A name for for the downloaded file.
  9040. * @constructor
  9041. */
  9042. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9043. if (mimeType === void 0) { mimeType = "image/png"; }
  9044. if (samples === void 0) { samples = 1; }
  9045. if (antialiasing === void 0) { antialiasing = false; }
  9046. var width;
  9047. var height;
  9048. //If a precision value is specified
  9049. if (size.precision) {
  9050. width = Math.round(engine.getRenderWidth() * size.precision);
  9051. height = Math.round(width / engine.getAspectRatio(camera));
  9052. size = { width: width, height: height };
  9053. }
  9054. else if (size.width && size.height) {
  9055. width = size.width;
  9056. height = size.height;
  9057. }
  9058. else if (size.width && !size.height) {
  9059. width = size.width;
  9060. height = Math.round(width / engine.getAspectRatio(camera));
  9061. size = { width: width, height: height };
  9062. }
  9063. else if (size.height && !size.width) {
  9064. height = size.height;
  9065. width = Math.round(height * engine.getAspectRatio(camera));
  9066. size = { width: width, height: height };
  9067. }
  9068. else if (!isNaN(size)) {
  9069. height = size;
  9070. width = size;
  9071. }
  9072. else {
  9073. Tools.Error("Invalid 'size' parameter !");
  9074. return;
  9075. }
  9076. var scene = camera.getScene();
  9077. var previousCamera = null;
  9078. if (scene.activeCamera !== camera) {
  9079. previousCamera = scene.activeCamera;
  9080. scene.activeCamera = camera;
  9081. }
  9082. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9083. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9084. texture.renderList = null;
  9085. texture.samples = samples;
  9086. if (antialiasing) {
  9087. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9088. }
  9089. texture.onAfterRenderObservable.add(function () {
  9090. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9091. });
  9092. scene.incrementRenderId();
  9093. scene.resetCachedMaterial();
  9094. texture.render(true);
  9095. texture.dispose();
  9096. if (previousCamera) {
  9097. scene.activeCamera = previousCamera;
  9098. }
  9099. camera.getProjectionMatrix(true); // Force cache refresh;
  9100. };
  9101. // XHR response validator for local file scenario
  9102. Tools.ValidateXHRData = function (xhr, dataType) {
  9103. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9104. if (dataType === void 0) { dataType = 7; }
  9105. try {
  9106. if (dataType & 1) {
  9107. if (xhr.responseText && xhr.responseText.length > 0) {
  9108. return true;
  9109. }
  9110. else if (dataType === 1) {
  9111. return false;
  9112. }
  9113. }
  9114. if (dataType & 2) {
  9115. // Check header width and height since there is no "TGA" magic number
  9116. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9117. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9118. return true;
  9119. }
  9120. else if (dataType === 2) {
  9121. return false;
  9122. }
  9123. }
  9124. if (dataType & 4) {
  9125. // Check for the "DDS" magic number
  9126. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9127. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9128. return true;
  9129. }
  9130. else {
  9131. return false;
  9132. }
  9133. }
  9134. }
  9135. catch (e) {
  9136. // Global protection
  9137. }
  9138. return false;
  9139. };
  9140. /**
  9141. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9142. * Be aware Math.random() could cause collisions, but:
  9143. * "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"
  9144. */
  9145. Tools.RandomId = function () {
  9146. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9147. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9148. return v.toString(16);
  9149. });
  9150. };
  9151. /**
  9152. * Test if the given uri is a base64 string.
  9153. * @param uri The uri to test
  9154. * @return True if the uri is a base64 string or false otherwise.
  9155. */
  9156. Tools.IsBase64 = function (uri) {
  9157. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9158. };
  9159. /**
  9160. * Decode the given base64 uri.
  9161. * @param uri The uri to decode
  9162. * @return The decoded base64 data.
  9163. */
  9164. Tools.DecodeBase64 = function (uri) {
  9165. var decodedString = atob(uri.split(",")[1]);
  9166. var bufferLength = decodedString.length;
  9167. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9168. for (var i = 0; i < bufferLength; i++) {
  9169. bufferView[i] = decodedString.charCodeAt(i);
  9170. }
  9171. return bufferView.buffer;
  9172. };
  9173. Object.defineProperty(Tools, "NoneLogLevel", {
  9174. get: function () {
  9175. return Tools._NoneLogLevel;
  9176. },
  9177. enumerable: true,
  9178. configurable: true
  9179. });
  9180. Object.defineProperty(Tools, "MessageLogLevel", {
  9181. get: function () {
  9182. return Tools._MessageLogLevel;
  9183. },
  9184. enumerable: true,
  9185. configurable: true
  9186. });
  9187. Object.defineProperty(Tools, "WarningLogLevel", {
  9188. get: function () {
  9189. return Tools._WarningLogLevel;
  9190. },
  9191. enumerable: true,
  9192. configurable: true
  9193. });
  9194. Object.defineProperty(Tools, "ErrorLogLevel", {
  9195. get: function () {
  9196. return Tools._ErrorLogLevel;
  9197. },
  9198. enumerable: true,
  9199. configurable: true
  9200. });
  9201. Object.defineProperty(Tools, "AllLogLevel", {
  9202. get: function () {
  9203. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9204. },
  9205. enumerable: true,
  9206. configurable: true
  9207. });
  9208. Tools._AddLogEntry = function (entry) {
  9209. Tools._LogCache = entry + Tools._LogCache;
  9210. if (Tools.OnNewCacheEntry) {
  9211. Tools.OnNewCacheEntry(entry);
  9212. }
  9213. };
  9214. Tools._FormatMessage = function (message) {
  9215. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9216. var date = new Date();
  9217. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9218. };
  9219. Tools._LogDisabled = function (message) {
  9220. // nothing to do
  9221. };
  9222. Tools._LogEnabled = function (message) {
  9223. var formattedMessage = Tools._FormatMessage(message);
  9224. console.log("BJS - " + formattedMessage);
  9225. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9226. Tools._AddLogEntry(entry);
  9227. };
  9228. Tools._WarnDisabled = function (message) {
  9229. // nothing to do
  9230. };
  9231. Tools._WarnEnabled = function (message) {
  9232. var formattedMessage = Tools._FormatMessage(message);
  9233. console.warn("BJS - " + formattedMessage);
  9234. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9235. Tools._AddLogEntry(entry);
  9236. };
  9237. Tools._ErrorDisabled = function (message) {
  9238. // nothing to do
  9239. };
  9240. Tools._ErrorEnabled = function (message) {
  9241. Tools.errorsCount++;
  9242. var formattedMessage = Tools._FormatMessage(message);
  9243. console.error("BJS - " + formattedMessage);
  9244. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9245. Tools._AddLogEntry(entry);
  9246. };
  9247. Object.defineProperty(Tools, "LogCache", {
  9248. get: function () {
  9249. return Tools._LogCache;
  9250. },
  9251. enumerable: true,
  9252. configurable: true
  9253. });
  9254. Tools.ClearLogCache = function () {
  9255. Tools._LogCache = "";
  9256. Tools.errorsCount = 0;
  9257. };
  9258. Object.defineProperty(Tools, "LogLevels", {
  9259. set: function (level) {
  9260. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9261. Tools.Log = Tools._LogEnabled;
  9262. }
  9263. else {
  9264. Tools.Log = Tools._LogDisabled;
  9265. }
  9266. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9267. Tools.Warn = Tools._WarnEnabled;
  9268. }
  9269. else {
  9270. Tools.Warn = Tools._WarnDisabled;
  9271. }
  9272. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9273. Tools.Error = Tools._ErrorEnabled;
  9274. }
  9275. else {
  9276. Tools.Error = Tools._ErrorDisabled;
  9277. }
  9278. },
  9279. enumerable: true,
  9280. configurable: true
  9281. });
  9282. Tools.IsWindowObjectExist = function () {
  9283. return (typeof window) !== "undefined";
  9284. };
  9285. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9286. get: function () {
  9287. return Tools._PerformanceNoneLogLevel;
  9288. },
  9289. enumerable: true,
  9290. configurable: true
  9291. });
  9292. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9293. get: function () {
  9294. return Tools._PerformanceUserMarkLogLevel;
  9295. },
  9296. enumerable: true,
  9297. configurable: true
  9298. });
  9299. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9300. get: function () {
  9301. return Tools._PerformanceConsoleLogLevel;
  9302. },
  9303. enumerable: true,
  9304. configurable: true
  9305. });
  9306. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9307. set: function (level) {
  9308. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9309. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9310. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9311. return;
  9312. }
  9313. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9314. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9315. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9316. return;
  9317. }
  9318. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9319. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9320. },
  9321. enumerable: true,
  9322. configurable: true
  9323. });
  9324. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9325. };
  9326. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9327. };
  9328. Tools._StartUserMark = function (counterName, condition) {
  9329. if (condition === void 0) { condition = true; }
  9330. if (!Tools._performance) {
  9331. if (!Tools.IsWindowObjectExist()) {
  9332. return;
  9333. }
  9334. Tools._performance = window.performance;
  9335. }
  9336. if (!condition || !Tools._performance.mark) {
  9337. return;
  9338. }
  9339. Tools._performance.mark(counterName + "-Begin");
  9340. };
  9341. Tools._EndUserMark = function (counterName, condition) {
  9342. if (condition === void 0) { condition = true; }
  9343. if (!condition || !Tools._performance.mark) {
  9344. return;
  9345. }
  9346. Tools._performance.mark(counterName + "-End");
  9347. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9348. };
  9349. Tools._StartPerformanceConsole = function (counterName, condition) {
  9350. if (condition === void 0) { condition = true; }
  9351. if (!condition) {
  9352. return;
  9353. }
  9354. Tools._StartUserMark(counterName, condition);
  9355. if (console.time) {
  9356. console.time(counterName);
  9357. }
  9358. };
  9359. Tools._EndPerformanceConsole = function (counterName, condition) {
  9360. if (condition === void 0) { condition = true; }
  9361. if (!condition) {
  9362. return;
  9363. }
  9364. Tools._EndUserMark(counterName, condition);
  9365. if (console.time) {
  9366. console.timeEnd(counterName);
  9367. }
  9368. };
  9369. Object.defineProperty(Tools, "Now", {
  9370. get: function () {
  9371. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9372. return window.performance.now();
  9373. }
  9374. return new Date().getTime();
  9375. },
  9376. enumerable: true,
  9377. configurable: true
  9378. });
  9379. /**
  9380. * This method will return the name of the class used to create the instance of the given object.
  9381. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9382. * @param object the object to get the class name from
  9383. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9384. */
  9385. Tools.GetClassName = function (object, isType) {
  9386. if (isType === void 0) { isType = false; }
  9387. var name = null;
  9388. if (!isType && object.getClassName) {
  9389. name = object.getClassName();
  9390. }
  9391. else {
  9392. if (object instanceof Object) {
  9393. var classObj = isType ? object : Object.getPrototypeOf(object);
  9394. name = classObj.constructor["__bjsclassName__"];
  9395. }
  9396. if (!name) {
  9397. name = typeof object;
  9398. }
  9399. }
  9400. return name;
  9401. };
  9402. Tools.First = function (array, predicate) {
  9403. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9404. var el = array_1[_i];
  9405. if (predicate(el)) {
  9406. return el;
  9407. }
  9408. }
  9409. return null;
  9410. };
  9411. /**
  9412. * This method will return the name of the full name of the class, including its owning module (if any).
  9413. * 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).
  9414. * @param object the object to get the class name from
  9415. * @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.
  9416. */
  9417. Tools.getFullClassName = function (object, isType) {
  9418. if (isType === void 0) { isType = false; }
  9419. var className = null;
  9420. var moduleName = null;
  9421. if (!isType && object.getClassName) {
  9422. className = object.getClassName();
  9423. }
  9424. else {
  9425. if (object instanceof Object) {
  9426. var classObj = isType ? object : Object.getPrototypeOf(object);
  9427. className = classObj.constructor["__bjsclassName__"];
  9428. moduleName = classObj.constructor["__bjsmoduleName__"];
  9429. }
  9430. if (!className) {
  9431. className = typeof object;
  9432. }
  9433. }
  9434. if (!className) {
  9435. return null;
  9436. }
  9437. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9438. };
  9439. /**
  9440. * 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.
  9441. * @param array
  9442. */
  9443. Tools.arrayOrStringFeeder = function (array) {
  9444. return function (index) {
  9445. if (index >= array.length) {
  9446. return null;
  9447. }
  9448. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9449. if (val && val.getHashCode) {
  9450. val = val.getHashCode();
  9451. }
  9452. if (typeof val === "string") {
  9453. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9454. }
  9455. return val;
  9456. };
  9457. };
  9458. /**
  9459. * Compute the hashCode of a stream of number
  9460. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9461. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9462. * @return the hash code computed
  9463. */
  9464. Tools.hashCodeFromStream = function (feeder) {
  9465. // Based from here: http://stackoverflow.com/a/7616484/802124
  9466. var hash = 0;
  9467. var index = 0;
  9468. var chr = feeder(index++);
  9469. while (chr != null) {
  9470. hash = ((hash << 5) - hash) + chr;
  9471. hash |= 0; // Convert to 32bit integer
  9472. chr = feeder(index++);
  9473. }
  9474. return hash;
  9475. };
  9476. /**
  9477. * Returns a promise that resolves after the given amount of time.
  9478. * @param delay Number of milliseconds to delay
  9479. * @returns Promise that resolves after the given amount of time
  9480. */
  9481. Tools.DelayAsync = function (delay) {
  9482. return new Promise(function (resolve) {
  9483. setTimeout(function () {
  9484. resolve();
  9485. }, delay);
  9486. });
  9487. };
  9488. Tools.BaseUrl = "";
  9489. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9490. /**
  9491. * Default behaviour for cors in the application.
  9492. * It can be a string if the expected behavior is identical in the entire app.
  9493. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9494. */
  9495. Tools.CorsBehavior = "anonymous";
  9496. Tools.UseFallbackTexture = true;
  9497. /**
  9498. * Use this object to register external classes like custom textures or material
  9499. * to allow the laoders to instantiate them
  9500. */
  9501. Tools.RegisteredExternalClasses = {};
  9502. // Used in case of a texture loading problem
  9503. 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";
  9504. Tools.PreprocessUrl = function (url) {
  9505. return url;
  9506. };
  9507. // Logs
  9508. Tools._NoneLogLevel = 0;
  9509. Tools._MessageLogLevel = 1;
  9510. Tools._WarningLogLevel = 2;
  9511. Tools._ErrorLogLevel = 4;
  9512. Tools._LogCache = "";
  9513. Tools.errorsCount = 0;
  9514. Tools.Log = Tools._LogEnabled;
  9515. Tools.Warn = Tools._WarnEnabled;
  9516. Tools.Error = Tools._ErrorEnabled;
  9517. // Performances
  9518. Tools._PerformanceNoneLogLevel = 0;
  9519. Tools._PerformanceUserMarkLogLevel = 1;
  9520. Tools._PerformanceConsoleLogLevel = 2;
  9521. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9522. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9523. return Tools;
  9524. }());
  9525. BABYLON.Tools = Tools;
  9526. /**
  9527. * This class is used to track a performance counter which is number based.
  9528. * The user has access to many properties which give statistics of different nature
  9529. *
  9530. * The implementer can track two kinds of Performance Counter: time and count
  9531. * 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.
  9532. * 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.
  9533. */
  9534. var PerfCounter = /** @class */ (function () {
  9535. function PerfCounter() {
  9536. this._startMonitoringTime = 0;
  9537. this._min = 0;
  9538. this._max = 0;
  9539. this._average = 0;
  9540. this._lastSecAverage = 0;
  9541. this._current = 0;
  9542. this._totalValueCount = 0;
  9543. this._totalAccumulated = 0;
  9544. this._lastSecAccumulated = 0;
  9545. this._lastSecTime = 0;
  9546. this._lastSecValueCount = 0;
  9547. }
  9548. Object.defineProperty(PerfCounter.prototype, "min", {
  9549. /**
  9550. * Returns the smallest value ever
  9551. */
  9552. get: function () {
  9553. return this._min;
  9554. },
  9555. enumerable: true,
  9556. configurable: true
  9557. });
  9558. Object.defineProperty(PerfCounter.prototype, "max", {
  9559. /**
  9560. * Returns the biggest value ever
  9561. */
  9562. get: function () {
  9563. return this._max;
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. Object.defineProperty(PerfCounter.prototype, "average", {
  9569. /**
  9570. * Returns the average value since the performance counter is running
  9571. */
  9572. get: function () {
  9573. return this._average;
  9574. },
  9575. enumerable: true,
  9576. configurable: true
  9577. });
  9578. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9579. /**
  9580. * Returns the average value of the last second the counter was monitored
  9581. */
  9582. get: function () {
  9583. return this._lastSecAverage;
  9584. },
  9585. enumerable: true,
  9586. configurable: true
  9587. });
  9588. Object.defineProperty(PerfCounter.prototype, "current", {
  9589. /**
  9590. * Returns the current value
  9591. */
  9592. get: function () {
  9593. return this._current;
  9594. },
  9595. enumerable: true,
  9596. configurable: true
  9597. });
  9598. Object.defineProperty(PerfCounter.prototype, "total", {
  9599. get: function () {
  9600. return this._totalAccumulated;
  9601. },
  9602. enumerable: true,
  9603. configurable: true
  9604. });
  9605. Object.defineProperty(PerfCounter.prototype, "count", {
  9606. get: function () {
  9607. return this._totalValueCount;
  9608. },
  9609. enumerable: true,
  9610. configurable: true
  9611. });
  9612. /**
  9613. * Call this method to start monitoring a new frame.
  9614. * 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.
  9615. */
  9616. PerfCounter.prototype.fetchNewFrame = function () {
  9617. this._totalValueCount++;
  9618. this._current = 0;
  9619. this._lastSecValueCount++;
  9620. };
  9621. /**
  9622. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9623. * @param newCount the count value to add to the monitored count
  9624. * @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.
  9625. */
  9626. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9627. if (!PerfCounter.Enabled) {
  9628. return;
  9629. }
  9630. this._current += newCount;
  9631. if (fetchResult) {
  9632. this._fetchResult();
  9633. }
  9634. };
  9635. /**
  9636. * Start monitoring this performance counter
  9637. */
  9638. PerfCounter.prototype.beginMonitoring = function () {
  9639. if (!PerfCounter.Enabled) {
  9640. return;
  9641. }
  9642. this._startMonitoringTime = Tools.Now;
  9643. };
  9644. /**
  9645. * Compute the time lapsed since the previous beginMonitoring() call.
  9646. * @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
  9647. */
  9648. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9649. if (newFrame === void 0) { newFrame = true; }
  9650. if (!PerfCounter.Enabled) {
  9651. return;
  9652. }
  9653. if (newFrame) {
  9654. this.fetchNewFrame();
  9655. }
  9656. var currentTime = Tools.Now;
  9657. this._current = currentTime - this._startMonitoringTime;
  9658. if (newFrame) {
  9659. this._fetchResult();
  9660. }
  9661. };
  9662. PerfCounter.prototype._fetchResult = function () {
  9663. this._totalAccumulated += this._current;
  9664. this._lastSecAccumulated += this._current;
  9665. // Min/Max update
  9666. this._min = Math.min(this._min, this._current);
  9667. this._max = Math.max(this._max, this._current);
  9668. this._average = this._totalAccumulated / this._totalValueCount;
  9669. // Reset last sec?
  9670. var now = Tools.Now;
  9671. if ((now - this._lastSecTime) > 1000) {
  9672. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9673. this._lastSecTime = now;
  9674. this._lastSecAccumulated = 0;
  9675. this._lastSecValueCount = 0;
  9676. }
  9677. };
  9678. PerfCounter.Enabled = true;
  9679. return PerfCounter;
  9680. }());
  9681. BABYLON.PerfCounter = PerfCounter;
  9682. /**
  9683. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9684. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9685. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9686. * @param name The name of the class, case should be preserved
  9687. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9688. */
  9689. function className(name, module) {
  9690. return function (target) {
  9691. target["__bjsclassName__"] = name;
  9692. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9693. };
  9694. }
  9695. BABYLON.className = className;
  9696. /**
  9697. * An implementation of a loop for asynchronous functions.
  9698. */
  9699. var AsyncLoop = /** @class */ (function () {
  9700. /**
  9701. * Constroctor.
  9702. * @param iterations the number of iterations.
  9703. * @param _fn the function to run each iteration
  9704. * @param _successCallback the callback that will be called upon succesful execution
  9705. * @param offset starting offset.
  9706. */
  9707. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9708. if (offset === void 0) { offset = 0; }
  9709. this.iterations = iterations;
  9710. this._fn = _fn;
  9711. this._successCallback = _successCallback;
  9712. this.index = offset - 1;
  9713. this._done = false;
  9714. }
  9715. /**
  9716. * Execute the next iteration. Must be called after the last iteration was finished.
  9717. */
  9718. AsyncLoop.prototype.executeNext = function () {
  9719. if (!this._done) {
  9720. if (this.index + 1 < this.iterations) {
  9721. ++this.index;
  9722. this._fn(this);
  9723. }
  9724. else {
  9725. this.breakLoop();
  9726. }
  9727. }
  9728. };
  9729. /**
  9730. * Break the loop and run the success callback.
  9731. */
  9732. AsyncLoop.prototype.breakLoop = function () {
  9733. this._done = true;
  9734. this._successCallback();
  9735. };
  9736. /**
  9737. * Helper function
  9738. */
  9739. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9740. if (offset === void 0) { offset = 0; }
  9741. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9742. loop.executeNext();
  9743. return loop;
  9744. };
  9745. /**
  9746. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9747. * @param iterations total number of iterations
  9748. * @param syncedIterations number of synchronous iterations in each async iteration.
  9749. * @param fn the function to call each iteration.
  9750. * @param callback a success call back that will be called when iterating stops.
  9751. * @param breakFunction a break condition (optional)
  9752. * @param timeout timeout settings for the setTimeout function. default - 0.
  9753. * @constructor
  9754. */
  9755. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9756. if (timeout === void 0) { timeout = 0; }
  9757. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9758. if (breakFunction && breakFunction())
  9759. loop.breakLoop();
  9760. else {
  9761. setTimeout(function () {
  9762. for (var i = 0; i < syncedIterations; ++i) {
  9763. var iteration = (loop.index * syncedIterations) + i;
  9764. if (iteration >= iterations)
  9765. break;
  9766. fn(iteration);
  9767. if (breakFunction && breakFunction()) {
  9768. loop.breakLoop();
  9769. break;
  9770. }
  9771. }
  9772. loop.executeNext();
  9773. }, timeout);
  9774. }
  9775. }, callback);
  9776. };
  9777. return AsyncLoop;
  9778. }());
  9779. BABYLON.AsyncLoop = AsyncLoop;
  9780. })(BABYLON || (BABYLON = {}));
  9781. //# sourceMappingURL=babylon.tools.js.map
  9782. "use strict";
  9783. var BABYLON;
  9784. (function (BABYLON) {
  9785. var PromiseStates;
  9786. (function (PromiseStates) {
  9787. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9788. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9789. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9790. })(PromiseStates || (PromiseStates = {}));
  9791. var FulFillmentAgregator = /** @class */ (function () {
  9792. function FulFillmentAgregator() {
  9793. this.count = 0;
  9794. this.target = 0;
  9795. this.results = [];
  9796. }
  9797. return FulFillmentAgregator;
  9798. }());
  9799. var InternalPromise = /** @class */ (function () {
  9800. function InternalPromise(resolver) {
  9801. var _this = this;
  9802. this._state = PromiseStates.Pending;
  9803. this._children = new Array();
  9804. this._rejectWasConsumed = false;
  9805. if (!resolver) {
  9806. return;
  9807. }
  9808. try {
  9809. resolver(function (value) {
  9810. _this._resolve(value);
  9811. }, function (reason) {
  9812. _this._reject(reason);
  9813. });
  9814. }
  9815. catch (e) {
  9816. this._reject(e);
  9817. }
  9818. }
  9819. InternalPromise.prototype.catch = function (onRejected) {
  9820. return this.then(undefined, onRejected);
  9821. };
  9822. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9823. var _this = this;
  9824. var newPromise = new InternalPromise();
  9825. newPromise._onFulfilled = onFulfilled;
  9826. newPromise._onRejected = onRejected;
  9827. // Composition
  9828. this._children.push(newPromise);
  9829. if (this._state !== PromiseStates.Pending) {
  9830. BABYLON.Tools.SetImmediate(function () {
  9831. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9832. var returnedValue = newPromise._resolve(_this._result);
  9833. if (returnedValue !== undefined && returnedValue !== null) {
  9834. if (returnedValue._state !== undefined) {
  9835. var returnedPromise = returnedValue;
  9836. newPromise._children.push(returnedPromise);
  9837. newPromise = returnedPromise;
  9838. }
  9839. else {
  9840. newPromise._result = returnedValue;
  9841. }
  9842. }
  9843. }
  9844. else {
  9845. newPromise._reject(_this._reason);
  9846. }
  9847. });
  9848. }
  9849. return newPromise;
  9850. };
  9851. InternalPromise.prototype._moveChildren = function (children) {
  9852. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9853. if (this._state === PromiseStates.Fulfilled) {
  9854. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9855. var child = _b[_i];
  9856. child._resolve(this._result);
  9857. }
  9858. }
  9859. else if (this._state === PromiseStates.Rejected) {
  9860. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9861. var child = _d[_c];
  9862. child._reject(this._reason);
  9863. }
  9864. }
  9865. var _a;
  9866. };
  9867. InternalPromise.prototype._resolve = function (value) {
  9868. try {
  9869. this._state = PromiseStates.Fulfilled;
  9870. var returnedValue = null;
  9871. if (this._onFulfilled) {
  9872. returnedValue = this._onFulfilled(value);
  9873. }
  9874. if (returnedValue !== undefined && returnedValue !== null) {
  9875. if (returnedValue._state !== undefined) {
  9876. // Transmit children
  9877. var returnedPromise = returnedValue;
  9878. returnedPromise._moveChildren(this._children);
  9879. value = returnedPromise._result;
  9880. }
  9881. else {
  9882. value = returnedValue;
  9883. }
  9884. }
  9885. this._result = value;
  9886. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9887. var child = _a[_i];
  9888. child._resolve(value);
  9889. }
  9890. this._children.length = 0;
  9891. delete this._onFulfilled;
  9892. delete this._onRejected;
  9893. }
  9894. catch (e) {
  9895. this._reject(e, true);
  9896. }
  9897. };
  9898. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9899. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9900. this._state = PromiseStates.Rejected;
  9901. this._reason = reason;
  9902. if (this._onRejected && !onLocalThrow) {
  9903. try {
  9904. this._onRejected(reason);
  9905. this._rejectWasConsumed = true;
  9906. }
  9907. catch (e) {
  9908. reason = e;
  9909. }
  9910. }
  9911. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9912. var child = _a[_i];
  9913. if (this._rejectWasConsumed) {
  9914. child._resolve(null);
  9915. }
  9916. else {
  9917. child._reject(reason);
  9918. }
  9919. }
  9920. this._children.length = 0;
  9921. delete this._onFulfilled;
  9922. delete this._onRejected;
  9923. };
  9924. InternalPromise.resolve = function (value) {
  9925. var newPromise = new InternalPromise();
  9926. newPromise._resolve(value);
  9927. return newPromise;
  9928. };
  9929. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9930. promise.then(function (value) {
  9931. agregator.results[index] = value;
  9932. agregator.count++;
  9933. if (agregator.count === agregator.target) {
  9934. agregator.rootPromise._resolve(agregator.results);
  9935. }
  9936. return null;
  9937. }, function (reason) {
  9938. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9939. agregator.rootPromise._reject(reason);
  9940. }
  9941. });
  9942. };
  9943. InternalPromise.all = function (promises) {
  9944. var newPromise = new InternalPromise();
  9945. var agregator = new FulFillmentAgregator();
  9946. agregator.target = promises.length;
  9947. agregator.rootPromise = newPromise;
  9948. if (promises.length) {
  9949. for (var index = 0; index < promises.length; index++) {
  9950. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9951. }
  9952. }
  9953. else {
  9954. newPromise._resolve([]);
  9955. }
  9956. return newPromise;
  9957. };
  9958. InternalPromise.race = function (promises) {
  9959. var newPromise = new InternalPromise();
  9960. if (promises.length) {
  9961. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9962. var promise = promises_1[_i];
  9963. promise.then(function (value) {
  9964. if (newPromise) {
  9965. newPromise._resolve(value);
  9966. newPromise = null;
  9967. }
  9968. return null;
  9969. }, function (reason) {
  9970. if (newPromise) {
  9971. newPromise._reject(reason);
  9972. newPromise = null;
  9973. }
  9974. });
  9975. }
  9976. }
  9977. return newPromise;
  9978. };
  9979. return InternalPromise;
  9980. }());
  9981. /**
  9982. * Helper class that provides a small promise polyfill
  9983. */
  9984. var PromisePolyfill = /** @class */ (function () {
  9985. function PromisePolyfill() {
  9986. }
  9987. /**
  9988. * Static function used to check if the polyfill is required
  9989. * If this is the case then the function will inject the polyfill to window.Promise
  9990. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9991. */
  9992. PromisePolyfill.Apply = function (force) {
  9993. if (force === void 0) { force = false; }
  9994. if (force || typeof Promise === 'undefined') {
  9995. var root = window;
  9996. root.Promise = InternalPromise;
  9997. }
  9998. };
  9999. return PromisePolyfill;
  10000. }());
  10001. BABYLON.PromisePolyfill = PromisePolyfill;
  10002. })(BABYLON || (BABYLON = {}));
  10003. //# sourceMappingURL=babylon.promise.js.map
  10004. "use strict";
  10005. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10006. var BABYLON;
  10007. (function (BABYLON) {
  10008. /**
  10009. * Helper class to push actions to a pool of workers.
  10010. */
  10011. var WorkerPool = /** @class */ (function () {
  10012. /**
  10013. * Constructor
  10014. * @param workers Array of workers to use for actions
  10015. */
  10016. function WorkerPool(workers) {
  10017. this._pendingActions = new Array();
  10018. this._workerInfos = workers.map(function (worker) { return ({
  10019. worker: worker,
  10020. active: false
  10021. }); });
  10022. }
  10023. /**
  10024. * Terminates all workers and clears any pending actions.
  10025. */
  10026. WorkerPool.prototype.dispose = function () {
  10027. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10028. var workerInfo = _a[_i];
  10029. workerInfo.worker.terminate();
  10030. }
  10031. delete this._workerInfos;
  10032. delete this._pendingActions;
  10033. };
  10034. /**
  10035. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10036. * pended until a worker has completed its action.
  10037. * @param action The action to perform. Call onComplete when the action is complete.
  10038. */
  10039. WorkerPool.prototype.push = function (action) {
  10040. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10041. var workerInfo = _a[_i];
  10042. if (!workerInfo.active) {
  10043. this._execute(workerInfo, action);
  10044. return;
  10045. }
  10046. }
  10047. this._pendingActions.push(action);
  10048. };
  10049. WorkerPool.prototype._execute = function (workerInfo, action) {
  10050. var _this = this;
  10051. workerInfo.active = true;
  10052. action(workerInfo.worker, function () {
  10053. workerInfo.active = false;
  10054. var nextAction = _this._pendingActions.shift();
  10055. if (nextAction) {
  10056. _this._execute(workerInfo, nextAction);
  10057. }
  10058. });
  10059. };
  10060. return WorkerPool;
  10061. }());
  10062. BABYLON.WorkerPool = WorkerPool;
  10063. })(BABYLON || (BABYLON = {}));
  10064. //# sourceMappingURL=babylon.workerPool.js.map
  10065. "use strict";
  10066. var BABYLON;
  10067. (function (BABYLON) {
  10068. var _AlphaState = /** @class */ (function () {
  10069. /**
  10070. * Initializes the state.
  10071. */
  10072. function _AlphaState() {
  10073. this._isAlphaBlendDirty = false;
  10074. this._isBlendFunctionParametersDirty = false;
  10075. this._isBlendEquationParametersDirty = false;
  10076. this._isBlendConstantsDirty = false;
  10077. this._alphaBlend = false;
  10078. this._blendFunctionParameters = new Array(4);
  10079. this._blendEquationParameters = new Array(2);
  10080. this._blendConstants = new Array(4);
  10081. this.reset();
  10082. }
  10083. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10084. get: function () {
  10085. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10086. },
  10087. enumerable: true,
  10088. configurable: true
  10089. });
  10090. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10091. get: function () {
  10092. return this._alphaBlend;
  10093. },
  10094. set: function (value) {
  10095. if (this._alphaBlend === value) {
  10096. return;
  10097. }
  10098. this._alphaBlend = value;
  10099. this._isAlphaBlendDirty = true;
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10105. if (this._blendConstants[0] === r &&
  10106. this._blendConstants[1] === g &&
  10107. this._blendConstants[2] === b &&
  10108. this._blendConstants[3] === a) {
  10109. return;
  10110. }
  10111. this._blendConstants[0] = r;
  10112. this._blendConstants[1] = g;
  10113. this._blendConstants[2] = b;
  10114. this._blendConstants[3] = a;
  10115. this._isBlendConstantsDirty = true;
  10116. };
  10117. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10118. if (this._blendFunctionParameters[0] === value0 &&
  10119. this._blendFunctionParameters[1] === value1 &&
  10120. this._blendFunctionParameters[2] === value2 &&
  10121. this._blendFunctionParameters[3] === value3) {
  10122. return;
  10123. }
  10124. this._blendFunctionParameters[0] = value0;
  10125. this._blendFunctionParameters[1] = value1;
  10126. this._blendFunctionParameters[2] = value2;
  10127. this._blendFunctionParameters[3] = value3;
  10128. this._isBlendFunctionParametersDirty = true;
  10129. };
  10130. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10131. if (this._blendEquationParameters[0] === rgb &&
  10132. this._blendEquationParameters[1] === alpha) {
  10133. return;
  10134. }
  10135. this._blendEquationParameters[0] = rgb;
  10136. this._blendEquationParameters[1] = alpha;
  10137. this._isBlendEquationParametersDirty = true;
  10138. };
  10139. _AlphaState.prototype.reset = function () {
  10140. this._alphaBlend = false;
  10141. this._blendFunctionParameters[0] = null;
  10142. this._blendFunctionParameters[1] = null;
  10143. this._blendFunctionParameters[2] = null;
  10144. this._blendFunctionParameters[3] = null;
  10145. this._blendEquationParameters[0] = null;
  10146. this._blendEquationParameters[1] = null;
  10147. this._blendConstants[0] = null;
  10148. this._blendConstants[1] = null;
  10149. this._blendConstants[2] = null;
  10150. this._blendConstants[3] = null;
  10151. this._isAlphaBlendDirty = true;
  10152. this._isBlendFunctionParametersDirty = false;
  10153. this._isBlendEquationParametersDirty = false;
  10154. this._isBlendConstantsDirty = false;
  10155. };
  10156. _AlphaState.prototype.apply = function (gl) {
  10157. if (!this.isDirty) {
  10158. return;
  10159. }
  10160. // Alpha blend
  10161. if (this._isAlphaBlendDirty) {
  10162. if (this._alphaBlend) {
  10163. gl.enable(gl.BLEND);
  10164. }
  10165. else {
  10166. gl.disable(gl.BLEND);
  10167. }
  10168. this._isAlphaBlendDirty = false;
  10169. }
  10170. // Alpha function
  10171. if (this._isBlendFunctionParametersDirty) {
  10172. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10173. this._isBlendFunctionParametersDirty = false;
  10174. }
  10175. // Alpha equation
  10176. if (this._isBlendEquationParametersDirty) {
  10177. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10178. this._isBlendEquationParametersDirty = false;
  10179. }
  10180. // Constants
  10181. if (this._isBlendConstantsDirty) {
  10182. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10183. this._isBlendConstantsDirty = false;
  10184. }
  10185. };
  10186. return _AlphaState;
  10187. }());
  10188. BABYLON._AlphaState = _AlphaState;
  10189. })(BABYLON || (BABYLON = {}));
  10190. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10191. "use strict";
  10192. var BABYLON;
  10193. (function (BABYLON) {
  10194. var _DepthCullingState = /** @class */ (function () {
  10195. /**
  10196. * Initializes the state.
  10197. */
  10198. function _DepthCullingState() {
  10199. this._isDepthTestDirty = false;
  10200. this._isDepthMaskDirty = false;
  10201. this._isDepthFuncDirty = false;
  10202. this._isCullFaceDirty = false;
  10203. this._isCullDirty = false;
  10204. this._isZOffsetDirty = false;
  10205. this._isFrontFaceDirty = false;
  10206. this.reset();
  10207. }
  10208. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10209. get: function () {
  10210. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10211. },
  10212. enumerable: true,
  10213. configurable: true
  10214. });
  10215. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10216. get: function () {
  10217. return this._zOffset;
  10218. },
  10219. set: function (value) {
  10220. if (this._zOffset === value) {
  10221. return;
  10222. }
  10223. this._zOffset = value;
  10224. this._isZOffsetDirty = true;
  10225. },
  10226. enumerable: true,
  10227. configurable: true
  10228. });
  10229. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10230. get: function () {
  10231. return this._cullFace;
  10232. },
  10233. set: function (value) {
  10234. if (this._cullFace === value) {
  10235. return;
  10236. }
  10237. this._cullFace = value;
  10238. this._isCullFaceDirty = true;
  10239. },
  10240. enumerable: true,
  10241. configurable: true
  10242. });
  10243. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10244. get: function () {
  10245. return this._cull;
  10246. },
  10247. set: function (value) {
  10248. if (this._cull === value) {
  10249. return;
  10250. }
  10251. this._cull = value;
  10252. this._isCullDirty = true;
  10253. },
  10254. enumerable: true,
  10255. configurable: true
  10256. });
  10257. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10258. get: function () {
  10259. return this._depthFunc;
  10260. },
  10261. set: function (value) {
  10262. if (this._depthFunc === value) {
  10263. return;
  10264. }
  10265. this._depthFunc = value;
  10266. this._isDepthFuncDirty = true;
  10267. },
  10268. enumerable: true,
  10269. configurable: true
  10270. });
  10271. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10272. get: function () {
  10273. return this._depthMask;
  10274. },
  10275. set: function (value) {
  10276. if (this._depthMask === value) {
  10277. return;
  10278. }
  10279. this._depthMask = value;
  10280. this._isDepthMaskDirty = true;
  10281. },
  10282. enumerable: true,
  10283. configurable: true
  10284. });
  10285. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10286. get: function () {
  10287. return this._depthTest;
  10288. },
  10289. set: function (value) {
  10290. if (this._depthTest === value) {
  10291. return;
  10292. }
  10293. this._depthTest = value;
  10294. this._isDepthTestDirty = true;
  10295. },
  10296. enumerable: true,
  10297. configurable: true
  10298. });
  10299. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10300. get: function () {
  10301. return this._frontFace;
  10302. },
  10303. set: function (value) {
  10304. if (this._frontFace === value) {
  10305. return;
  10306. }
  10307. this._frontFace = value;
  10308. this._isFrontFaceDirty = true;
  10309. },
  10310. enumerable: true,
  10311. configurable: true
  10312. });
  10313. _DepthCullingState.prototype.reset = function () {
  10314. this._depthMask = true;
  10315. this._depthTest = true;
  10316. this._depthFunc = null;
  10317. this._cullFace = null;
  10318. this._cull = null;
  10319. this._zOffset = 0;
  10320. this._frontFace = null;
  10321. this._isDepthTestDirty = true;
  10322. this._isDepthMaskDirty = true;
  10323. this._isDepthFuncDirty = false;
  10324. this._isCullFaceDirty = false;
  10325. this._isCullDirty = false;
  10326. this._isZOffsetDirty = false;
  10327. this._isFrontFaceDirty = false;
  10328. };
  10329. _DepthCullingState.prototype.apply = function (gl) {
  10330. if (!this.isDirty) {
  10331. return;
  10332. }
  10333. // Cull
  10334. if (this._isCullDirty) {
  10335. if (this.cull) {
  10336. gl.enable(gl.CULL_FACE);
  10337. }
  10338. else {
  10339. gl.disable(gl.CULL_FACE);
  10340. }
  10341. this._isCullDirty = false;
  10342. }
  10343. // Cull face
  10344. if (this._isCullFaceDirty) {
  10345. gl.cullFace(this.cullFace);
  10346. this._isCullFaceDirty = false;
  10347. }
  10348. // Depth mask
  10349. if (this._isDepthMaskDirty) {
  10350. gl.depthMask(this.depthMask);
  10351. this._isDepthMaskDirty = false;
  10352. }
  10353. // Depth test
  10354. if (this._isDepthTestDirty) {
  10355. if (this.depthTest) {
  10356. gl.enable(gl.DEPTH_TEST);
  10357. }
  10358. else {
  10359. gl.disable(gl.DEPTH_TEST);
  10360. }
  10361. this._isDepthTestDirty = false;
  10362. }
  10363. // Depth func
  10364. if (this._isDepthFuncDirty) {
  10365. gl.depthFunc(this.depthFunc);
  10366. this._isDepthFuncDirty = false;
  10367. }
  10368. // zOffset
  10369. if (this._isZOffsetDirty) {
  10370. if (this.zOffset) {
  10371. gl.enable(gl.POLYGON_OFFSET_FILL);
  10372. gl.polygonOffset(this.zOffset, 0);
  10373. }
  10374. else {
  10375. gl.disable(gl.POLYGON_OFFSET_FILL);
  10376. }
  10377. this._isZOffsetDirty = false;
  10378. }
  10379. // Front face
  10380. if (this._isFrontFaceDirty) {
  10381. gl.frontFace(this.frontFace);
  10382. this._isFrontFaceDirty = false;
  10383. }
  10384. };
  10385. return _DepthCullingState;
  10386. }());
  10387. BABYLON._DepthCullingState = _DepthCullingState;
  10388. })(BABYLON || (BABYLON = {}));
  10389. //# sourceMappingURL=babylon.depthCullingState.js.map
  10390. "use strict";
  10391. var BABYLON;
  10392. (function (BABYLON) {
  10393. var _StencilState = /** @class */ (function () {
  10394. function _StencilState() {
  10395. this._isStencilTestDirty = false;
  10396. this._isStencilMaskDirty = false;
  10397. this._isStencilFuncDirty = false;
  10398. this._isStencilOpDirty = false;
  10399. this.reset();
  10400. }
  10401. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10402. get: function () {
  10403. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10404. },
  10405. enumerable: true,
  10406. configurable: true
  10407. });
  10408. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10409. get: function () {
  10410. return this._stencilFunc;
  10411. },
  10412. set: function (value) {
  10413. if (this._stencilFunc === value) {
  10414. return;
  10415. }
  10416. this._stencilFunc = value;
  10417. this._isStencilFuncDirty = true;
  10418. },
  10419. enumerable: true,
  10420. configurable: true
  10421. });
  10422. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10423. get: function () {
  10424. return this._stencilFuncRef;
  10425. },
  10426. set: function (value) {
  10427. if (this._stencilFuncRef === value) {
  10428. return;
  10429. }
  10430. this._stencilFuncRef = value;
  10431. this._isStencilFuncDirty = true;
  10432. },
  10433. enumerable: true,
  10434. configurable: true
  10435. });
  10436. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10437. get: function () {
  10438. return this._stencilFuncMask;
  10439. },
  10440. set: function (value) {
  10441. if (this._stencilFuncMask === value) {
  10442. return;
  10443. }
  10444. this._stencilFuncMask = value;
  10445. this._isStencilFuncDirty = true;
  10446. },
  10447. enumerable: true,
  10448. configurable: true
  10449. });
  10450. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10451. get: function () {
  10452. return this._stencilOpStencilFail;
  10453. },
  10454. set: function (value) {
  10455. if (this._stencilOpStencilFail === value) {
  10456. return;
  10457. }
  10458. this._stencilOpStencilFail = value;
  10459. this._isStencilOpDirty = true;
  10460. },
  10461. enumerable: true,
  10462. configurable: true
  10463. });
  10464. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10465. get: function () {
  10466. return this._stencilOpDepthFail;
  10467. },
  10468. set: function (value) {
  10469. if (this._stencilOpDepthFail === value) {
  10470. return;
  10471. }
  10472. this._stencilOpDepthFail = value;
  10473. this._isStencilOpDirty = true;
  10474. },
  10475. enumerable: true,
  10476. configurable: true
  10477. });
  10478. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10479. get: function () {
  10480. return this._stencilOpStencilDepthPass;
  10481. },
  10482. set: function (value) {
  10483. if (this._stencilOpStencilDepthPass === value) {
  10484. return;
  10485. }
  10486. this._stencilOpStencilDepthPass = value;
  10487. this._isStencilOpDirty = true;
  10488. },
  10489. enumerable: true,
  10490. configurable: true
  10491. });
  10492. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10493. get: function () {
  10494. return this._stencilMask;
  10495. },
  10496. set: function (value) {
  10497. if (this._stencilMask === value) {
  10498. return;
  10499. }
  10500. this._stencilMask = value;
  10501. this._isStencilMaskDirty = true;
  10502. },
  10503. enumerable: true,
  10504. configurable: true
  10505. });
  10506. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10507. get: function () {
  10508. return this._stencilTest;
  10509. },
  10510. set: function (value) {
  10511. if (this._stencilTest === value) {
  10512. return;
  10513. }
  10514. this._stencilTest = value;
  10515. this._isStencilTestDirty = true;
  10516. },
  10517. enumerable: true,
  10518. configurable: true
  10519. });
  10520. _StencilState.prototype.reset = function () {
  10521. this._stencilTest = false;
  10522. this._stencilMask = 0xFF;
  10523. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10524. this._stencilFuncRef = 1;
  10525. this._stencilFuncMask = 0xFF;
  10526. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10527. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10528. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10529. this._isStencilTestDirty = true;
  10530. this._isStencilMaskDirty = true;
  10531. this._isStencilFuncDirty = true;
  10532. this._isStencilOpDirty = true;
  10533. };
  10534. _StencilState.prototype.apply = function (gl) {
  10535. if (!this.isDirty) {
  10536. return;
  10537. }
  10538. // Stencil test
  10539. if (this._isStencilTestDirty) {
  10540. if (this.stencilTest) {
  10541. gl.enable(gl.STENCIL_TEST);
  10542. }
  10543. else {
  10544. gl.disable(gl.STENCIL_TEST);
  10545. }
  10546. this._isStencilTestDirty = false;
  10547. }
  10548. // Stencil mask
  10549. if (this._isStencilMaskDirty) {
  10550. gl.stencilMask(this.stencilMask);
  10551. this._isStencilMaskDirty = false;
  10552. }
  10553. // Stencil func
  10554. if (this._isStencilFuncDirty) {
  10555. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10556. this._isStencilFuncDirty = false;
  10557. }
  10558. // Stencil op
  10559. if (this._isStencilOpDirty) {
  10560. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10561. this._isStencilOpDirty = false;
  10562. }
  10563. };
  10564. return _StencilState;
  10565. }());
  10566. BABYLON._StencilState = _StencilState;
  10567. })(BABYLON || (BABYLON = {}));
  10568. //# sourceMappingURL=babylon.stencilState.js.map
  10569. "use strict";
  10570. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10571. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10572. s = arguments[i];
  10573. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10574. t[p] = s[p];
  10575. }
  10576. return t;
  10577. };
  10578. var BABYLON;
  10579. (function (BABYLON) {
  10580. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10581. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10582. };
  10583. var compileRawShader = function (gl, source, type) {
  10584. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10585. gl.shaderSource(shader, source);
  10586. gl.compileShader(shader);
  10587. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10588. var log = gl.getShaderInfoLog(shader);
  10589. if (log) {
  10590. throw new Error(log);
  10591. }
  10592. }
  10593. if (!shader) {
  10594. throw new Error("Something went wrong while compile the shader.");
  10595. }
  10596. return shader;
  10597. };
  10598. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10599. var magFilter = gl.NEAREST;
  10600. var minFilter = gl.NEAREST;
  10601. switch (samplingMode) {
  10602. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10603. magFilter = gl.LINEAR;
  10604. if (generateMipMaps) {
  10605. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10606. }
  10607. else {
  10608. minFilter = gl.LINEAR;
  10609. }
  10610. break;
  10611. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10612. magFilter = gl.LINEAR;
  10613. if (generateMipMaps) {
  10614. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10615. }
  10616. else {
  10617. minFilter = gl.LINEAR;
  10618. }
  10619. break;
  10620. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10621. magFilter = gl.NEAREST;
  10622. if (generateMipMaps) {
  10623. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10624. }
  10625. else {
  10626. minFilter = gl.NEAREST;
  10627. }
  10628. break;
  10629. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10630. magFilter = gl.NEAREST;
  10631. if (generateMipMaps) {
  10632. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10633. }
  10634. else {
  10635. minFilter = gl.NEAREST;
  10636. }
  10637. break;
  10638. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10639. magFilter = gl.NEAREST;
  10640. if (generateMipMaps) {
  10641. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10642. }
  10643. else {
  10644. minFilter = gl.LINEAR;
  10645. }
  10646. break;
  10647. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10648. magFilter = gl.NEAREST;
  10649. if (generateMipMaps) {
  10650. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10651. }
  10652. else {
  10653. minFilter = gl.LINEAR;
  10654. }
  10655. break;
  10656. case BABYLON.Texture.NEAREST_LINEAR:
  10657. magFilter = gl.NEAREST;
  10658. minFilter = gl.LINEAR;
  10659. break;
  10660. case BABYLON.Texture.NEAREST_NEAREST:
  10661. magFilter = gl.NEAREST;
  10662. minFilter = gl.NEAREST;
  10663. break;
  10664. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10665. magFilter = gl.LINEAR;
  10666. if (generateMipMaps) {
  10667. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10668. }
  10669. else {
  10670. minFilter = gl.NEAREST;
  10671. }
  10672. break;
  10673. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10674. magFilter = gl.LINEAR;
  10675. if (generateMipMaps) {
  10676. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10677. }
  10678. else {
  10679. minFilter = gl.NEAREST;
  10680. }
  10681. break;
  10682. case BABYLON.Texture.LINEAR_LINEAR:
  10683. magFilter = gl.LINEAR;
  10684. minFilter = gl.LINEAR;
  10685. break;
  10686. case BABYLON.Texture.LINEAR_NEAREST:
  10687. magFilter = gl.LINEAR;
  10688. minFilter = gl.NEAREST;
  10689. break;
  10690. }
  10691. return {
  10692. min: minFilter,
  10693. mag: magFilter
  10694. };
  10695. };
  10696. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10697. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10698. var img;
  10699. var onload = function () {
  10700. loadedImages[index] = img;
  10701. loadedImages._internalCount++;
  10702. if (scene) {
  10703. scene._removePendingData(img);
  10704. }
  10705. if (loadedImages._internalCount === 6) {
  10706. onfinish(loadedImages);
  10707. }
  10708. };
  10709. var onerror = function (message, exception) {
  10710. if (scene) {
  10711. scene._removePendingData(img);
  10712. }
  10713. if (onErrorCallBack) {
  10714. onErrorCallBack(message, exception);
  10715. }
  10716. };
  10717. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10718. if (scene) {
  10719. scene._addPendingData(img);
  10720. }
  10721. };
  10722. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10723. if (onError === void 0) { onError = null; }
  10724. var loadedImages = [];
  10725. loadedImages._internalCount = 0;
  10726. for (var index = 0; index < 6; index++) {
  10727. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10728. }
  10729. };
  10730. var BufferPointer = /** @class */ (function () {
  10731. function BufferPointer() {
  10732. }
  10733. return BufferPointer;
  10734. }());
  10735. /**
  10736. * Interface for attribute information associated with buffer instanciation
  10737. */
  10738. var InstancingAttributeInfo = /** @class */ (function () {
  10739. function InstancingAttributeInfo() {
  10740. }
  10741. return InstancingAttributeInfo;
  10742. }());
  10743. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10744. /**
  10745. * Define options used to create a render target texture
  10746. */
  10747. var RenderTargetCreationOptions = /** @class */ (function () {
  10748. function RenderTargetCreationOptions() {
  10749. }
  10750. return RenderTargetCreationOptions;
  10751. }());
  10752. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10753. /**
  10754. * Define options used to create a depth texture
  10755. */
  10756. var DepthTextureCreationOptions = /** @class */ (function () {
  10757. function DepthTextureCreationOptions() {
  10758. }
  10759. return DepthTextureCreationOptions;
  10760. }());
  10761. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10762. /**
  10763. * Class used to describe the capabilities of the engine relatively to the current browser
  10764. */
  10765. var EngineCapabilities = /** @class */ (function () {
  10766. function EngineCapabilities() {
  10767. }
  10768. return EngineCapabilities;
  10769. }());
  10770. BABYLON.EngineCapabilities = EngineCapabilities;
  10771. /**
  10772. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  10773. */
  10774. var Engine = /** @class */ (function () {
  10775. /**
  10776. * Creates a new engine
  10777. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10778. * @param antialias defines enable antialiasing (default: false)
  10779. * @param options defines further options to be sent to the getContext() function
  10780. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10781. */
  10782. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10783. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10784. var _this = this;
  10785. // Public members
  10786. /**
  10787. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  10788. */
  10789. this.forcePOTTextures = false;
  10790. /**
  10791. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  10792. */
  10793. this.isFullscreen = false;
  10794. /**
  10795. * Gets a boolean indicating if the pointer is currently locked
  10796. */
  10797. this.isPointerLock = false;
  10798. /**
  10799. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  10800. */
  10801. this.cullBackFaces = true;
  10802. /**
  10803. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  10804. */
  10805. this.renderEvenInBackground = true;
  10806. /**
  10807. * Gets or sets a boolean indicating that cache can be kept between frames
  10808. */
  10809. this.preventCacheWipeBetweenFrames = false;
  10810. /**
  10811. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  10812. **/
  10813. this.enableOfflineSupport = false;
  10814. /**
  10815. * Gets the list of created scenes
  10816. */
  10817. this.scenes = new Array();
  10818. /**
  10819. * Gets the list of created postprocesses
  10820. */
  10821. this.postProcesses = new Array();
  10822. // Observables
  10823. /**
  10824. * Observable event triggered each time the rendering canvas is resized
  10825. */
  10826. this.onResizeObservable = new BABYLON.Observable();
  10827. /**
  10828. * Observable event triggered each time the canvas loses focus
  10829. */
  10830. this.onCanvasBlurObservable = new BABYLON.Observable();
  10831. /**
  10832. * Observable event triggered each time the canvas gains focus
  10833. */
  10834. this.onCanvasFocusObservable = new BABYLON.Observable();
  10835. /**
  10836. * Observable event triggered each time the canvas receives pointerout event
  10837. */
  10838. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10839. /**
  10840. * Observable event triggered before each texture is initialized
  10841. */
  10842. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10843. //WebVR
  10844. this._vrDisplay = undefined;
  10845. this._vrSupported = false;
  10846. this._vrExclusivePointerMode = false;
  10847. // Uniform buffers list
  10848. /**
  10849. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  10850. */
  10851. this.disableUniformBuffers = false;
  10852. /** @ignore */
  10853. this._uniformBuffers = new Array();
  10854. // Observables
  10855. /**
  10856. * Observable raised when the engine begins a new frame
  10857. */
  10858. this.onBeginFrameObservable = new BABYLON.Observable();
  10859. /**
  10860. * Observable raised when the engine ends the current frame
  10861. */
  10862. this.onEndFrameObservable = new BABYLON.Observable();
  10863. /**
  10864. * Observable raised when the engine is about to compile a shader
  10865. */
  10866. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10867. /**
  10868. * Observable raised when the engine has jsut compiled a shader
  10869. */
  10870. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10871. this._windowIsBackground = false;
  10872. this._webGLVersion = 1.0;
  10873. /** @ignore */
  10874. this._badOS = false;
  10875. /** @ignore */
  10876. this._badDesktopOS = false;
  10877. /**
  10878. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10879. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  10880. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  10881. */
  10882. this.disableTextureBindingOptimization = false;
  10883. /**
  10884. * Observable signaled when VR display mode changes
  10885. */
  10886. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10887. /**
  10888. * Observable signaled when VR request present is complete
  10889. */
  10890. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10891. /**
  10892. * Observable signaled when VR request present starts
  10893. */
  10894. this.onVRRequestPresentStart = new BABYLON.Observable();
  10895. this._colorWrite = true;
  10896. /** @ignore */
  10897. this._drawCalls = new BABYLON.PerfCounter();
  10898. /** @ignore */
  10899. this._textureCollisions = new BABYLON.PerfCounter();
  10900. this._renderingQueueLaunched = false;
  10901. this._activeRenderLoops = new Array();
  10902. // Deterministic lockstepMaxSteps
  10903. this._deterministicLockstep = false;
  10904. this._lockstepMaxSteps = 4;
  10905. // Lost context
  10906. /**
  10907. * Observable signaled when a context lost event is raised
  10908. */
  10909. this.onContextLostObservable = new BABYLON.Observable();
  10910. /**
  10911. * Observable signaled when a context restored event is raised
  10912. */
  10913. this.onContextRestoredObservable = new BABYLON.Observable();
  10914. this._contextWasLost = false;
  10915. this._doNotHandleContextLost = false;
  10916. // FPS
  10917. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10918. this._fps = 60;
  10919. this._deltaTime = 0;
  10920. /**
  10921. * Turn this value on if you want to pause FPS computation when in background
  10922. */
  10923. this.disablePerformanceMonitorInBackground = false;
  10924. // States
  10925. /** @ignore */
  10926. this._depthCullingState = new BABYLON._DepthCullingState();
  10927. /** @ignore */
  10928. this._stencilState = new BABYLON._StencilState();
  10929. /** @ignore */
  10930. this._alphaState = new BABYLON._AlphaState();
  10931. /** @ignore */
  10932. this._alphaMode = Engine.ALPHA_DISABLE;
  10933. // Cache
  10934. this._internalTexturesCache = new Array();
  10935. /** @ignore */
  10936. this._activeChannel = 0;
  10937. this._currentTextureChannel = -1;
  10938. /** @ignore */
  10939. this._boundTexturesCache = {};
  10940. this._compiledEffects = {};
  10941. this._vertexAttribArraysEnabled = [];
  10942. this._uintIndicesCurrentlySet = false;
  10943. this._currentBoundBuffer = new Array();
  10944. this._currentBufferPointers = new Array();
  10945. this._currentInstanceLocations = new Array();
  10946. this._currentInstanceBuffers = new Array();
  10947. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10948. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10949. this._vaoRecordInProgress = false;
  10950. this._mustWipeVertexAttributes = false;
  10951. this._nextFreeTextureSlots = new Array();
  10952. this._maxSimultaneousTextures = 0;
  10953. this._activeRequests = new Array();
  10954. // Hardware supported Compressed Textures
  10955. this._texturesSupported = new Array();
  10956. this._onVRFullScreenTriggered = function () {
  10957. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10958. //get the old size before we change
  10959. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10960. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10961. //get the width and height, change the render size
  10962. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10963. _this.setHardwareScalingLevel(1);
  10964. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10965. }
  10966. else {
  10967. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10968. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10969. }
  10970. };
  10971. this._boundUniforms = {};
  10972. // Register promises
  10973. BABYLON.PromisePolyfill.Apply();
  10974. var canvas = null;
  10975. Engine.Instances.push(this);
  10976. if (!canvasOrContext) {
  10977. return;
  10978. }
  10979. options = options || {};
  10980. if (canvasOrContext.getContext) {
  10981. canvas = canvasOrContext;
  10982. this._renderingCanvas = canvas;
  10983. if (antialias != null) {
  10984. options.antialias = antialias;
  10985. }
  10986. if (options.deterministicLockstep === undefined) {
  10987. options.deterministicLockstep = false;
  10988. }
  10989. if (options.lockstepMaxSteps === undefined) {
  10990. options.lockstepMaxSteps = 4;
  10991. }
  10992. if (options.preserveDrawingBuffer === undefined) {
  10993. options.preserveDrawingBuffer = false;
  10994. }
  10995. if (options.audioEngine === undefined) {
  10996. options.audioEngine = true;
  10997. }
  10998. if (options.stencil === undefined) {
  10999. options.stencil = true;
  11000. }
  11001. this._deterministicLockstep = options.deterministicLockstep;
  11002. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11003. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11004. // Exceptions
  11005. if (navigator && navigator.userAgent) {
  11006. var ua = navigator.userAgent;
  11007. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11008. var exception = _a[_i];
  11009. var key = exception.key;
  11010. var targets = exception.targets;
  11011. if (ua.indexOf(key) > -1) {
  11012. if (exception.capture && exception.captureConstraint) {
  11013. var capture = exception.capture;
  11014. var constraint = exception.captureConstraint;
  11015. var regex = new RegExp(capture);
  11016. var matches = regex.exec(ua);
  11017. if (matches && matches.length > 0) {
  11018. var capturedValue = parseInt(matches[matches.length - 1]);
  11019. if (capturedValue >= constraint) {
  11020. continue;
  11021. }
  11022. }
  11023. }
  11024. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11025. var target = targets_1[_b];
  11026. switch (target) {
  11027. case "uniformBuffer":
  11028. this.disableUniformBuffers = true;
  11029. break;
  11030. case "textureBindingOptimization":
  11031. this.disableTextureBindingOptimization = true;
  11032. break;
  11033. }
  11034. }
  11035. }
  11036. }
  11037. }
  11038. // GL
  11039. if (!options.disableWebGL2Support) {
  11040. try {
  11041. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11042. if (this._gl) {
  11043. this._webGLVersion = 2.0;
  11044. }
  11045. }
  11046. catch (e) {
  11047. // Do nothing
  11048. }
  11049. }
  11050. if (!this._gl) {
  11051. if (!canvas) {
  11052. throw new Error("The provided canvas is null or undefined.");
  11053. }
  11054. try {
  11055. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11056. }
  11057. catch (e) {
  11058. throw new Error("WebGL not supported");
  11059. }
  11060. }
  11061. if (!this._gl) {
  11062. throw new Error("WebGL not supported");
  11063. }
  11064. this._onCanvasFocus = function () {
  11065. _this.onCanvasFocusObservable.notifyObservers(_this);
  11066. };
  11067. this._onCanvasBlur = function () {
  11068. _this.onCanvasBlurObservable.notifyObservers(_this);
  11069. };
  11070. canvas.addEventListener("focus", this._onCanvasFocus);
  11071. canvas.addEventListener("blur", this._onCanvasBlur);
  11072. this._onBlur = function () {
  11073. if (_this.disablePerformanceMonitorInBackground) {
  11074. _this._performanceMonitor.disable();
  11075. }
  11076. _this._windowIsBackground = true;
  11077. };
  11078. this._onFocus = function () {
  11079. if (_this.disablePerformanceMonitorInBackground) {
  11080. _this._performanceMonitor.enable();
  11081. }
  11082. _this._windowIsBackground = false;
  11083. };
  11084. this._onCanvasPointerOut = function (ev) {
  11085. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11086. };
  11087. window.addEventListener("blur", this._onBlur);
  11088. window.addEventListener("focus", this._onFocus);
  11089. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11090. // Context lost
  11091. if (!this._doNotHandleContextLost) {
  11092. this._onContextLost = function (evt) {
  11093. evt.preventDefault();
  11094. _this._contextWasLost = true;
  11095. BABYLON.Tools.Warn("WebGL context lost.");
  11096. _this.onContextLostObservable.notifyObservers(_this);
  11097. };
  11098. this._onContextRestored = function (evt) {
  11099. // Adding a timeout to avoid race condition at browser level
  11100. setTimeout(function () {
  11101. // Rebuild gl context
  11102. _this._initGLContext();
  11103. // Rebuild effects
  11104. _this._rebuildEffects();
  11105. // Rebuild textures
  11106. _this._rebuildInternalTextures();
  11107. // Rebuild buffers
  11108. _this._rebuildBuffers();
  11109. // Cache
  11110. _this.wipeCaches(true);
  11111. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11112. _this.onContextRestoredObservable.notifyObservers(_this);
  11113. _this._contextWasLost = false;
  11114. }, 0);
  11115. };
  11116. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11117. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11118. }
  11119. }
  11120. else {
  11121. this._gl = canvasOrContext;
  11122. this._renderingCanvas = this._gl.canvas;
  11123. if (this._gl.renderbufferStorageMultisample) {
  11124. this._webGLVersion = 2.0;
  11125. }
  11126. options.stencil = this._gl.getContextAttributes().stencil;
  11127. }
  11128. // Viewport
  11129. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11130. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11131. this.resize();
  11132. this._isStencilEnable = options.stencil ? true : false;
  11133. this._initGLContext();
  11134. if (canvas) {
  11135. // Fullscreen
  11136. this._onFullscreenChange = function () {
  11137. if (document.fullscreen !== undefined) {
  11138. _this.isFullscreen = document.fullscreen;
  11139. }
  11140. else if (document.mozFullScreen !== undefined) {
  11141. _this.isFullscreen = document.mozFullScreen;
  11142. }
  11143. else if (document.webkitIsFullScreen !== undefined) {
  11144. _this.isFullscreen = document.webkitIsFullScreen;
  11145. }
  11146. else if (document.msIsFullScreen !== undefined) {
  11147. _this.isFullscreen = document.msIsFullScreen;
  11148. }
  11149. // Pointer lock
  11150. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11151. canvas.requestPointerLock = canvas.requestPointerLock ||
  11152. canvas.msRequestPointerLock ||
  11153. canvas.mozRequestPointerLock ||
  11154. canvas.webkitRequestPointerLock;
  11155. if (canvas.requestPointerLock) {
  11156. canvas.requestPointerLock();
  11157. }
  11158. }
  11159. };
  11160. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11161. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11162. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11163. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11164. // Pointer lock
  11165. this._onPointerLockChange = function () {
  11166. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11167. document.webkitPointerLockElement === canvas ||
  11168. document.msPointerLockElement === canvas ||
  11169. document.pointerLockElement === canvas);
  11170. };
  11171. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11172. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11173. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11174. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11175. this._onVRDisplayPointerRestricted = function () {
  11176. if (canvas) {
  11177. canvas.requestPointerLock();
  11178. }
  11179. };
  11180. this._onVRDisplayPointerUnrestricted = function () {
  11181. document.exitPointerLock();
  11182. };
  11183. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11184. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11185. }
  11186. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11187. Engine.audioEngine = new BABYLON.AudioEngine();
  11188. }
  11189. // Prepare buffer pointers
  11190. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11191. this._currentBufferPointers[i] = new BufferPointer();
  11192. }
  11193. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11194. // Load WebVR Devices
  11195. if (options.autoEnableWebVR) {
  11196. this.initWebVR();
  11197. }
  11198. // Detect if we are running on a faulty buggy OS.
  11199. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11200. // Detect if we are running on a faulty buggy desktop OS.
  11201. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11202. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11203. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11204. }
  11205. Object.defineProperty(Engine, "LastCreatedEngine", {
  11206. /**
  11207. * Gets the latest created engine
  11208. */
  11209. get: function () {
  11210. if (Engine.Instances.length === 0) {
  11211. return null;
  11212. }
  11213. return Engine.Instances[Engine.Instances.length - 1];
  11214. },
  11215. enumerable: true,
  11216. configurable: true
  11217. });
  11218. Object.defineProperty(Engine, "LastCreatedScene", {
  11219. /**
  11220. * Gets the latest created scene
  11221. */
  11222. get: function () {
  11223. var lastCreatedEngine = Engine.LastCreatedEngine;
  11224. if (!lastCreatedEngine) {
  11225. return null;
  11226. }
  11227. if (lastCreatedEngine.scenes.length === 0) {
  11228. return null;
  11229. }
  11230. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. /**
  11236. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11237. * @param flag defines which part of the materials must be marked as dirty
  11238. * @param predicate defines a predicate used to filter which materials should be affected
  11239. */
  11240. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11241. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11242. var engine = Engine.Instances[engineIndex];
  11243. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11244. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11245. }
  11246. }
  11247. };
  11248. Object.defineProperty(Engine, "NEVER", {
  11249. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11250. get: function () {
  11251. return Engine._NEVER;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. Object.defineProperty(Engine, "ALWAYS", {
  11257. /** 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 */
  11258. get: function () {
  11259. return Engine._ALWAYS;
  11260. },
  11261. enumerable: true,
  11262. configurable: true
  11263. });
  11264. Object.defineProperty(Engine, "LESS", {
  11265. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11266. get: function () {
  11267. return Engine._LESS;
  11268. },
  11269. enumerable: true,
  11270. configurable: true
  11271. });
  11272. Object.defineProperty(Engine, "EQUAL", {
  11273. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11274. get: function () {
  11275. return Engine._EQUAL;
  11276. },
  11277. enumerable: true,
  11278. configurable: true
  11279. });
  11280. Object.defineProperty(Engine, "LEQUAL", {
  11281. /** 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 */
  11282. get: function () {
  11283. return Engine._LEQUAL;
  11284. },
  11285. enumerable: true,
  11286. configurable: true
  11287. });
  11288. Object.defineProperty(Engine, "GREATER", {
  11289. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11290. get: function () {
  11291. return Engine._GREATER;
  11292. },
  11293. enumerable: true,
  11294. configurable: true
  11295. });
  11296. Object.defineProperty(Engine, "GEQUAL", {
  11297. /** 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 */
  11298. get: function () {
  11299. return Engine._GEQUAL;
  11300. },
  11301. enumerable: true,
  11302. configurable: true
  11303. });
  11304. Object.defineProperty(Engine, "NOTEQUAL", {
  11305. /** 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 */
  11306. get: function () {
  11307. return Engine._NOTEQUAL;
  11308. },
  11309. enumerable: true,
  11310. configurable: true
  11311. });
  11312. Object.defineProperty(Engine, "KEEP", {
  11313. /** Passed to stencilOperation to specify that stencil value must be kept */
  11314. get: function () {
  11315. return Engine._KEEP;
  11316. },
  11317. enumerable: true,
  11318. configurable: true
  11319. });
  11320. Object.defineProperty(Engine, "REPLACE", {
  11321. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11322. get: function () {
  11323. return Engine._REPLACE;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Object.defineProperty(Engine, "INCR", {
  11329. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11330. get: function () {
  11331. return Engine._INCR;
  11332. },
  11333. enumerable: true,
  11334. configurable: true
  11335. });
  11336. Object.defineProperty(Engine, "DECR", {
  11337. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11338. get: function () {
  11339. return Engine._DECR;
  11340. },
  11341. enumerable: true,
  11342. configurable: true
  11343. });
  11344. Object.defineProperty(Engine, "INVERT", {
  11345. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11346. get: function () {
  11347. return Engine._INVERT;
  11348. },
  11349. enumerable: true,
  11350. configurable: true
  11351. });
  11352. Object.defineProperty(Engine, "INCR_WRAP", {
  11353. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11354. get: function () {
  11355. return Engine._INCR_WRAP;
  11356. },
  11357. enumerable: true,
  11358. configurable: true
  11359. });
  11360. Object.defineProperty(Engine, "DECR_WRAP", {
  11361. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11362. get: function () {
  11363. return Engine._DECR_WRAP;
  11364. },
  11365. enumerable: true,
  11366. configurable: true
  11367. });
  11368. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11369. // Alpha
  11370. /** Defines that alpha blending is disabled */
  11371. get: function () {
  11372. return Engine._ALPHA_DISABLE;
  11373. },
  11374. enumerable: true,
  11375. configurable: true
  11376. });
  11377. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11378. /** Defines that alpha blending to SRC + DEST */
  11379. get: function () {
  11380. return Engine._ALPHA_ONEONE;
  11381. },
  11382. enumerable: true,
  11383. configurable: true
  11384. });
  11385. Object.defineProperty(Engine, "ALPHA_ADD", {
  11386. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11387. get: function () {
  11388. return Engine._ALPHA_ADD;
  11389. },
  11390. enumerable: true,
  11391. configurable: true
  11392. });
  11393. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11394. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11395. get: function () {
  11396. return Engine._ALPHA_COMBINE;
  11397. },
  11398. enumerable: true,
  11399. configurable: true
  11400. });
  11401. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11402. /** Defines that alpha blending to DEST - SRC * DEST */
  11403. get: function () {
  11404. return Engine._ALPHA_SUBTRACT;
  11405. },
  11406. enumerable: true,
  11407. configurable: true
  11408. });
  11409. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11410. /** Defines that alpha blending to SRC * DEST */
  11411. get: function () {
  11412. return Engine._ALPHA_MULTIPLY;
  11413. },
  11414. enumerable: true,
  11415. configurable: true
  11416. });
  11417. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11418. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11419. get: function () {
  11420. return Engine._ALPHA_MAXIMIZED;
  11421. },
  11422. enumerable: true,
  11423. configurable: true
  11424. });
  11425. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11426. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11427. get: function () {
  11428. return Engine._ALPHA_PREMULTIPLIED;
  11429. },
  11430. enumerable: true,
  11431. configurable: true
  11432. });
  11433. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11434. /**
  11435. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11436. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11437. */
  11438. get: function () {
  11439. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11440. },
  11441. enumerable: true,
  11442. configurable: true
  11443. });
  11444. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11445. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11446. get: function () {
  11447. return Engine._ALPHA_INTERPOLATE;
  11448. },
  11449. enumerable: true,
  11450. configurable: true
  11451. });
  11452. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11453. /**
  11454. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11455. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11456. */
  11457. get: function () {
  11458. return Engine._ALPHA_SCREENMODE;
  11459. },
  11460. enumerable: true,
  11461. configurable: true
  11462. });
  11463. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11464. // Delays
  11465. /** Defines that the ressource is not delayed*/
  11466. get: function () {
  11467. return Engine._DELAYLOADSTATE_NONE;
  11468. },
  11469. enumerable: true,
  11470. configurable: true
  11471. });
  11472. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11473. /** Defines that the ressource was successfully delay loaded */
  11474. get: function () {
  11475. return Engine._DELAYLOADSTATE_LOADED;
  11476. },
  11477. enumerable: true,
  11478. configurable: true
  11479. });
  11480. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11481. /** Defines that the ressource is currently delay loading */
  11482. get: function () {
  11483. return Engine._DELAYLOADSTATE_LOADING;
  11484. },
  11485. enumerable: true,
  11486. configurable: true
  11487. });
  11488. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11489. /** Defines that the ressource is delayed and has not started loading */
  11490. get: function () {
  11491. return Engine._DELAYLOADSTATE_NOTLOADED;
  11492. },
  11493. enumerable: true,
  11494. configurable: true
  11495. });
  11496. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11497. /** ALPHA */
  11498. get: function () {
  11499. return Engine._TEXTUREFORMAT_ALPHA;
  11500. },
  11501. enumerable: true,
  11502. configurable: true
  11503. });
  11504. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11505. /** LUMINANCE */
  11506. get: function () {
  11507. return Engine._TEXTUREFORMAT_LUMINANCE;
  11508. },
  11509. enumerable: true,
  11510. configurable: true
  11511. });
  11512. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11513. /**
  11514. * R32F
  11515. */
  11516. get: function () {
  11517. return Engine._TEXTUREFORMAT_R32F;
  11518. },
  11519. enumerable: true,
  11520. configurable: true
  11521. });
  11522. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11523. /**
  11524. * RG32F
  11525. */
  11526. get: function () {
  11527. return Engine._TEXTUREFORMAT_RG32F;
  11528. },
  11529. enumerable: true,
  11530. configurable: true
  11531. });
  11532. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11533. /**
  11534. * RGB32F
  11535. */
  11536. get: function () {
  11537. return Engine._TEXTUREFORMAT_RGB32F;
  11538. },
  11539. enumerable: true,
  11540. configurable: true
  11541. });
  11542. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11543. /**
  11544. * RGBA32F
  11545. */
  11546. get: function () {
  11547. return Engine._TEXTUREFORMAT_RGBA32F;
  11548. },
  11549. enumerable: true,
  11550. configurable: true
  11551. });
  11552. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11553. /** LUMINANCE_ALPHA */
  11554. get: function () {
  11555. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11561. /** RGB */
  11562. get: function () {
  11563. return Engine._TEXTUREFORMAT_RGB;
  11564. },
  11565. enumerable: true,
  11566. configurable: true
  11567. });
  11568. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11569. /** RGBA */
  11570. get: function () {
  11571. return Engine._TEXTUREFORMAT_RGBA;
  11572. },
  11573. enumerable: true,
  11574. configurable: true
  11575. });
  11576. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11577. /** UNSIGNED_INT */
  11578. get: function () {
  11579. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11580. },
  11581. enumerable: true,
  11582. configurable: true
  11583. });
  11584. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11585. /** FLOAT */
  11586. get: function () {
  11587. return Engine._TEXTURETYPE_FLOAT;
  11588. },
  11589. enumerable: true,
  11590. configurable: true
  11591. });
  11592. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11593. /** HALF_FLOAT */
  11594. get: function () {
  11595. return Engine._TEXTURETYPE_HALF_FLOAT;
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11601. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11602. get: function () {
  11603. return Engine._SCALEMODE_FLOOR;
  11604. },
  11605. enumerable: true,
  11606. configurable: true
  11607. });
  11608. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11609. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11610. get: function () {
  11611. return Engine._SCALEMODE_NEAREST;
  11612. },
  11613. enumerable: true,
  11614. configurable: true
  11615. });
  11616. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11617. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11618. get: function () {
  11619. return Engine._SCALEMODE_CEILING;
  11620. },
  11621. enumerable: true,
  11622. configurable: true
  11623. });
  11624. Object.defineProperty(Engine, "Version", {
  11625. /**
  11626. * Returns the current version of the framework
  11627. */
  11628. get: function () {
  11629. return "3.2.0-beta.4";
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11635. /**
  11636. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11637. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11638. */
  11639. get: function () {
  11640. return this._vrExclusivePointerMode;
  11641. },
  11642. enumerable: true,
  11643. configurable: true
  11644. });
  11645. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11646. /**
  11647. * Gets a boolean indicating that the engine supports uniform buffers
  11648. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11649. */
  11650. get: function () {
  11651. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11652. },
  11653. enumerable: true,
  11654. configurable: true
  11655. });
  11656. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11657. /**
  11658. * Gets a boolean indicating that only power of 2 textures are supported
  11659. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11660. */
  11661. get: function () {
  11662. return this._webGLVersion < 2 || this.forcePOTTextures;
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11668. /**
  11669. * Gets the performance monitor attached to this engine
  11670. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11671. */
  11672. get: function () {
  11673. return this._performanceMonitor;
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11679. /**
  11680. * Gets the list of texture formats supported
  11681. */
  11682. get: function () {
  11683. return this._texturesSupported;
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11689. /**
  11690. * Gets the list of texture formats in use
  11691. */
  11692. get: function () {
  11693. return this._textureFormatInUse;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine.prototype, "currentViewport", {
  11699. /**
  11700. * Gets the current viewport
  11701. */
  11702. get: function () {
  11703. return this._cachedViewport;
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11709. /**
  11710. * Gets the default empty texture
  11711. */
  11712. get: function () {
  11713. if (!this._emptyTexture) {
  11714. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11715. }
  11716. return this._emptyTexture;
  11717. },
  11718. enumerable: true,
  11719. configurable: true
  11720. });
  11721. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11722. /**
  11723. * Gets the default empty 3D texture
  11724. */
  11725. get: function () {
  11726. if (!this._emptyTexture3D) {
  11727. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11728. }
  11729. return this._emptyTexture3D;
  11730. },
  11731. enumerable: true,
  11732. configurable: true
  11733. });
  11734. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11735. /**
  11736. * Gets the default empty cube texture
  11737. */
  11738. get: function () {
  11739. if (!this._emptyCubeTexture) {
  11740. var faceData = new Uint8Array(4);
  11741. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11742. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11743. }
  11744. return this._emptyCubeTexture;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Engine.prototype._rebuildInternalTextures = function () {
  11750. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11751. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11752. var internalTexture = currentState_1[_i];
  11753. internalTexture._rebuild();
  11754. }
  11755. };
  11756. Engine.prototype._rebuildEffects = function () {
  11757. for (var key in this._compiledEffects) {
  11758. var effect = this._compiledEffects[key];
  11759. effect._prepareEffect();
  11760. }
  11761. BABYLON.Effect.ResetCache();
  11762. };
  11763. Engine.prototype._rebuildBuffers = function () {
  11764. // Index / Vertex
  11765. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11766. var scene = _a[_i];
  11767. scene.resetCachedMaterial();
  11768. scene._rebuildGeometries();
  11769. scene._rebuildTextures();
  11770. }
  11771. // Uniforms
  11772. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11773. var uniformBuffer = _c[_b];
  11774. uniformBuffer._rebuild();
  11775. }
  11776. };
  11777. Engine.prototype._initGLContext = function () {
  11778. // Caps
  11779. this._caps = new EngineCapabilities();
  11780. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11781. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11782. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11783. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11784. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11785. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11786. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11787. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11788. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11789. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11790. // Infos
  11791. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11792. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11793. if (rendererInfo != null) {
  11794. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11795. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11796. }
  11797. if (!this._glVendor) {
  11798. this._glVendor = "Unknown vendor";
  11799. }
  11800. if (!this._glRenderer) {
  11801. this._glRenderer = "Unknown renderer";
  11802. }
  11803. // Constants
  11804. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11805. if (this._gl.RGBA16F !== 0x881A) {
  11806. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11807. }
  11808. if (this._gl.RGBA32F !== 0x8814) {
  11809. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11810. }
  11811. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11812. this._gl.DEPTH24_STENCIL8 = 35056;
  11813. }
  11814. // Extensions
  11815. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11816. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11817. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11818. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11819. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11820. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11821. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11822. 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');
  11823. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11824. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11825. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11826. this._caps.highPrecisionShaderSupported = true;
  11827. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11828. if (this._caps.timerQuery) {
  11829. if (this._webGLVersion === 1) {
  11830. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11831. }
  11832. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11833. }
  11834. // Checks if some of the format renders first to allow the use of webgl inspector.
  11835. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11836. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11837. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11838. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11839. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11840. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11841. if (this._webGLVersion > 1) {
  11842. this._gl.HALF_FLOAT_OES = 0x140B;
  11843. }
  11844. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11845. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11846. // Draw buffers
  11847. if (this._webGLVersion > 1) {
  11848. this._caps.drawBuffersExtension = true;
  11849. }
  11850. else {
  11851. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11852. if (drawBuffersExtension !== null) {
  11853. this._caps.drawBuffersExtension = true;
  11854. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11855. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11856. for (var i = 0; i < 16; i++) {
  11857. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11858. }
  11859. }
  11860. else {
  11861. this._caps.drawBuffersExtension = false;
  11862. }
  11863. }
  11864. // Depth Texture
  11865. if (this._webGLVersion > 1) {
  11866. this._caps.depthTextureExtension = true;
  11867. }
  11868. else {
  11869. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11870. if (depthTextureExtension != null) {
  11871. this._caps.depthTextureExtension = true;
  11872. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11873. }
  11874. }
  11875. // Vertex array object
  11876. if (this._webGLVersion > 1) {
  11877. this._caps.vertexArrayObject = true;
  11878. }
  11879. else {
  11880. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11881. if (vertexArrayObjectExtension != null) {
  11882. this._caps.vertexArrayObject = true;
  11883. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11884. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11885. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11886. }
  11887. else {
  11888. this._caps.vertexArrayObject = false;
  11889. }
  11890. }
  11891. // Instances count
  11892. if (this._webGLVersion > 1) {
  11893. this._caps.instancedArrays = true;
  11894. }
  11895. else {
  11896. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11897. if (instanceExtension != null) {
  11898. this._caps.instancedArrays = true;
  11899. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11900. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11901. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11902. }
  11903. else {
  11904. this._caps.instancedArrays = false;
  11905. }
  11906. }
  11907. // Intelligently add supported compressed formats in order to check for.
  11908. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11909. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11910. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11911. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11912. if (this._caps.astc)
  11913. this.texturesSupported.push('-astc.ktx');
  11914. if (this._caps.s3tc)
  11915. this.texturesSupported.push('-dxt.ktx');
  11916. if (this._caps.pvrtc)
  11917. this.texturesSupported.push('-pvrtc.ktx');
  11918. if (this._caps.etc2)
  11919. this.texturesSupported.push('-etc2.ktx');
  11920. if (this._caps.etc1)
  11921. this.texturesSupported.push('-etc1.ktx');
  11922. if (this._gl.getShaderPrecisionFormat) {
  11923. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11924. if (highp) {
  11925. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11926. }
  11927. }
  11928. // Depth buffer
  11929. this.setDepthBuffer(true);
  11930. this.setDepthFunctionToLessOrEqual();
  11931. this.setDepthWrite(true);
  11932. // Texture maps
  11933. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11934. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11935. this._nextFreeTextureSlots.push(slot);
  11936. }
  11937. };
  11938. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11939. /**
  11940. * Gets version of the current webGL context
  11941. */
  11942. get: function () {
  11943. return this._webGLVersion;
  11944. },
  11945. enumerable: true,
  11946. configurable: true
  11947. });
  11948. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11949. /**
  11950. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11951. */
  11952. get: function () {
  11953. return this._isStencilEnable;
  11954. },
  11955. enumerable: true,
  11956. configurable: true
  11957. });
  11958. Engine.prototype._prepareWorkingCanvas = function () {
  11959. if (this._workingCanvas) {
  11960. return;
  11961. }
  11962. this._workingCanvas = document.createElement("canvas");
  11963. var context = this._workingCanvas.getContext("2d");
  11964. if (context) {
  11965. this._workingContext = context;
  11966. }
  11967. };
  11968. /**
  11969. * Reset the texture cache to empty state
  11970. */
  11971. Engine.prototype.resetTextureCache = function () {
  11972. for (var key in this._boundTexturesCache) {
  11973. var boundTexture = this._boundTexturesCache[key];
  11974. if (boundTexture) {
  11975. this._removeDesignatedSlot(boundTexture);
  11976. }
  11977. this._boundTexturesCache[key] = null;
  11978. }
  11979. if (!this.disableTextureBindingOptimization) {
  11980. this._nextFreeTextureSlots = [];
  11981. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11982. this._nextFreeTextureSlots.push(slot);
  11983. }
  11984. }
  11985. this._currentTextureChannel = -1;
  11986. };
  11987. /**
  11988. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  11989. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11990. * @returns true if engine is in deterministic lock step mode
  11991. */
  11992. Engine.prototype.isDeterministicLockStep = function () {
  11993. return this._deterministicLockstep;
  11994. };
  11995. /**
  11996. * Gets the max steps when engine is running in deterministic lock step
  11997. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  11998. * @returns the max steps
  11999. */
  12000. Engine.prototype.getLockstepMaxSteps = function () {
  12001. return this._lockstepMaxSteps;
  12002. };
  12003. /**
  12004. * Gets an object containing information about the current webGL context
  12005. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12006. */
  12007. Engine.prototype.getGlInfo = function () {
  12008. return {
  12009. vendor: this._glVendor,
  12010. renderer: this._glRenderer,
  12011. version: this._glVersion
  12012. };
  12013. };
  12014. /**
  12015. * Gets current aspect ratio
  12016. * @param camera defines the camera to use to get the aspect ratio
  12017. * @param useScreen defines if screen size must be used (or the current render target if any)
  12018. * @returns a number defining the aspect ratio
  12019. */
  12020. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12021. if (useScreen === void 0) { useScreen = false; }
  12022. var viewport = camera.viewport;
  12023. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12024. };
  12025. /**
  12026. * Gets the current render width
  12027. * @param useScreen defines if screen size must be used (or the current render target if any)
  12028. * @returns a number defining the current render width
  12029. */
  12030. Engine.prototype.getRenderWidth = function (useScreen) {
  12031. if (useScreen === void 0) { useScreen = false; }
  12032. if (!useScreen && this._currentRenderTarget) {
  12033. return this._currentRenderTarget.width;
  12034. }
  12035. return this._gl.drawingBufferWidth;
  12036. };
  12037. /**
  12038. * Gets the current render height
  12039. * @param useScreen defines if screen size must be used (or the current render target if any)
  12040. * @returns a number defining the current render height
  12041. */
  12042. Engine.prototype.getRenderHeight = function (useScreen) {
  12043. if (useScreen === void 0) { useScreen = false; }
  12044. if (!useScreen && this._currentRenderTarget) {
  12045. return this._currentRenderTarget.height;
  12046. }
  12047. return this._gl.drawingBufferHeight;
  12048. };
  12049. /**
  12050. * Gets the HTML canvas attached with the current webGL context
  12051. * @returns a HTML canvas
  12052. */
  12053. Engine.prototype.getRenderingCanvas = function () {
  12054. return this._renderingCanvas;
  12055. };
  12056. /**
  12057. * Gets the client rect of the HTML canvas attached with the current webGL context
  12058. * @returns a client rectanglee
  12059. */
  12060. Engine.prototype.getRenderingCanvasClientRect = function () {
  12061. if (!this._renderingCanvas) {
  12062. return null;
  12063. }
  12064. return this._renderingCanvas.getBoundingClientRect();
  12065. };
  12066. /**
  12067. * Defines the hardware scaling level.
  12068. * By default the hardware scaling level is computed from the window device ratio.
  12069. * 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.
  12070. * @param level defines the level to use
  12071. */
  12072. Engine.prototype.setHardwareScalingLevel = function (level) {
  12073. this._hardwareScalingLevel = level;
  12074. this.resize();
  12075. };
  12076. /**
  12077. * Gets the current hardware scaling level.
  12078. * By default the hardware scaling level is computed from the window device ratio.
  12079. * 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.
  12080. * @returns a number indicating the current hardware scaling level
  12081. */
  12082. Engine.prototype.getHardwareScalingLevel = function () {
  12083. return this._hardwareScalingLevel;
  12084. };
  12085. /**
  12086. * Gets the list of loaded textures
  12087. * @returns an array containing all loaded textures
  12088. */
  12089. Engine.prototype.getLoadedTexturesCache = function () {
  12090. return this._internalTexturesCache;
  12091. };
  12092. /**
  12093. * Gets the object containing all engine capabilities
  12094. * @returns the EngineCapabilities object
  12095. */
  12096. Engine.prototype.getCaps = function () {
  12097. return this._caps;
  12098. };
  12099. Object.defineProperty(Engine.prototype, "drawCalls", {
  12100. /** @ignore */
  12101. get: function () {
  12102. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12103. return 0;
  12104. },
  12105. enumerable: true,
  12106. configurable: true
  12107. });
  12108. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12109. /** @ignore */
  12110. get: function () {
  12111. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12112. return null;
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. /**
  12118. * Gets the current depth function
  12119. * @returns a number defining the depth function
  12120. */
  12121. Engine.prototype.getDepthFunction = function () {
  12122. return this._depthCullingState.depthFunc;
  12123. };
  12124. /**
  12125. * Sets the current depth function
  12126. * @param depthFunc defines the function to use
  12127. */
  12128. Engine.prototype.setDepthFunction = function (depthFunc) {
  12129. this._depthCullingState.depthFunc = depthFunc;
  12130. };
  12131. /**
  12132. * Sets the current depth function to GREATER
  12133. */
  12134. Engine.prototype.setDepthFunctionToGreater = function () {
  12135. this._depthCullingState.depthFunc = this._gl.GREATER;
  12136. };
  12137. /**
  12138. * Sets the current depth function to GEQUAL
  12139. */
  12140. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12141. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12142. };
  12143. /**
  12144. * Sets the current depth function to LESS
  12145. */
  12146. Engine.prototype.setDepthFunctionToLess = function () {
  12147. this._depthCullingState.depthFunc = this._gl.LESS;
  12148. };
  12149. /**
  12150. * Sets the current depth function to LEQUAL
  12151. */
  12152. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12153. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12154. };
  12155. /**
  12156. * Gets a boolean indicating if stencil buffer is enabled
  12157. * @returns the current stencil buffer state
  12158. */
  12159. Engine.prototype.getStencilBuffer = function () {
  12160. return this._stencilState.stencilTest;
  12161. };
  12162. /**
  12163. * Enable or disable the stencil buffer
  12164. * @param enable defines if the stencil buffer must be enabled or disabled
  12165. */
  12166. Engine.prototype.setStencilBuffer = function (enable) {
  12167. this._stencilState.stencilTest = enable;
  12168. };
  12169. /**
  12170. * Gets the current stencil mask
  12171. * @returns a number defining the new stencil mask to use
  12172. */
  12173. Engine.prototype.getStencilMask = function () {
  12174. return this._stencilState.stencilMask;
  12175. };
  12176. /**
  12177. * Sets the current stencil mask
  12178. * @param mask defines the new stencil mask to use
  12179. */
  12180. Engine.prototype.setStencilMask = function (mask) {
  12181. this._stencilState.stencilMask = mask;
  12182. };
  12183. /**
  12184. * Gets the current stencil function
  12185. * @returns a number defining the stencil function to use
  12186. */
  12187. Engine.prototype.getStencilFunction = function () {
  12188. return this._stencilState.stencilFunc;
  12189. };
  12190. /**
  12191. * Gets the current stencil reference value
  12192. * @returns a number defining the stencil reference value to use
  12193. */
  12194. Engine.prototype.getStencilFunctionReference = function () {
  12195. return this._stencilState.stencilFuncRef;
  12196. };
  12197. /**
  12198. * Gets the current stencil mask
  12199. * @returns a number defining the stencil mask to use
  12200. */
  12201. Engine.prototype.getStencilFunctionMask = function () {
  12202. return this._stencilState.stencilFuncMask;
  12203. };
  12204. /**
  12205. * Sets the current stencil function
  12206. * @param stencilFunc defines the new stencil function to use
  12207. */
  12208. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12209. this._stencilState.stencilFunc = stencilFunc;
  12210. };
  12211. /**
  12212. * Sets the current stencil reference
  12213. * @param reference defines the new stencil reference to use
  12214. */
  12215. Engine.prototype.setStencilFunctionReference = function (reference) {
  12216. this._stencilState.stencilFuncRef = reference;
  12217. };
  12218. /**
  12219. * Sets the current stencil mask
  12220. * @param mask defines the new stencil mask to use
  12221. */
  12222. Engine.prototype.setStencilFunctionMask = function (mask) {
  12223. this._stencilState.stencilFuncMask = mask;
  12224. };
  12225. /**
  12226. * Gets the current stencil operation when stencil fails
  12227. * @returns a number defining stencil operation to use when stencil fails
  12228. */
  12229. Engine.prototype.getStencilOperationFail = function () {
  12230. return this._stencilState.stencilOpStencilFail;
  12231. };
  12232. /**
  12233. * Gets the current stencil operation when depth fails
  12234. * @returns a number defining stencil operation to use when depth fails
  12235. */
  12236. Engine.prototype.getStencilOperationDepthFail = function () {
  12237. return this._stencilState.stencilOpDepthFail;
  12238. };
  12239. /**
  12240. * Gets the current stencil operation when stencil passes
  12241. * @returns a number defining stencil operation to use when stencil passes
  12242. */
  12243. Engine.prototype.getStencilOperationPass = function () {
  12244. return this._stencilState.stencilOpStencilDepthPass;
  12245. };
  12246. /**
  12247. * Sets the stencil operation to use when stencil fails
  12248. * @param operation defines the stencil operation to use when stencil fails
  12249. */
  12250. Engine.prototype.setStencilOperationFail = function (operation) {
  12251. this._stencilState.stencilOpStencilFail = operation;
  12252. };
  12253. /**
  12254. * Sets the stencil operation to use when depth fails
  12255. * @param operation defines the stencil operation to use when depth fails
  12256. */
  12257. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12258. this._stencilState.stencilOpDepthFail = operation;
  12259. };
  12260. /**
  12261. * Sets the stencil operation to use when stencil passes
  12262. * @param operation defines the stencil operation to use when stencil passes
  12263. */
  12264. Engine.prototype.setStencilOperationPass = function (operation) {
  12265. this._stencilState.stencilOpStencilDepthPass = operation;
  12266. };
  12267. /**
  12268. * Sets a boolean indicating if the dithering state is enabled or disabled
  12269. * @param value defines the dithering state
  12270. */
  12271. Engine.prototype.setDitheringState = function (value) {
  12272. if (value) {
  12273. this._gl.enable(this._gl.DITHER);
  12274. }
  12275. else {
  12276. this._gl.disable(this._gl.DITHER);
  12277. }
  12278. };
  12279. /**
  12280. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12281. * @param value defines the rasterizer state
  12282. */
  12283. Engine.prototype.setRasterizerState = function (value) {
  12284. if (value) {
  12285. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12286. }
  12287. else {
  12288. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12289. }
  12290. };
  12291. /**
  12292. * stop executing a render loop function and remove it from the execution array
  12293. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12294. */
  12295. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12296. if (!renderFunction) {
  12297. this._activeRenderLoops = [];
  12298. return;
  12299. }
  12300. var index = this._activeRenderLoops.indexOf(renderFunction);
  12301. if (index >= 0) {
  12302. this._activeRenderLoops.splice(index, 1);
  12303. }
  12304. };
  12305. /** @ignore */
  12306. Engine.prototype._renderLoop = function () {
  12307. if (!this._contextWasLost) {
  12308. var shouldRender = true;
  12309. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12310. shouldRender = false;
  12311. }
  12312. if (shouldRender) {
  12313. // Start new frame
  12314. this.beginFrame();
  12315. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12316. var renderFunction = this._activeRenderLoops[index];
  12317. renderFunction();
  12318. }
  12319. // Present
  12320. this.endFrame();
  12321. }
  12322. }
  12323. if (this._activeRenderLoops.length > 0) {
  12324. // Register new frame
  12325. var requester = null;
  12326. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12327. requester = this._vrDisplay;
  12328. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12329. }
  12330. else {
  12331. this._renderingQueueLaunched = false;
  12332. }
  12333. };
  12334. /**
  12335. * Register and execute a render loop. The engine can have more than one render function
  12336. * @param renderFunction defines the function to continuously execute
  12337. */
  12338. Engine.prototype.runRenderLoop = function (renderFunction) {
  12339. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12340. return;
  12341. }
  12342. this._activeRenderLoops.push(renderFunction);
  12343. if (!this._renderingQueueLaunched) {
  12344. this._renderingQueueLaunched = true;
  12345. this._bindedRenderFunction = this._renderLoop.bind(this);
  12346. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12347. }
  12348. };
  12349. /**
  12350. * Toggle full screen mode
  12351. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12352. * @param options defines an option object to be sent to the requestFullscreen function
  12353. */
  12354. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12355. if (this.isFullscreen) {
  12356. BABYLON.Tools.ExitFullscreen();
  12357. }
  12358. else {
  12359. this._pointerLockRequested = requestPointerLock;
  12360. if (this._renderingCanvas) {
  12361. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12362. }
  12363. }
  12364. };
  12365. /**
  12366. * Clear the current render buffer or the current render target (if any is set up)
  12367. * @param color defines the color to use
  12368. * @param backBuffer defines if the back buffer must be cleared
  12369. * @param depth defines if the depth buffer must be cleared
  12370. * @param stencil defines if the stencil buffer must be cleared
  12371. */
  12372. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12373. if (stencil === void 0) { stencil = false; }
  12374. this.applyStates();
  12375. var mode = 0;
  12376. if (backBuffer && color) {
  12377. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12378. mode |= this._gl.COLOR_BUFFER_BIT;
  12379. }
  12380. if (depth) {
  12381. this._gl.clearDepth(1.0);
  12382. mode |= this._gl.DEPTH_BUFFER_BIT;
  12383. }
  12384. if (stencil) {
  12385. this._gl.clearStencil(0);
  12386. mode |= this._gl.STENCIL_BUFFER_BIT;
  12387. }
  12388. this._gl.clear(mode);
  12389. };
  12390. /**
  12391. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12392. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12393. * @param y defines the y-coordinate of the corner of the clear rectangle
  12394. * @param width defines the width of the clear rectangle
  12395. * @param height defines the height of the clear rectangle
  12396. * @param clearColor defines the clear color
  12397. */
  12398. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12399. var gl = this._gl;
  12400. // Save state
  12401. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12402. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12403. // Change state
  12404. gl.enable(gl.SCISSOR_TEST);
  12405. gl.scissor(x, y, width, height);
  12406. // Clear
  12407. this.clear(clearColor, true, true, true);
  12408. // Restore state
  12409. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12410. if (curScissor === true) {
  12411. gl.enable(gl.SCISSOR_TEST);
  12412. }
  12413. else {
  12414. gl.disable(gl.SCISSOR_TEST);
  12415. }
  12416. };
  12417. /**
  12418. * Set the WebGL's viewport
  12419. * @param viewport defines the viewport element to be used
  12420. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12421. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12422. */
  12423. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12424. var width = requiredWidth || this.getRenderWidth();
  12425. var height = requiredHeight || this.getRenderHeight();
  12426. var x = viewport.x || 0;
  12427. var y = viewport.y || 0;
  12428. this._cachedViewport = viewport;
  12429. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12430. };
  12431. /**
  12432. * Directly set the WebGL Viewport
  12433. * @param x defines the x coordinate of the viewport (in screen space)
  12434. * @param y defines the y coordinate of the viewport (in screen space)
  12435. * @param width defines the width of the viewport (in screen space)
  12436. * @param height defines the height of the viewport (in screen space)
  12437. * @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
  12438. */
  12439. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12440. var currentViewport = this._cachedViewport;
  12441. this._cachedViewport = null;
  12442. this._gl.viewport(x, y, width, height);
  12443. return currentViewport;
  12444. };
  12445. /**
  12446. * Begin a new frame
  12447. */
  12448. Engine.prototype.beginFrame = function () {
  12449. this.onBeginFrameObservable.notifyObservers(this);
  12450. this._measureFps();
  12451. };
  12452. /**
  12453. * Enf the current frame
  12454. */
  12455. Engine.prototype.endFrame = function () {
  12456. // Force a flush in case we are using a bad OS.
  12457. if (this._badOS) {
  12458. this.flushFramebuffer();
  12459. }
  12460. // Submit frame to the vr device, if enabled
  12461. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12462. // TODO: We should only submit the frame if we read frameData successfully.
  12463. this._vrDisplay.submitFrame();
  12464. }
  12465. this.onEndFrameObservable.notifyObservers(this);
  12466. };
  12467. /**
  12468. * Resize the view according to the canvas' size
  12469. */
  12470. Engine.prototype.resize = function () {
  12471. // We're not resizing the size of the canvas while in VR mode & presenting
  12472. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12473. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12474. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12475. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12476. }
  12477. };
  12478. /**
  12479. * Force a specific size of the canvas
  12480. * @param width defines the new canvas' width
  12481. * @param height defines the new canvas' height
  12482. */
  12483. Engine.prototype.setSize = function (width, height) {
  12484. if (!this._renderingCanvas) {
  12485. return;
  12486. }
  12487. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12488. return;
  12489. }
  12490. this._renderingCanvas.width = width;
  12491. this._renderingCanvas.height = height;
  12492. for (var index = 0; index < this.scenes.length; index++) {
  12493. var scene = this.scenes[index];
  12494. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12495. var cam = scene.cameras[camIndex];
  12496. cam._currentRenderId = 0;
  12497. }
  12498. }
  12499. if (this.onResizeObservable.hasObservers) {
  12500. this.onResizeObservable.notifyObservers(this);
  12501. }
  12502. };
  12503. // WebVR functions
  12504. /**
  12505. * Gets a boolean indicating if a webVR device was detected
  12506. * @returns true if a webVR device was detected
  12507. */
  12508. Engine.prototype.isVRDevicePresent = function () {
  12509. return !!this._vrDisplay;
  12510. };
  12511. /**
  12512. * Gets the current webVR device
  12513. * @returns the current webVR device (or null)
  12514. */
  12515. Engine.prototype.getVRDevice = function () {
  12516. return this._vrDisplay;
  12517. };
  12518. /**
  12519. * Initializes a webVR display and starts listening to display change events
  12520. * The onVRDisplayChangedObservable will be notified upon these changes
  12521. * @returns The onVRDisplayChangedObservable
  12522. */
  12523. Engine.prototype.initWebVR = function () {
  12524. this.initWebVRAsync();
  12525. return this.onVRDisplayChangedObservable;
  12526. };
  12527. /**
  12528. * Initializes a webVR display and starts listening to display change events
  12529. * The onVRDisplayChangedObservable will be notified upon these changes
  12530. * @returns A promise containing a VRDisplay and if vr is supported
  12531. */
  12532. Engine.prototype.initWebVRAsync = function () {
  12533. var _this = this;
  12534. var notifyObservers = function () {
  12535. var eventArgs = {
  12536. vrDisplay: _this._vrDisplay,
  12537. vrSupported: _this._vrSupported
  12538. };
  12539. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12540. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12541. };
  12542. if (!this._onVrDisplayConnect) {
  12543. this._onVrDisplayConnect = function (event) {
  12544. _this._vrDisplay = event.display;
  12545. notifyObservers();
  12546. };
  12547. this._onVrDisplayDisconnect = function () {
  12548. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12549. _this._vrDisplay = undefined;
  12550. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12551. notifyObservers();
  12552. };
  12553. this._onVrDisplayPresentChange = function () {
  12554. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12555. };
  12556. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12557. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12558. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12559. }
  12560. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12561. this._webVRInitPromise.then(notifyObservers);
  12562. return this._webVRInitPromise;
  12563. };
  12564. /**
  12565. * Call this function to switch to webVR mode
  12566. * Will do nothing if webVR is not supported or if there is no webVR device
  12567. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12568. */
  12569. Engine.prototype.enableVR = function () {
  12570. var _this = this;
  12571. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12572. var onResolved = function () {
  12573. _this.onVRRequestPresentComplete.notifyObservers(true);
  12574. _this._onVRFullScreenTriggered();
  12575. };
  12576. var onRejected = function () {
  12577. _this.onVRRequestPresentComplete.notifyObservers(false);
  12578. };
  12579. this.onVRRequestPresentStart.notifyObservers(this);
  12580. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12581. }
  12582. };
  12583. /**
  12584. * Call this function to leave webVR mode
  12585. * Will do nothing if webVR is not supported or if there is no webVR device
  12586. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12587. */
  12588. Engine.prototype.disableVR = function () {
  12589. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12590. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12591. }
  12592. };
  12593. Engine.prototype._getVRDisplaysAsync = function () {
  12594. var _this = this;
  12595. return new Promise(function (res, rej) {
  12596. if (navigator.getVRDisplays) {
  12597. navigator.getVRDisplays().then(function (devices) {
  12598. _this._vrSupported = true;
  12599. // note that devices may actually be an empty array. This is fine;
  12600. // we expect this._vrDisplay to be undefined in this case.
  12601. _this._vrDisplay = devices[0];
  12602. res({
  12603. vrDisplay: _this._vrDisplay,
  12604. vrSupported: _this._vrSupported
  12605. });
  12606. });
  12607. }
  12608. else {
  12609. _this._vrDisplay = undefined;
  12610. _this._vrSupported = false;
  12611. res({
  12612. vrDisplay: _this._vrDisplay,
  12613. vrSupported: _this._vrSupported
  12614. });
  12615. }
  12616. });
  12617. };
  12618. /**
  12619. * Binds the frame buffer to the specified texture.
  12620. * @param texture The texture to render to or null for the default canvas
  12621. * @param faceIndex The face of the texture to render to in case of cube texture
  12622. * @param requiredWidth The width of the target to render to
  12623. * @param requiredHeight The height of the target to render to
  12624. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12625. * @param depthStencilTexture The depth stencil texture to use to render
  12626. */
  12627. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12628. if (this._currentRenderTarget) {
  12629. this.unBindFramebuffer(this._currentRenderTarget);
  12630. }
  12631. this._currentRenderTarget = texture;
  12632. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12633. var gl = this._gl;
  12634. if (texture.isCube) {
  12635. if (faceIndex === undefined) {
  12636. faceIndex = 0;
  12637. }
  12638. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12639. if (depthStencilTexture) {
  12640. if (depthStencilTexture._generateStencilBuffer) {
  12641. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12642. }
  12643. else {
  12644. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12645. }
  12646. }
  12647. }
  12648. if (this._cachedViewport && !forceFullscreenViewport) {
  12649. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12650. }
  12651. else {
  12652. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12653. }
  12654. this.wipeCaches();
  12655. };
  12656. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12657. if (this._currentFramebuffer !== framebuffer) {
  12658. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12659. this._currentFramebuffer = framebuffer;
  12660. }
  12661. };
  12662. /**
  12663. * Unbind the current render target texture from the webGL context
  12664. * @param texture defines the render target texture to unbind
  12665. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12666. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12667. */
  12668. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12669. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12670. this._currentRenderTarget = null;
  12671. // If MSAA, we need to bitblt back to main texture
  12672. var gl = this._gl;
  12673. if (texture._MSAAFramebuffer) {
  12674. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12675. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12676. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12677. }
  12678. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12679. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12680. gl.generateMipmap(gl.TEXTURE_2D);
  12681. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12682. }
  12683. if (onBeforeUnbind) {
  12684. if (texture._MSAAFramebuffer) {
  12685. // Bind the correct framebuffer
  12686. this.bindUnboundFramebuffer(texture._framebuffer);
  12687. }
  12688. onBeforeUnbind();
  12689. }
  12690. this.bindUnboundFramebuffer(null);
  12691. };
  12692. /**
  12693. * Unbind a list of render target textures from the webGL context
  12694. * This is used only when drawBuffer extension or webGL2 are active
  12695. * @param textures defines the render target textures to unbind
  12696. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12697. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12698. */
  12699. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12700. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12701. this._currentRenderTarget = null;
  12702. // If MSAA, we need to bitblt back to main texture
  12703. var gl = this._gl;
  12704. if (textures[0]._MSAAFramebuffer) {
  12705. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12706. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12707. var attachments = textures[0]._attachments;
  12708. if (!attachments) {
  12709. attachments = new Array(textures.length);
  12710. textures[0]._attachments = attachments;
  12711. }
  12712. for (var i = 0; i < textures.length; i++) {
  12713. var texture = textures[i];
  12714. for (var j = 0; j < attachments.length; j++) {
  12715. attachments[j] = gl.NONE;
  12716. }
  12717. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12718. gl.readBuffer(attachments[i]);
  12719. gl.drawBuffers(attachments);
  12720. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12721. }
  12722. for (var i = 0; i < attachments.length; i++) {
  12723. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12724. }
  12725. gl.drawBuffers(attachments);
  12726. }
  12727. for (var i = 0; i < textures.length; i++) {
  12728. var texture = textures[i];
  12729. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12730. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12731. gl.generateMipmap(gl.TEXTURE_2D);
  12732. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12733. }
  12734. }
  12735. if (onBeforeUnbind) {
  12736. if (textures[0]._MSAAFramebuffer) {
  12737. // Bind the correct framebuffer
  12738. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12739. }
  12740. onBeforeUnbind();
  12741. }
  12742. this.bindUnboundFramebuffer(null);
  12743. };
  12744. /**
  12745. * Force the mipmap generation for the given render target texture
  12746. * @param texture defines the render target texture to use
  12747. */
  12748. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12749. if (texture.generateMipMaps) {
  12750. var gl = this._gl;
  12751. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12752. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12753. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12754. }
  12755. };
  12756. /**
  12757. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12758. */
  12759. Engine.prototype.flushFramebuffer = function () {
  12760. this._gl.flush();
  12761. };
  12762. /**
  12763. * Unbind the current render target and bind the default framebuffer
  12764. */
  12765. Engine.prototype.restoreDefaultFramebuffer = function () {
  12766. if (this._currentRenderTarget) {
  12767. this.unBindFramebuffer(this._currentRenderTarget);
  12768. }
  12769. else {
  12770. this.bindUnboundFramebuffer(null);
  12771. }
  12772. if (this._cachedViewport) {
  12773. this.setViewport(this._cachedViewport);
  12774. }
  12775. this.wipeCaches();
  12776. };
  12777. // UBOs
  12778. /**
  12779. * Create an uniform buffer
  12780. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12781. * @param elements defines the content of the uniform buffer
  12782. * @returns the webGL uniform buffer
  12783. */
  12784. Engine.prototype.createUniformBuffer = function (elements) {
  12785. var ubo = this._gl.createBuffer();
  12786. if (!ubo) {
  12787. throw new Error("Unable to create uniform buffer");
  12788. }
  12789. this.bindUniformBuffer(ubo);
  12790. if (elements instanceof Float32Array) {
  12791. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12792. }
  12793. else {
  12794. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12795. }
  12796. this.bindUniformBuffer(null);
  12797. ubo.references = 1;
  12798. return ubo;
  12799. };
  12800. /**
  12801. * Create a dynamic uniform buffer
  12802. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12803. * @param elements defines the content of the uniform buffer
  12804. * @returns the webGL uniform buffer
  12805. */
  12806. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12807. var ubo = this._gl.createBuffer();
  12808. if (!ubo) {
  12809. throw new Error("Unable to create dynamic uniform buffer");
  12810. }
  12811. this.bindUniformBuffer(ubo);
  12812. if (elements instanceof Float32Array) {
  12813. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12814. }
  12815. else {
  12816. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12817. }
  12818. this.bindUniformBuffer(null);
  12819. ubo.references = 1;
  12820. return ubo;
  12821. };
  12822. /**
  12823. * Update an existing uniform buffer
  12824. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12825. * @param uniformBuffer defines the target uniform buffer
  12826. * @param elements defines the content to update
  12827. * @param offset defines the offset in the uniform buffer where update should start
  12828. * @param count defines the size of the data to update
  12829. */
  12830. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12831. this.bindUniformBuffer(uniformBuffer);
  12832. if (offset === undefined) {
  12833. offset = 0;
  12834. }
  12835. if (count === undefined) {
  12836. if (elements instanceof Float32Array) {
  12837. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12838. }
  12839. else {
  12840. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12841. }
  12842. }
  12843. else {
  12844. if (elements instanceof Float32Array) {
  12845. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12846. }
  12847. else {
  12848. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12849. }
  12850. }
  12851. this.bindUniformBuffer(null);
  12852. };
  12853. // VBOs
  12854. Engine.prototype._resetVertexBufferBinding = function () {
  12855. this.bindArrayBuffer(null);
  12856. this._cachedVertexBuffers = null;
  12857. };
  12858. /**
  12859. * Creates a vertex buffer
  12860. * @param data the data for the vertex buffer
  12861. * @returns the new WebGL static buffer
  12862. */
  12863. Engine.prototype.createVertexBuffer = function (data) {
  12864. var vbo = this._gl.createBuffer();
  12865. if (!vbo) {
  12866. throw new Error("Unable to create vertex buffer");
  12867. }
  12868. this.bindArrayBuffer(vbo);
  12869. if (data instanceof Array) {
  12870. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12871. }
  12872. else {
  12873. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12874. }
  12875. this._resetVertexBufferBinding();
  12876. vbo.references = 1;
  12877. return vbo;
  12878. };
  12879. /**
  12880. * Creates a dynamic vertex buffer
  12881. * @param data the data for the dynamic vertex buffer
  12882. * @returns the new WebGL dynamic buffer
  12883. */
  12884. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12885. var vbo = this._gl.createBuffer();
  12886. if (!vbo) {
  12887. throw new Error("Unable to create dynamic vertex buffer");
  12888. }
  12889. this.bindArrayBuffer(vbo);
  12890. if (data instanceof Array) {
  12891. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12892. }
  12893. else {
  12894. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12895. }
  12896. this._resetVertexBufferBinding();
  12897. vbo.references = 1;
  12898. return vbo;
  12899. };
  12900. /**
  12901. * Update a dynamic index buffer
  12902. * @param indexBuffer defines the target index buffer
  12903. * @param indices defines the data to update
  12904. * @param offset defines the offset in the target index buffer where update should start
  12905. */
  12906. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12907. if (offset === void 0) { offset = 0; }
  12908. // Force cache update
  12909. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12910. this.bindIndexBuffer(indexBuffer);
  12911. var arrayBuffer;
  12912. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12913. arrayBuffer = indices;
  12914. }
  12915. else {
  12916. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12917. }
  12918. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12919. this._resetIndexBufferBinding();
  12920. };
  12921. /**
  12922. * Updates a dynamic vertex buffer.
  12923. * @param vertexBuffer the vertex buffer to update
  12924. * @param data the data used to update the vertex buffer
  12925. * @param byteOffset the byte offset of the data
  12926. * @param byteLength the byte length of the data
  12927. */
  12928. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  12929. this.bindArrayBuffer(vertexBuffer);
  12930. if (byteOffset === undefined) {
  12931. byteOffset = 0;
  12932. }
  12933. if (byteLength === undefined) {
  12934. if (data instanceof Array) {
  12935. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  12936. }
  12937. else {
  12938. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  12939. }
  12940. }
  12941. else {
  12942. if (data instanceof Array) {
  12943. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  12944. }
  12945. else {
  12946. if (data instanceof ArrayBuffer) {
  12947. data = new Uint8Array(data, byteOffset, byteLength);
  12948. }
  12949. else {
  12950. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  12951. }
  12952. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12953. }
  12954. }
  12955. this._resetVertexBufferBinding();
  12956. };
  12957. Engine.prototype._resetIndexBufferBinding = function () {
  12958. this.bindIndexBuffer(null);
  12959. this._cachedIndexBuffer = null;
  12960. };
  12961. /**
  12962. * Creates a new index buffer
  12963. * @param indices defines the content of the index buffer
  12964. * @param updatable defines if the index buffer must be updatable
  12965. * @returns a new webGL buffer
  12966. */
  12967. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12968. var vbo = this._gl.createBuffer();
  12969. if (!vbo) {
  12970. throw new Error("Unable to create index buffer");
  12971. }
  12972. this.bindIndexBuffer(vbo);
  12973. // Check for 32 bits indices
  12974. var arrayBuffer;
  12975. var need32Bits = false;
  12976. if (indices instanceof Uint16Array) {
  12977. arrayBuffer = indices;
  12978. }
  12979. else {
  12980. //check 32 bit support
  12981. if (this._caps.uintIndices) {
  12982. if (indices instanceof Uint32Array) {
  12983. arrayBuffer = indices;
  12984. need32Bits = true;
  12985. }
  12986. else {
  12987. //number[] or Int32Array, check if 32 bit is necessary
  12988. for (var index = 0; index < indices.length; index++) {
  12989. if (indices[index] > 65535) {
  12990. need32Bits = true;
  12991. break;
  12992. }
  12993. }
  12994. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12995. }
  12996. }
  12997. else {
  12998. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12999. arrayBuffer = new Uint16Array(indices);
  13000. }
  13001. }
  13002. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13003. this._resetIndexBufferBinding();
  13004. vbo.references = 1;
  13005. vbo.is32Bits = need32Bits;
  13006. return vbo;
  13007. };
  13008. /**
  13009. * Bind a webGL buffer to the webGL context
  13010. * @param buffer defines the buffer to bind
  13011. */
  13012. Engine.prototype.bindArrayBuffer = function (buffer) {
  13013. if (!this._vaoRecordInProgress) {
  13014. this._unbindVertexArrayObject();
  13015. }
  13016. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13017. };
  13018. /**
  13019. * Bind an uniform buffer to the current webGL context
  13020. * @param buffer defines the buffer to bind
  13021. */
  13022. Engine.prototype.bindUniformBuffer = function (buffer) {
  13023. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13024. };
  13025. /**
  13026. * Bind a buffer to the current webGL context at a given location
  13027. * @param buffer defines the buffer to bind
  13028. * @param location defines the index where to bind the buffer
  13029. */
  13030. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13031. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13032. };
  13033. /**
  13034. * Bind a specific block at a given index in a specific shader program
  13035. * @param shaderProgram defines the shader program
  13036. * @param blockName defines the block name
  13037. * @param index defines the index where to bind the block
  13038. */
  13039. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13040. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13041. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13042. };
  13043. ;
  13044. Engine.prototype.bindIndexBuffer = function (buffer) {
  13045. if (!this._vaoRecordInProgress) {
  13046. this._unbindVertexArrayObject();
  13047. }
  13048. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13049. };
  13050. Engine.prototype.bindBuffer = function (buffer, target) {
  13051. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13052. this._gl.bindBuffer(target, buffer);
  13053. this._currentBoundBuffer[target] = buffer;
  13054. }
  13055. };
  13056. /**
  13057. * update the bound buffer with the given data
  13058. * @param data defines the data to update
  13059. */
  13060. Engine.prototype.updateArrayBuffer = function (data) {
  13061. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13062. };
  13063. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13064. var pointer = this._currentBufferPointers[indx];
  13065. var changed = false;
  13066. if (!pointer.active) {
  13067. changed = true;
  13068. pointer.active = true;
  13069. pointer.index = indx;
  13070. pointer.size = size;
  13071. pointer.type = type;
  13072. pointer.normalized = normalized;
  13073. pointer.stride = stride;
  13074. pointer.offset = offset;
  13075. pointer.buffer = buffer;
  13076. }
  13077. else {
  13078. if (pointer.buffer !== buffer) {
  13079. pointer.buffer = buffer;
  13080. changed = true;
  13081. }
  13082. if (pointer.size !== size) {
  13083. pointer.size = size;
  13084. changed = true;
  13085. }
  13086. if (pointer.type !== type) {
  13087. pointer.type = type;
  13088. changed = true;
  13089. }
  13090. if (pointer.normalized !== normalized) {
  13091. pointer.normalized = normalized;
  13092. changed = true;
  13093. }
  13094. if (pointer.stride !== stride) {
  13095. pointer.stride = stride;
  13096. changed = true;
  13097. }
  13098. if (pointer.offset !== offset) {
  13099. pointer.offset = offset;
  13100. changed = true;
  13101. }
  13102. }
  13103. if (changed || this._vaoRecordInProgress) {
  13104. this.bindArrayBuffer(buffer);
  13105. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13106. }
  13107. };
  13108. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13109. if (indexBuffer == null) {
  13110. return;
  13111. }
  13112. if (this._cachedIndexBuffer !== indexBuffer) {
  13113. this._cachedIndexBuffer = indexBuffer;
  13114. this.bindIndexBuffer(indexBuffer);
  13115. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13116. }
  13117. };
  13118. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13119. var attributes = effect.getAttributesNames();
  13120. if (!this._vaoRecordInProgress) {
  13121. this._unbindVertexArrayObject();
  13122. }
  13123. this.unbindAllAttributes();
  13124. for (var index = 0; index < attributes.length; index++) {
  13125. var order = effect.getAttributeLocation(index);
  13126. if (order >= 0) {
  13127. var vertexBuffer = vertexBuffers[attributes[index]];
  13128. if (!vertexBuffer) {
  13129. continue;
  13130. }
  13131. this._gl.enableVertexAttribArray(order);
  13132. if (!this._vaoRecordInProgress) {
  13133. this._vertexAttribArraysEnabled[order] = true;
  13134. }
  13135. var buffer = vertexBuffer.getBuffer();
  13136. if (buffer) {
  13137. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13138. if (vertexBuffer.getIsInstanced()) {
  13139. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13140. if (!this._vaoRecordInProgress) {
  13141. this._currentInstanceLocations.push(order);
  13142. this._currentInstanceBuffers.push(buffer);
  13143. }
  13144. }
  13145. }
  13146. }
  13147. }
  13148. };
  13149. /**
  13150. * Records a vertex array object
  13151. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13152. * @param vertexBuffers defines the list of vertex buffers to store
  13153. * @param indexBuffer defines the index buffer to store
  13154. * @param effect defines the effect to store
  13155. * @returns the new vertex array object
  13156. */
  13157. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13158. var vao = this._gl.createVertexArray();
  13159. this._vaoRecordInProgress = true;
  13160. this._gl.bindVertexArray(vao);
  13161. this._mustWipeVertexAttributes = true;
  13162. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13163. this.bindIndexBuffer(indexBuffer);
  13164. this._vaoRecordInProgress = false;
  13165. this._gl.bindVertexArray(null);
  13166. return vao;
  13167. };
  13168. /**
  13169. * Bind a specific vertex array object
  13170. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13171. * @param vertexArrayObject defines the vertex array object to bind
  13172. * @param indexBuffer defines the index buffer to bind
  13173. */
  13174. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13175. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13176. this._cachedVertexArrayObject = vertexArrayObject;
  13177. this._gl.bindVertexArray(vertexArrayObject);
  13178. this._cachedVertexBuffers = null;
  13179. this._cachedIndexBuffer = null;
  13180. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13181. this._mustWipeVertexAttributes = true;
  13182. }
  13183. };
  13184. /**
  13185. * Bind webGl buffers directly to the webGL context
  13186. * @param vertexBuffer defines the vertex buffer to bind
  13187. * @param indexBuffer defines the index buffer to bind
  13188. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13189. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13190. * @param effect defines the effect associated with the vertex buffer
  13191. */
  13192. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13193. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13194. this._cachedVertexBuffers = vertexBuffer;
  13195. this._cachedEffectForVertexBuffers = effect;
  13196. var attributesCount = effect.getAttributesCount();
  13197. this._unbindVertexArrayObject();
  13198. this.unbindAllAttributes();
  13199. var offset = 0;
  13200. for (var index = 0; index < attributesCount; index++) {
  13201. if (index < vertexDeclaration.length) {
  13202. var order = effect.getAttributeLocation(index);
  13203. if (order >= 0) {
  13204. this._gl.enableVertexAttribArray(order);
  13205. this._vertexAttribArraysEnabled[order] = true;
  13206. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13207. }
  13208. offset += vertexDeclaration[index] * 4;
  13209. }
  13210. }
  13211. }
  13212. this._bindIndexBufferWithCache(indexBuffer);
  13213. };
  13214. Engine.prototype._unbindVertexArrayObject = function () {
  13215. if (!this._cachedVertexArrayObject) {
  13216. return;
  13217. }
  13218. this._cachedVertexArrayObject = null;
  13219. this._gl.bindVertexArray(null);
  13220. };
  13221. /**
  13222. * Bind a list of vertex buffers to the webGL context
  13223. * @param vertexBuffers defines the list of vertex buffers to bind
  13224. * @param indexBuffer defines the index buffer to bind
  13225. * @param effect defines the effect associated with the vertex buffers
  13226. */
  13227. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13228. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13229. this._cachedVertexBuffers = vertexBuffers;
  13230. this._cachedEffectForVertexBuffers = effect;
  13231. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13232. }
  13233. this._bindIndexBufferWithCache(indexBuffer);
  13234. };
  13235. /**
  13236. * Unbind all instance attributes
  13237. */
  13238. Engine.prototype.unbindInstanceAttributes = function () {
  13239. var boundBuffer;
  13240. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13241. var instancesBuffer = this._currentInstanceBuffers[i];
  13242. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13243. boundBuffer = instancesBuffer;
  13244. this.bindArrayBuffer(instancesBuffer);
  13245. }
  13246. var offsetLocation = this._currentInstanceLocations[i];
  13247. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13248. }
  13249. this._currentInstanceBuffers.length = 0;
  13250. this._currentInstanceLocations.length = 0;
  13251. };
  13252. /**
  13253. * Release and free the memory of a vertex array object
  13254. * @param vao defines the vertex array object to delete
  13255. */
  13256. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13257. this._gl.deleteVertexArray(vao);
  13258. };
  13259. /** @ignore */
  13260. Engine.prototype._releaseBuffer = function (buffer) {
  13261. buffer.references--;
  13262. if (buffer.references === 0) {
  13263. this._gl.deleteBuffer(buffer);
  13264. return true;
  13265. }
  13266. return false;
  13267. };
  13268. /**
  13269. * Creates a webGL buffer to use with instanciation
  13270. * @param capacity defines the size of the buffer
  13271. * @returns the webGL buffer
  13272. */
  13273. Engine.prototype.createInstancesBuffer = function (capacity) {
  13274. var buffer = this._gl.createBuffer();
  13275. if (!buffer) {
  13276. throw new Error("Unable to create instance buffer");
  13277. }
  13278. buffer.capacity = capacity;
  13279. this.bindArrayBuffer(buffer);
  13280. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13281. return buffer;
  13282. };
  13283. /**
  13284. * Delete a webGL buffer used with instanciation
  13285. * @param buffer defines the webGL buffer to delete
  13286. */
  13287. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13288. this._gl.deleteBuffer(buffer);
  13289. };
  13290. /**
  13291. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13292. * @param instancesBuffer defines the webGL buffer to update and bind
  13293. * @param data defines the data to store in the buffer
  13294. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13295. */
  13296. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13297. this.bindArrayBuffer(instancesBuffer);
  13298. if (data) {
  13299. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13300. }
  13301. if (offsetLocations[0].index !== undefined) {
  13302. var stride = 0;
  13303. for (var i = 0; i < offsetLocations.length; i++) {
  13304. var ai = offsetLocations[i];
  13305. stride += ai.attributeSize * 4;
  13306. }
  13307. for (var i = 0; i < offsetLocations.length; i++) {
  13308. var ai = offsetLocations[i];
  13309. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13310. this._gl.enableVertexAttribArray(ai.index);
  13311. this._vertexAttribArraysEnabled[ai.index] = true;
  13312. }
  13313. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13314. this._gl.vertexAttribDivisor(ai.index, 1);
  13315. this._currentInstanceLocations.push(ai.index);
  13316. this._currentInstanceBuffers.push(instancesBuffer);
  13317. }
  13318. }
  13319. else {
  13320. for (var index = 0; index < 4; index++) {
  13321. var offsetLocation = offsetLocations[index];
  13322. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13323. this._gl.enableVertexAttribArray(offsetLocation);
  13324. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13325. }
  13326. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13327. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13328. this._currentInstanceLocations.push(offsetLocation);
  13329. this._currentInstanceBuffers.push(instancesBuffer);
  13330. }
  13331. }
  13332. };
  13333. /**
  13334. * Apply all cached states (depth, culling, stencil and alpha)
  13335. */
  13336. Engine.prototype.applyStates = function () {
  13337. this._depthCullingState.apply(this._gl);
  13338. this._stencilState.apply(this._gl);
  13339. this._alphaState.apply(this._gl);
  13340. };
  13341. /**
  13342. * Send a draw order
  13343. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13344. * @param indexStart defines the starting index
  13345. * @param indexCount defines the number of index to draw
  13346. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13347. */
  13348. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13349. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13350. };
  13351. /**
  13352. * Draw a list of points
  13353. * @param verticesStart defines the index of first vertex to draw
  13354. * @param verticesCount defines the count of vertices to draw
  13355. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13356. */
  13357. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13358. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13359. };
  13360. /**
  13361. * Draw a list of unindexed primitives
  13362. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13363. * @param verticesStart defines the index of first vertex to draw
  13364. * @param verticesCount defines the count of vertices to draw
  13365. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13366. */
  13367. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13368. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13369. };
  13370. /**
  13371. * Draw a list of indexed primitives
  13372. * @param fillMode defines the primitive to use
  13373. * @param indexStart defines the starting index
  13374. * @param indexCount defines the number of index to draw
  13375. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13376. */
  13377. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13378. // Apply states
  13379. this.applyStates();
  13380. this._drawCalls.addCount(1, false);
  13381. // Render
  13382. var drawMode = this._drawMode(fillMode);
  13383. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13384. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13385. if (instancesCount) {
  13386. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13387. }
  13388. else {
  13389. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13390. }
  13391. };
  13392. /**
  13393. * Draw a list of unindexed primitives
  13394. * @param fillMode defines the primitive to use
  13395. * @param verticesStart defines the index of first vertex to draw
  13396. * @param verticesCount defines the count of vertices to draw
  13397. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13398. */
  13399. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13400. // Apply states
  13401. this.applyStates();
  13402. this._drawCalls.addCount(1, false);
  13403. var drawMode = this._drawMode(fillMode);
  13404. if (instancesCount) {
  13405. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13406. }
  13407. else {
  13408. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13409. }
  13410. };
  13411. Engine.prototype._drawMode = function (fillMode) {
  13412. switch (fillMode) {
  13413. // Triangle views
  13414. case BABYLON.Material.TriangleFillMode:
  13415. return this._gl.TRIANGLES;
  13416. case BABYLON.Material.PointFillMode:
  13417. return this._gl.POINTS;
  13418. case BABYLON.Material.WireFrameFillMode:
  13419. return this._gl.LINES;
  13420. // Draw modes
  13421. case BABYLON.Material.PointListDrawMode:
  13422. return this._gl.POINTS;
  13423. case BABYLON.Material.LineListDrawMode:
  13424. return this._gl.LINES;
  13425. case BABYLON.Material.LineLoopDrawMode:
  13426. return this._gl.LINE_LOOP;
  13427. case BABYLON.Material.LineStripDrawMode:
  13428. return this._gl.LINE_STRIP;
  13429. case BABYLON.Material.TriangleStripDrawMode:
  13430. return this._gl.TRIANGLE_STRIP;
  13431. case BABYLON.Material.TriangleFanDrawMode:
  13432. return this._gl.TRIANGLE_FAN;
  13433. default:
  13434. return this._gl.TRIANGLES;
  13435. }
  13436. };
  13437. // Shaders
  13438. /** @ignore */
  13439. Engine.prototype._releaseEffect = function (effect) {
  13440. if (this._compiledEffects[effect._key]) {
  13441. delete this._compiledEffects[effect._key];
  13442. this._deleteProgram(effect.getProgram());
  13443. }
  13444. };
  13445. /** @ignore */
  13446. Engine.prototype._deleteProgram = function (program) {
  13447. if (program) {
  13448. program.__SPECTOR_rebuildProgram = null;
  13449. if (program.transformFeedback) {
  13450. this.deleteTransformFeedback(program.transformFeedback);
  13451. program.transformFeedback = null;
  13452. }
  13453. this._gl.deleteProgram(program);
  13454. }
  13455. };
  13456. /**
  13457. * Create a new effect (used to store vertex/fragment shaders)
  13458. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13459. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13460. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13461. * @param samplers defines an array of string used to represent textures
  13462. * @param defines defines the string containing the defines to use to compile the shaders
  13463. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13464. * @param onCompiled defines a function to call when the effect creation is successful
  13465. * @param onError defines a function to call when the effect creation has failed
  13466. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13467. * @returns the new Effect
  13468. */
  13469. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13470. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13471. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13472. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13473. if (this._compiledEffects[name]) {
  13474. var compiledEffect = this._compiledEffects[name];
  13475. if (onCompiled && compiledEffect.isReady()) {
  13476. onCompiled(compiledEffect);
  13477. }
  13478. return compiledEffect;
  13479. }
  13480. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13481. effect._key = name;
  13482. this._compiledEffects[name] = effect;
  13483. return effect;
  13484. };
  13485. /**
  13486. * Create an effect to use with particle systems
  13487. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13488. * @param uniformsNames defines a list of attribute names
  13489. * @param samplers defines an array of string used to represent textures
  13490. * @param defines defines the string containing the defines to use to compile the shaders
  13491. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13492. * @param onCompiled defines a function to call when the effect creation is successful
  13493. * @param onError defines a function to call when the effect creation has failed
  13494. * @returns the new Effect
  13495. */
  13496. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13497. if (uniformsNames === void 0) { uniformsNames = []; }
  13498. if (samplers === void 0) { samplers = []; }
  13499. if (defines === void 0) { defines = ""; }
  13500. return this.createEffect({
  13501. vertex: "particles",
  13502. fragmentElement: fragmentName
  13503. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13504. };
  13505. /**
  13506. * Directly creates a webGL program
  13507. * @param vertexCode defines the vertex shader code to use
  13508. * @param fragmentCode defines the fragment shader code to use
  13509. * @param context defines the webGL context to use (if not set, the current one will be used)
  13510. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13511. * @returns the new webGL program
  13512. */
  13513. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13514. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13515. context = context || this._gl;
  13516. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13517. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13518. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13519. };
  13520. /**
  13521. * Creates a webGL program
  13522. * @param vertexCode defines the vertex shader code to use
  13523. * @param fragmentCode defines the fragment shader code to use
  13524. * @param defines defines the string containing the defines to use to compile the shaders
  13525. * @param context defines the webGL context to use (if not set, the current one will be used)
  13526. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13527. * @returns the new webGL program
  13528. */
  13529. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13530. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13531. context = context || this._gl;
  13532. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13533. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13534. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13535. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13536. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13537. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13538. return program;
  13539. };
  13540. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13541. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13542. var shaderProgram = context.createProgram();
  13543. if (!shaderProgram) {
  13544. throw new Error("Unable to create program");
  13545. }
  13546. context.attachShader(shaderProgram, vertexShader);
  13547. context.attachShader(shaderProgram, fragmentShader);
  13548. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13549. var transformFeedback = this.createTransformFeedback();
  13550. this.bindTransformFeedback(transformFeedback);
  13551. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13552. shaderProgram.transformFeedback = transformFeedback;
  13553. }
  13554. context.linkProgram(shaderProgram);
  13555. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13556. this.bindTransformFeedback(null);
  13557. }
  13558. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13559. if (!linked) {
  13560. context.validateProgram(shaderProgram);
  13561. var error = context.getProgramInfoLog(shaderProgram);
  13562. if (error) {
  13563. throw new Error(error);
  13564. }
  13565. }
  13566. context.deleteShader(vertexShader);
  13567. context.deleteShader(fragmentShader);
  13568. return shaderProgram;
  13569. };
  13570. /**
  13571. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13572. * @param shaderProgram defines the webGL program to use
  13573. * @param uniformsNames defines the list of uniform names
  13574. * @returns an array of webGL uniform locations
  13575. */
  13576. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13577. var results = new Array();
  13578. for (var index = 0; index < uniformsNames.length; index++) {
  13579. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13580. }
  13581. return results;
  13582. };
  13583. /**
  13584. * Gets the lsit of active attributes for a given webGL program
  13585. * @param shaderProgram defines the webGL program to use
  13586. * @param attributesNames defines the list of attribute names to get
  13587. * @returns an array of indices indicating the offset of each attribute
  13588. */
  13589. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13590. var results = [];
  13591. for (var index = 0; index < attributesNames.length; index++) {
  13592. try {
  13593. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13594. }
  13595. catch (e) {
  13596. results.push(-1);
  13597. }
  13598. }
  13599. return results;
  13600. };
  13601. /**
  13602. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13603. * @param effect defines the effect to activate
  13604. */
  13605. Engine.prototype.enableEffect = function (effect) {
  13606. if (!effect) {
  13607. return;
  13608. }
  13609. // Use program
  13610. this.bindSamplers(effect);
  13611. this._currentEffect = effect;
  13612. if (effect.onBind) {
  13613. effect.onBind(effect);
  13614. }
  13615. effect.onBindObservable.notifyObservers(effect);
  13616. };
  13617. /**
  13618. * Set the value of an uniform to an array of int32
  13619. * @param uniform defines the webGL uniform location where to store the value
  13620. * @param array defines the array of int32 to store
  13621. */
  13622. Engine.prototype.setIntArray = function (uniform, array) {
  13623. if (!uniform)
  13624. return;
  13625. this._gl.uniform1iv(uniform, array);
  13626. };
  13627. /**
  13628. * Set the value of an uniform to an array of int32 (stored as vec2)
  13629. * @param uniform defines the webGL uniform location where to store the value
  13630. * @param array defines the array of int32 to store
  13631. */
  13632. Engine.prototype.setIntArray2 = function (uniform, array) {
  13633. if (!uniform || array.length % 2 !== 0)
  13634. return;
  13635. this._gl.uniform2iv(uniform, array);
  13636. };
  13637. /**
  13638. * Set the value of an uniform to an array of int32 (stored as vec3)
  13639. * @param uniform defines the webGL uniform location where to store the value
  13640. * @param array defines the array of int32 to store
  13641. */
  13642. Engine.prototype.setIntArray3 = function (uniform, array) {
  13643. if (!uniform || array.length % 3 !== 0)
  13644. return;
  13645. this._gl.uniform3iv(uniform, array);
  13646. };
  13647. /**
  13648. * Set the value of an uniform to an array of int32 (stored as vec4)
  13649. * @param uniform defines the webGL uniform location where to store the value
  13650. * @param array defines the array of int32 to store
  13651. */
  13652. Engine.prototype.setIntArray4 = function (uniform, array) {
  13653. if (!uniform || array.length % 4 !== 0)
  13654. return;
  13655. this._gl.uniform4iv(uniform, array);
  13656. };
  13657. /**
  13658. * Set the value of an uniform to an array of float32
  13659. * @param uniform defines the webGL uniform location where to store the value
  13660. * @param array defines the array of float32 to store
  13661. */
  13662. Engine.prototype.setFloatArray = function (uniform, array) {
  13663. if (!uniform)
  13664. return;
  13665. this._gl.uniform1fv(uniform, array);
  13666. };
  13667. /**
  13668. * Set the value of an uniform to an array of float32 (stored as vec2)
  13669. * @param uniform defines the webGL uniform location where to store the value
  13670. * @param array defines the array of float32 to store
  13671. */
  13672. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13673. if (!uniform || array.length % 2 !== 0)
  13674. return;
  13675. this._gl.uniform2fv(uniform, array);
  13676. };
  13677. /**
  13678. * Set the value of an uniform to an array of float32 (stored as vec3)
  13679. * @param uniform defines the webGL uniform location where to store the value
  13680. * @param array defines the array of float32 to store
  13681. */
  13682. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13683. if (!uniform || array.length % 3 !== 0)
  13684. return;
  13685. this._gl.uniform3fv(uniform, array);
  13686. };
  13687. /**
  13688. * Set the value of an uniform to an array of float32 (stored as vec4)
  13689. * @param uniform defines the webGL uniform location where to store the value
  13690. * @param array defines the array of float32 to store
  13691. */
  13692. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13693. if (!uniform || array.length % 4 !== 0)
  13694. return;
  13695. this._gl.uniform4fv(uniform, array);
  13696. };
  13697. /**
  13698. * Set the value of an uniform to an array of number
  13699. * @param uniform defines the webGL uniform location where to store the value
  13700. * @param array defines the array of number to store
  13701. */
  13702. Engine.prototype.setArray = function (uniform, array) {
  13703. if (!uniform)
  13704. return;
  13705. this._gl.uniform1fv(uniform, array);
  13706. };
  13707. /**
  13708. * Set the value of an uniform to an array of number (stored as vec2)
  13709. * @param uniform defines the webGL uniform location where to store the value
  13710. * @param array defines the array of number to store
  13711. */
  13712. Engine.prototype.setArray2 = function (uniform, array) {
  13713. if (!uniform || array.length % 2 !== 0)
  13714. return;
  13715. this._gl.uniform2fv(uniform, array);
  13716. };
  13717. /**
  13718. * Set the value of an uniform to an array of number (stored as vec3)
  13719. * @param uniform defines the webGL uniform location where to store the value
  13720. * @param array defines the array of number to store
  13721. */
  13722. Engine.prototype.setArray3 = function (uniform, array) {
  13723. if (!uniform || array.length % 3 !== 0)
  13724. return;
  13725. this._gl.uniform3fv(uniform, array);
  13726. };
  13727. /**
  13728. * Set the value of an uniform to an array of number (stored as vec4)
  13729. * @param uniform defines the webGL uniform location where to store the value
  13730. * @param array defines the array of number to store
  13731. */
  13732. Engine.prototype.setArray4 = function (uniform, array) {
  13733. if (!uniform || array.length % 4 !== 0)
  13734. return;
  13735. this._gl.uniform4fv(uniform, array);
  13736. };
  13737. /**
  13738. * Set the value of an uniform to an array of float32 (stored as matrices)
  13739. * @param uniform defines the webGL uniform location where to store the value
  13740. * @param matrices defines the array of float32 to store
  13741. */
  13742. Engine.prototype.setMatrices = function (uniform, matrices) {
  13743. if (!uniform)
  13744. return;
  13745. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13746. };
  13747. /**
  13748. * Set the value of an uniform to a matrix
  13749. * @param uniform defines the webGL uniform location where to store the value
  13750. * @param matrix defines the matrix to store
  13751. */
  13752. Engine.prototype.setMatrix = function (uniform, matrix) {
  13753. if (!uniform)
  13754. return;
  13755. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13756. };
  13757. /**
  13758. * Set the value of an uniform to a matrix (3x3)
  13759. * @param uniform defines the webGL uniform location where to store the value
  13760. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13761. */
  13762. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13763. if (!uniform)
  13764. return;
  13765. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13766. };
  13767. /**
  13768. * Set the value of an uniform to a matrix (2x2)
  13769. * @param uniform defines the webGL uniform location where to store the value
  13770. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13771. */
  13772. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13773. if (!uniform)
  13774. return;
  13775. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13776. };
  13777. /**
  13778. * Set the value of an uniform to a number (int)
  13779. * @param uniform defines the webGL uniform location where to store the value
  13780. * @param value defines the int number to store
  13781. */
  13782. Engine.prototype.setInt = function (uniform, value) {
  13783. if (!uniform)
  13784. return;
  13785. this._gl.uniform1i(uniform, value);
  13786. };
  13787. /**
  13788. * Set the value of an uniform to a number (float)
  13789. * @param uniform defines the webGL uniform location where to store the value
  13790. * @param value defines the float number to store
  13791. */
  13792. Engine.prototype.setFloat = function (uniform, value) {
  13793. if (!uniform)
  13794. return;
  13795. this._gl.uniform1f(uniform, value);
  13796. };
  13797. /**
  13798. * Set the value of an uniform to a vec2
  13799. * @param uniform defines the webGL uniform location where to store the value
  13800. * @param x defines the 1st component of the value
  13801. * @param y defines the 2nd component of the value
  13802. */
  13803. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13804. if (!uniform)
  13805. return;
  13806. this._gl.uniform2f(uniform, x, y);
  13807. };
  13808. /**
  13809. * Set the value of an uniform to a vec3
  13810. * @param uniform defines the webGL uniform location where to store the value
  13811. * @param x defines the 1st component of the value
  13812. * @param y defines the 2nd component of the value
  13813. * @param z defines the 3rd component of the value
  13814. */
  13815. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13816. if (!uniform)
  13817. return;
  13818. this._gl.uniform3f(uniform, x, y, z);
  13819. };
  13820. /**
  13821. * Set the value of an uniform to a boolean
  13822. * @param uniform defines the webGL uniform location where to store the value
  13823. * @param bool defines the boolean to store
  13824. */
  13825. Engine.prototype.setBool = function (uniform, bool) {
  13826. if (!uniform)
  13827. return;
  13828. this._gl.uniform1i(uniform, bool);
  13829. };
  13830. /**
  13831. * Set the value of an uniform to a vec4
  13832. * @param uniform defines the webGL uniform location where to store the value
  13833. * @param x defines the 1st component of the value
  13834. * @param y defines the 2nd component of the value
  13835. * @param z defines the 3rd component of the value
  13836. * @param w defines the 4th component of the value
  13837. */
  13838. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13839. if (!uniform)
  13840. return;
  13841. this._gl.uniform4f(uniform, x, y, z, w);
  13842. };
  13843. /**
  13844. * Set the value of an uniform to a Color3
  13845. * @param uniform defines the webGL uniform location where to store the value
  13846. * @param color3 defines the color to store
  13847. */
  13848. Engine.prototype.setColor3 = function (uniform, color3) {
  13849. if (!uniform)
  13850. return;
  13851. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13852. };
  13853. /**
  13854. * Set the value of an uniform to a Color3 and an alpha value
  13855. * @param uniform defines the webGL uniform location where to store the value
  13856. * @param color3 defines the color to store
  13857. * @param alpha defines the alpha component to store
  13858. */
  13859. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13860. if (!uniform)
  13861. return;
  13862. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13863. };
  13864. /**
  13865. * Sets a Color4 on a uniform variable
  13866. * @param uniform defines the uniform location
  13867. * @param color4 defines the value to be set
  13868. */
  13869. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13870. if (!uniform)
  13871. return;
  13872. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13873. };
  13874. // States
  13875. /**
  13876. * Set various states to the webGL context
  13877. * @param culling defines backface culling state
  13878. * @param zOffset defines the value to apply to zOffset (0 by default)
  13879. * @param force defines if states must be applied even if cache is up to date
  13880. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13881. */
  13882. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13883. if (zOffset === void 0) { zOffset = 0; }
  13884. if (reverseSide === void 0) { reverseSide = false; }
  13885. // Culling
  13886. if (this._depthCullingState.cull !== culling || force) {
  13887. this._depthCullingState.cull = culling;
  13888. }
  13889. // Cull face
  13890. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13891. if (this._depthCullingState.cullFace !== cullFace || force) {
  13892. this._depthCullingState.cullFace = cullFace;
  13893. }
  13894. // Z offset
  13895. this.setZOffset(zOffset);
  13896. // Front face
  13897. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13898. if (this._depthCullingState.frontFace !== frontFace || force) {
  13899. this._depthCullingState.frontFace = frontFace;
  13900. }
  13901. };
  13902. /**
  13903. * Set the z offset to apply to current rendering
  13904. * @param value defines the offset to apply
  13905. */
  13906. Engine.prototype.setZOffset = function (value) {
  13907. this._depthCullingState.zOffset = value;
  13908. };
  13909. /**
  13910. * Gets the current value of the zOffset
  13911. * @returns the current zOffset state
  13912. */
  13913. Engine.prototype.getZOffset = function () {
  13914. return this._depthCullingState.zOffset;
  13915. };
  13916. /**
  13917. * Enable or disable depth buffering
  13918. * @param enable defines the state to set
  13919. */
  13920. Engine.prototype.setDepthBuffer = function (enable) {
  13921. this._depthCullingState.depthTest = enable;
  13922. };
  13923. /**
  13924. * Gets a boolean indicating if depth writing is enabled
  13925. * @returns the current depth writing state
  13926. */
  13927. Engine.prototype.getDepthWrite = function () {
  13928. return this._depthCullingState.depthMask;
  13929. };
  13930. /**
  13931. * Enable or disable depth writing
  13932. * @param enable defines the state to set
  13933. */
  13934. Engine.prototype.setDepthWrite = function (enable) {
  13935. this._depthCullingState.depthMask = enable;
  13936. };
  13937. /**
  13938. * Enable or disable color writing
  13939. * @param enable defines the state to set
  13940. */
  13941. Engine.prototype.setColorWrite = function (enable) {
  13942. this._gl.colorMask(enable, enable, enable, enable);
  13943. this._colorWrite = enable;
  13944. };
  13945. /**
  13946. * Gets a boolean indicating if color writing is enabled
  13947. * @returns the current color writing state
  13948. */
  13949. Engine.prototype.getColorWrite = function () {
  13950. return this._colorWrite;
  13951. };
  13952. /**
  13953. * Sets alpha constants used by some alpha blending modes
  13954. * @param r defines the red component
  13955. * @param g defines the green component
  13956. * @param b defines the blue component
  13957. * @param a defines the alpha component
  13958. */
  13959. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  13960. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  13961. };
  13962. /**
  13963. * Sets the current alpha mode
  13964. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  13965. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  13966. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  13967. */
  13968. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  13969. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  13970. if (this._alphaMode === mode) {
  13971. return;
  13972. }
  13973. switch (mode) {
  13974. case Engine.ALPHA_DISABLE:
  13975. this._alphaState.alphaBlend = false;
  13976. break;
  13977. case Engine.ALPHA_PREMULTIPLIED:
  13978. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13979. this._alphaState.alphaBlend = true;
  13980. break;
  13981. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  13982. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13983. this._alphaState.alphaBlend = true;
  13984. break;
  13985. case Engine.ALPHA_COMBINE:
  13986. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  13987. this._alphaState.alphaBlend = true;
  13988. break;
  13989. case Engine.ALPHA_ONEONE:
  13990. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13991. this._alphaState.alphaBlend = true;
  13992. break;
  13993. case Engine.ALPHA_ADD:
  13994. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13995. this._alphaState.alphaBlend = true;
  13996. break;
  13997. case Engine.ALPHA_SUBTRACT:
  13998. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13999. this._alphaState.alphaBlend = true;
  14000. break;
  14001. case Engine.ALPHA_MULTIPLY:
  14002. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14003. this._alphaState.alphaBlend = true;
  14004. break;
  14005. case Engine.ALPHA_MAXIMIZED:
  14006. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14007. this._alphaState.alphaBlend = true;
  14008. break;
  14009. case Engine.ALPHA_INTERPOLATE:
  14010. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14011. this._alphaState.alphaBlend = true;
  14012. break;
  14013. case Engine.ALPHA_SCREENMODE:
  14014. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14015. this._alphaState.alphaBlend = true;
  14016. break;
  14017. }
  14018. if (!noDepthWriteChange) {
  14019. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14020. }
  14021. this._alphaMode = mode;
  14022. };
  14023. /**
  14024. * Gets the current alpha mode
  14025. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14026. * @returns the current alpha mode
  14027. */
  14028. Engine.prototype.getAlphaMode = function () {
  14029. return this._alphaMode;
  14030. };
  14031. // Textures
  14032. /**
  14033. * Force the entire cache to be cleared
  14034. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14035. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14036. */
  14037. Engine.prototype.wipeCaches = function (bruteForce) {
  14038. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14039. return;
  14040. }
  14041. this._currentEffect = null;
  14042. if (bruteForce) {
  14043. this.resetTextureCache();
  14044. this._currentProgram = null;
  14045. this._stencilState.reset();
  14046. this._depthCullingState.reset();
  14047. this.setDepthFunctionToLessOrEqual();
  14048. this._alphaState.reset();
  14049. }
  14050. this._resetVertexBufferBinding();
  14051. this._cachedIndexBuffer = null;
  14052. this._cachedEffectForVertexBuffers = null;
  14053. this._unbindVertexArrayObject();
  14054. this.bindIndexBuffer(null);
  14055. };
  14056. /**
  14057. * Set the compressed texture format to use, based on the formats you have, and the formats
  14058. * supported by the hardware / browser.
  14059. *
  14060. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14061. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14062. * to API arguments needed to compressed textures. This puts the burden on the container
  14063. * generator to house the arcane code for determining these for current & future formats.
  14064. *
  14065. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14066. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14067. *
  14068. * Note: The result of this call is not taken into account when a texture is base64.
  14069. *
  14070. * @param formatsAvailable defines the list of those format families you have created
  14071. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14072. *
  14073. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14074. * @returns The extension selected.
  14075. */
  14076. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14077. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14078. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14079. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14080. return this._textureFormatInUse = this._texturesSupported[i];
  14081. }
  14082. }
  14083. }
  14084. // actively set format to nothing, to allow this to be called more than once
  14085. // and possibly fail the 2nd time
  14086. this._textureFormatInUse = null;
  14087. return null;
  14088. };
  14089. /** @ignore */
  14090. Engine.prototype._createTexture = function () {
  14091. var texture = this._gl.createTexture();
  14092. if (!texture) {
  14093. throw new Error("Unable to create texture");
  14094. }
  14095. return texture;
  14096. };
  14097. /**
  14098. * Usually called from BABYLON.Texture.ts.
  14099. * Passed information to create a WebGLTexture
  14100. * @param urlArg defines a value which contains one of the following:
  14101. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14102. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14103. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14104. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14105. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14106. * @param scene needed for loading to the correct scene
  14107. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14108. * @param onLoad optional callback to be called upon successful completion
  14109. * @param onError optional callback to be called upon failure
  14110. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14111. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14112. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14113. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14114. */
  14115. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14116. var _this = this;
  14117. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14118. if (onLoad === void 0) { onLoad = null; }
  14119. if (onError === void 0) { onError = null; }
  14120. if (buffer === void 0) { buffer = null; }
  14121. if (fallback === void 0) { fallback = null; }
  14122. if (format === void 0) { format = null; }
  14123. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14124. var fromData = url.substr(0, 5) === "data:";
  14125. var fromBlob = url.substr(0, 5) === "blob:";
  14126. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14127. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14128. // establish the file extension, if possible
  14129. var lastDot = url.lastIndexOf('.');
  14130. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14131. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14132. var isTGA = (extension.indexOf(".tga") === 0);
  14133. // determine if a ktx file should be substituted
  14134. var isKTX = false;
  14135. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14136. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14137. isKTX = true;
  14138. }
  14139. if (scene) {
  14140. scene._addPendingData(texture);
  14141. }
  14142. texture.url = url;
  14143. texture.generateMipMaps = !noMipmap;
  14144. texture.samplingMode = samplingMode;
  14145. texture.invertY = invertY;
  14146. if (!this._doNotHandleContextLost) {
  14147. // Keep a link to the buffer only if we plan to handle context lost
  14148. texture._buffer = buffer;
  14149. }
  14150. var onLoadObserver = null;
  14151. if (onLoad && !fallback) {
  14152. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14153. }
  14154. if (!fallback)
  14155. this._internalTexturesCache.push(texture);
  14156. var onerror = function (message, exception) {
  14157. if (scene) {
  14158. scene._removePendingData(texture);
  14159. }
  14160. if (onLoadObserver) {
  14161. texture.onLoadedObservable.remove(onLoadObserver);
  14162. }
  14163. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14164. if (isKTX) {
  14165. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14166. }
  14167. else if (BABYLON.Tools.UseFallbackTexture) {
  14168. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14169. }
  14170. if (onError) {
  14171. onError(message || "Unknown error", exception);
  14172. }
  14173. };
  14174. var callback = null;
  14175. // processing for non-image formats
  14176. if (isKTX || isTGA || isDDS) {
  14177. if (isKTX) {
  14178. callback = function (data) {
  14179. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14180. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14181. ktx.uploadLevels(_this._gl, !noMipmap);
  14182. return false;
  14183. }, samplingMode);
  14184. };
  14185. }
  14186. else if (isTGA) {
  14187. callback = function (arrayBuffer) {
  14188. var data = new Uint8Array(arrayBuffer);
  14189. var header = BABYLON.TGATools.GetTGAHeader(data);
  14190. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14191. BABYLON.TGATools.UploadContent(_this._gl, data);
  14192. return false;
  14193. }, samplingMode);
  14194. };
  14195. }
  14196. else if (isDDS) {
  14197. callback = function (data) {
  14198. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14199. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14200. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14201. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14202. return false;
  14203. }, samplingMode);
  14204. };
  14205. }
  14206. if (!buffer) {
  14207. this._loadFile(url, function (data) {
  14208. if (callback) {
  14209. callback(data);
  14210. }
  14211. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14212. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14213. });
  14214. }
  14215. else {
  14216. if (callback) {
  14217. callback(buffer);
  14218. }
  14219. }
  14220. // image format processing
  14221. }
  14222. else {
  14223. var onload = function (img) {
  14224. if (fromBlob && !_this._doNotHandleContextLost) {
  14225. // We need to store the image if we need to rebuild the texture
  14226. // in case of a webgl context lost
  14227. texture._buffer = img;
  14228. }
  14229. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14230. var gl = _this._gl;
  14231. var isPot = (img.width === potWidth && img.height === potHeight);
  14232. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14233. if (isPot) {
  14234. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14235. return false;
  14236. }
  14237. // Using shaders to rescale because canvas.drawImage is lossy
  14238. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14239. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14240. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14243. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14244. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14245. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14246. _this._releaseTexture(source);
  14247. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14248. continuationCallback();
  14249. });
  14250. return true;
  14251. }, samplingMode);
  14252. };
  14253. if (!fromData || isBase64)
  14254. if (buffer instanceof HTMLImageElement) {
  14255. onload(buffer);
  14256. }
  14257. else {
  14258. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14259. }
  14260. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14261. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14262. else
  14263. onload(buffer);
  14264. }
  14265. return texture;
  14266. };
  14267. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14268. var _this = this;
  14269. var rtt = this.createRenderTargetTexture({
  14270. width: destination.width,
  14271. height: destination.height,
  14272. }, {
  14273. generateMipMaps: false,
  14274. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14275. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14276. generateDepthBuffer: false,
  14277. generateStencilBuffer: false
  14278. });
  14279. if (!this._rescalePostProcess) {
  14280. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14281. }
  14282. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14283. _this._rescalePostProcess.onApply = function (effect) {
  14284. effect._bindTexture("textureSampler", source);
  14285. };
  14286. var hostingScene = scene;
  14287. if (!hostingScene) {
  14288. hostingScene = _this.scenes[_this.scenes.length - 1];
  14289. }
  14290. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14291. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14292. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14293. _this.unBindFramebuffer(rtt);
  14294. _this._releaseTexture(rtt);
  14295. if (onComplete) {
  14296. onComplete();
  14297. }
  14298. });
  14299. };
  14300. /**
  14301. * Update a raw texture
  14302. * @param texture defines the texture to update
  14303. * @param data defines the data to store in the texture
  14304. * @param format defines the format of the data
  14305. * @param invertY defines if data must be stored with Y axis inverted
  14306. * @param compression defines the compression used (null by default)
  14307. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14308. */
  14309. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14310. if (compression === void 0) { compression = null; }
  14311. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14312. if (!texture) {
  14313. return;
  14314. }
  14315. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14316. var internalFormat = this._getInternalFormat(format);
  14317. var textureType = this._getWebGLTextureType(type);
  14318. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14319. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14320. if (!this._doNotHandleContextLost) {
  14321. texture._bufferView = data;
  14322. texture.format = format;
  14323. texture.type = type;
  14324. texture.invertY = invertY;
  14325. texture._compression = compression;
  14326. }
  14327. if (texture.width % 4 !== 0) {
  14328. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14329. }
  14330. if (compression && data) {
  14331. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14332. }
  14333. else {
  14334. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14335. }
  14336. if (texture.generateMipMaps) {
  14337. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14338. }
  14339. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14340. // this.resetTextureCache();
  14341. texture.isReady = true;
  14342. };
  14343. /**
  14344. * Creates a raw texture
  14345. * @param data defines the data to store in the texture
  14346. * @param width defines the width of the texture
  14347. * @param height defines the height of the texture
  14348. * @param format defines the format of the data
  14349. * @param generateMipMaps defines if the engine should generate the mip levels
  14350. * @param invertY defines if data must be stored with Y axis inverted
  14351. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14352. * @param compression defines the compression used (null by default)
  14353. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14354. * @returns the raw texture inside an InternalTexture
  14355. */
  14356. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14357. if (compression === void 0) { compression = null; }
  14358. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14359. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14360. texture.baseWidth = width;
  14361. texture.baseHeight = height;
  14362. texture.width = width;
  14363. texture.height = height;
  14364. texture.format = format;
  14365. texture.generateMipMaps = generateMipMaps;
  14366. texture.samplingMode = samplingMode;
  14367. texture.invertY = invertY;
  14368. texture._compression = compression;
  14369. texture.type = type;
  14370. if (!this._doNotHandleContextLost) {
  14371. texture._bufferView = data;
  14372. }
  14373. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14374. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14375. // Filters
  14376. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14377. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14378. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14379. if (generateMipMaps) {
  14380. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14381. }
  14382. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14383. this._internalTexturesCache.push(texture);
  14384. return texture;
  14385. };
  14386. /**
  14387. * Creates a dynamic texture
  14388. * @param width defines the width of the texture
  14389. * @param height defines the height of the texture
  14390. * @param generateMipMaps defines if the engine should generate the mip levels
  14391. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14392. * @returns the dynamic texture inside an InternalTexture
  14393. */
  14394. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14395. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14396. texture.baseWidth = width;
  14397. texture.baseHeight = height;
  14398. if (generateMipMaps) {
  14399. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14400. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14401. }
  14402. // this.resetTextureCache();
  14403. texture.width = width;
  14404. texture.height = height;
  14405. texture.isReady = false;
  14406. texture.generateMipMaps = generateMipMaps;
  14407. texture.samplingMode = samplingMode;
  14408. this.updateTextureSamplingMode(samplingMode, texture);
  14409. this._internalTexturesCache.push(texture);
  14410. return texture;
  14411. };
  14412. /**
  14413. * Update the sampling mode of a given texture
  14414. * @param samplingMode defines the required sampling mode
  14415. * @param texture defines the texture to update
  14416. */
  14417. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14418. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14419. if (texture.isCube) {
  14420. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14421. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14422. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14423. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14424. }
  14425. else if (texture.is3D) {
  14426. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14427. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14428. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14429. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14430. }
  14431. else {
  14432. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14433. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14434. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14435. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14436. }
  14437. texture.samplingMode = samplingMode;
  14438. };
  14439. /**
  14440. * Update the content of a dynamic texture
  14441. * @param texture defines the texture to update
  14442. * @param canvas defines the canvas containing the source
  14443. * @param invertY defines if data must be stored with Y axis inverted
  14444. * @param premulAlpha defines if alpha is stored as premultiplied
  14445. * @param format defines the format of the data
  14446. */
  14447. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14448. if (premulAlpha === void 0) { premulAlpha = false; }
  14449. if (!texture) {
  14450. return;
  14451. }
  14452. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14453. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14454. if (premulAlpha) {
  14455. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14456. }
  14457. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14458. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14459. if (texture.generateMipMaps) {
  14460. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14461. }
  14462. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14463. if (premulAlpha) {
  14464. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14465. }
  14466. texture.isReady = true;
  14467. };
  14468. /**
  14469. * Update a video texture
  14470. * @param texture defines the texture to update
  14471. * @param video defines the video element to use
  14472. * @param invertY defines if data must be stored with Y axis inverted
  14473. */
  14474. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14475. if (!texture || texture._isDisabled) {
  14476. return;
  14477. }
  14478. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14479. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14480. try {
  14481. // Testing video texture support
  14482. if (this._videoTextureSupported === undefined) {
  14483. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14484. if (this._gl.getError() !== 0) {
  14485. this._videoTextureSupported = false;
  14486. }
  14487. else {
  14488. this._videoTextureSupported = true;
  14489. }
  14490. }
  14491. // Copy video through the current working canvas if video texture is not supported
  14492. if (!this._videoTextureSupported) {
  14493. if (!texture._workingCanvas) {
  14494. texture._workingCanvas = document.createElement("canvas");
  14495. var context = texture._workingCanvas.getContext("2d");
  14496. if (!context) {
  14497. throw new Error("Unable to get 2d context");
  14498. }
  14499. texture._workingContext = context;
  14500. texture._workingCanvas.width = texture.width;
  14501. texture._workingCanvas.height = texture.height;
  14502. }
  14503. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14504. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14505. }
  14506. else {
  14507. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14508. }
  14509. if (texture.generateMipMaps) {
  14510. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14511. }
  14512. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14513. // this.resetTextureCache();
  14514. texture.isReady = true;
  14515. }
  14516. catch (ex) {
  14517. // Something unexpected
  14518. // Let's disable the texture
  14519. texture._isDisabled = true;
  14520. }
  14521. };
  14522. /**
  14523. * Updates a depth texture Comparison Mode and Function.
  14524. * If the comparison Function is equal to 0, the mode will be set to none.
  14525. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14526. * @param texture The texture to set the comparison function for
  14527. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14528. */
  14529. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14530. if (this.webGLVersion === 1) {
  14531. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14532. return;
  14533. }
  14534. var gl = this._gl;
  14535. if (texture.isCube) {
  14536. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14537. if (comparisonFunction === 0) {
  14538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14540. }
  14541. else {
  14542. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14543. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14544. }
  14545. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14546. }
  14547. else {
  14548. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14549. if (comparisonFunction === 0) {
  14550. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14551. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14552. }
  14553. else {
  14554. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14555. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14556. }
  14557. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14558. }
  14559. texture._comparisonFunction = comparisonFunction;
  14560. };
  14561. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14562. var width = size.width || size;
  14563. var height = size.height || size;
  14564. internalTexture.baseWidth = width;
  14565. internalTexture.baseHeight = height;
  14566. internalTexture.width = width;
  14567. internalTexture.height = height;
  14568. internalTexture.isReady = true;
  14569. internalTexture.samples = 1;
  14570. internalTexture.generateMipMaps = false;
  14571. internalTexture._generateDepthBuffer = true;
  14572. internalTexture._generateStencilBuffer = generateStencil;
  14573. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14574. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14575. internalTexture._comparisonFunction = comparisonFunction;
  14576. var gl = this._gl;
  14577. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14578. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14579. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14580. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14581. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14582. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14583. if (comparisonFunction === 0) {
  14584. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14585. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14586. }
  14587. else {
  14588. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14589. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14590. }
  14591. };
  14592. /**
  14593. * Creates a depth stencil texture.
  14594. * This is only available in WebGL 2 or with the depth texture extension available.
  14595. * @param size The size of face edge in the texture.
  14596. * @param options The options defining the texture.
  14597. * @returns The texture
  14598. */
  14599. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14600. if (options.isCube) {
  14601. var width = size.width || size;
  14602. return this._createDepthStencilCubeTexture(width, options);
  14603. }
  14604. else {
  14605. return this._createDepthStencilTexture(size, options);
  14606. }
  14607. };
  14608. /**
  14609. * Creates a depth stencil texture.
  14610. * This is only available in WebGL 2 or with the depth texture extension available.
  14611. * @param size The size of face edge in the texture.
  14612. * @param options The options defining the texture.
  14613. * @returns The texture
  14614. */
  14615. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14616. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14617. if (!this._caps.depthTextureExtension) {
  14618. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14619. return internalTexture;
  14620. }
  14621. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14622. var gl = this._gl;
  14623. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14624. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14625. if (this.webGLVersion > 1) {
  14626. if (internalOptions.generateStencil) {
  14627. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14628. }
  14629. else {
  14630. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14631. }
  14632. }
  14633. else {
  14634. if (internalOptions.generateStencil) {
  14635. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14636. }
  14637. else {
  14638. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14639. }
  14640. }
  14641. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14642. return internalTexture;
  14643. };
  14644. /**
  14645. * Creates a depth stencil cube texture.
  14646. * This is only available in WebGL 2.
  14647. * @param size The size of face edge in the cube texture.
  14648. * @param options The options defining the cube texture.
  14649. * @returns The cube texture
  14650. */
  14651. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14652. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14653. internalTexture.isCube = true;
  14654. if (this.webGLVersion === 1) {
  14655. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14656. return internalTexture;
  14657. }
  14658. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14659. var gl = this._gl;
  14660. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14661. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14662. // Create the depth/stencil buffer
  14663. for (var face = 0; face < 6; face++) {
  14664. if (internalOptions.generateStencil) {
  14665. 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);
  14666. }
  14667. else {
  14668. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14669. }
  14670. }
  14671. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14672. return internalTexture;
  14673. };
  14674. /**
  14675. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14676. * @param renderTarget The render target to set the frame buffer for
  14677. */
  14678. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14679. // Create the framebuffer
  14680. var internalTexture = renderTarget.getInternalTexture();
  14681. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14682. return;
  14683. }
  14684. var gl = this._gl;
  14685. var depthStencilTexture = renderTarget.depthStencilTexture;
  14686. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14687. if (depthStencilTexture.isCube) {
  14688. if (depthStencilTexture._generateStencilBuffer) {
  14689. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14690. }
  14691. else {
  14692. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14693. }
  14694. }
  14695. else {
  14696. if (depthStencilTexture._generateStencilBuffer) {
  14697. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14698. }
  14699. else {
  14700. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14701. }
  14702. }
  14703. this.bindUnboundFramebuffer(null);
  14704. };
  14705. /**
  14706. * Creates a new render target texture
  14707. * @param size defines the size of the texture
  14708. * @param options defines the options used to create the texture
  14709. * @returns a new render target texture stored in an InternalTexture
  14710. */
  14711. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14712. var fullOptions = new RenderTargetCreationOptions();
  14713. if (options !== undefined && typeof options === "object") {
  14714. fullOptions.generateMipMaps = options.generateMipMaps;
  14715. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14716. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14717. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14718. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14719. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14720. }
  14721. else {
  14722. fullOptions.generateMipMaps = options;
  14723. fullOptions.generateDepthBuffer = true;
  14724. fullOptions.generateStencilBuffer = false;
  14725. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14726. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14727. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14728. }
  14729. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14730. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14731. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14732. }
  14733. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14734. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14735. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14736. }
  14737. var gl = this._gl;
  14738. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14739. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14740. var width = size.width || size;
  14741. var height = size.height || size;
  14742. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14743. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14744. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14745. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14746. }
  14747. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14748. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14749. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14750. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14751. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14752. // Create the framebuffer
  14753. var framebuffer = gl.createFramebuffer();
  14754. this.bindUnboundFramebuffer(framebuffer);
  14755. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14756. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14757. if (fullOptions.generateMipMaps) {
  14758. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14759. }
  14760. // Unbind
  14761. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14762. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14763. this.bindUnboundFramebuffer(null);
  14764. texture._framebuffer = framebuffer;
  14765. texture.baseWidth = width;
  14766. texture.baseHeight = height;
  14767. texture.width = width;
  14768. texture.height = height;
  14769. texture.isReady = true;
  14770. texture.samples = 1;
  14771. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  14772. texture.samplingMode = fullOptions.samplingMode;
  14773. texture.type = fullOptions.type;
  14774. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14775. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  14776. // this.resetTextureCache();
  14777. this._internalTexturesCache.push(texture);
  14778. return texture;
  14779. };
  14780. /**
  14781. * Create a multi render target texture
  14782. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  14783. * @param size defines the size of the texture
  14784. * @param options defines the creation options
  14785. * @returns the cube texture as an InternalTexture
  14786. */
  14787. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  14788. var generateMipMaps = false;
  14789. var generateDepthBuffer = true;
  14790. var generateStencilBuffer = false;
  14791. var generateDepthTexture = false;
  14792. var textureCount = 1;
  14793. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  14794. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14795. var types = new Array();
  14796. var samplingModes = new Array();
  14797. if (options !== undefined) {
  14798. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  14799. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14800. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  14801. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  14802. textureCount = options.textureCount || 1;
  14803. if (options.types) {
  14804. types = options.types;
  14805. }
  14806. if (options.samplingModes) {
  14807. samplingModes = options.samplingModes;
  14808. }
  14809. }
  14810. var gl = this._gl;
  14811. // Create the framebuffer
  14812. var framebuffer = gl.createFramebuffer();
  14813. this.bindUnboundFramebuffer(framebuffer);
  14814. var width = size.width || size;
  14815. var height = size.height || size;
  14816. var textures = [];
  14817. var attachments = [];
  14818. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  14819. for (var i = 0; i < textureCount; i++) {
  14820. var samplingMode = samplingModes[i] || defaultSamplingMode;
  14821. var type = types[i] || defaultType;
  14822. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14823. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14824. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14825. }
  14826. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14827. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14828. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14829. }
  14830. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14831. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14832. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14833. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14834. }
  14835. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14836. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14837. textures.push(texture);
  14838. attachments.push(attachment);
  14839. gl.activeTexture(gl["TEXTURE" + i]);
  14840. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  14841. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14842. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14843. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14844. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14845. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14846. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14847. if (generateMipMaps) {
  14848. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14849. }
  14850. // Unbind
  14851. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14852. texture._framebuffer = framebuffer;
  14853. texture._depthStencilBuffer = depthStencilBuffer;
  14854. texture.baseWidth = width;
  14855. texture.baseHeight = height;
  14856. texture.width = width;
  14857. texture.height = height;
  14858. texture.isReady = true;
  14859. texture.samples = 1;
  14860. texture.generateMipMaps = generateMipMaps;
  14861. texture.samplingMode = samplingMode;
  14862. texture.type = type;
  14863. texture._generateDepthBuffer = generateDepthBuffer;
  14864. texture._generateStencilBuffer = generateStencilBuffer;
  14865. texture._attachments = attachments;
  14866. this._internalTexturesCache.push(texture);
  14867. }
  14868. if (generateDepthTexture && this._caps.depthTextureExtension) {
  14869. // Depth texture
  14870. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14871. gl.activeTexture(gl.TEXTURE0);
  14872. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  14873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14874. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14875. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14876. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14877. 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);
  14878. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  14879. depthTexture._framebuffer = framebuffer;
  14880. depthTexture.baseWidth = width;
  14881. depthTexture.baseHeight = height;
  14882. depthTexture.width = width;
  14883. depthTexture.height = height;
  14884. depthTexture.isReady = true;
  14885. depthTexture.samples = 1;
  14886. depthTexture.generateMipMaps = generateMipMaps;
  14887. depthTexture.samplingMode = gl.NEAREST;
  14888. depthTexture._generateDepthBuffer = generateDepthBuffer;
  14889. depthTexture._generateStencilBuffer = generateStencilBuffer;
  14890. textures.push(depthTexture);
  14891. this._internalTexturesCache.push(depthTexture);
  14892. }
  14893. gl.drawBuffers(attachments);
  14894. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14895. this.bindUnboundFramebuffer(null);
  14896. this.resetTextureCache();
  14897. return textures;
  14898. };
  14899. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  14900. if (samples === void 0) { samples = 1; }
  14901. var depthStencilBuffer = null;
  14902. var gl = this._gl;
  14903. // Create the depth/stencil buffer
  14904. if (generateStencilBuffer) {
  14905. depthStencilBuffer = gl.createRenderbuffer();
  14906. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14907. if (samples > 1) {
  14908. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  14909. }
  14910. else {
  14911. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  14912. }
  14913. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14914. }
  14915. else if (generateDepthBuffer) {
  14916. depthStencilBuffer = gl.createRenderbuffer();
  14917. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  14918. if (samples > 1) {
  14919. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  14920. }
  14921. else {
  14922. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  14923. }
  14924. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  14925. }
  14926. return depthStencilBuffer;
  14927. };
  14928. /**
  14929. * Updates the sample count of a render target texture
  14930. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14931. * @param texture defines the texture to update
  14932. * @param samples defines the sample count to set
  14933. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  14934. */
  14935. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  14936. if (this.webGLVersion < 2 || !texture) {
  14937. return 1;
  14938. }
  14939. if (texture.samples === samples) {
  14940. return samples;
  14941. }
  14942. var gl = this._gl;
  14943. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14944. // Dispose previous render buffers
  14945. if (texture._depthStencilBuffer) {
  14946. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14947. texture._depthStencilBuffer = null;
  14948. }
  14949. if (texture._MSAAFramebuffer) {
  14950. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14951. texture._MSAAFramebuffer = null;
  14952. }
  14953. if (texture._MSAARenderBuffer) {
  14954. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14955. texture._MSAARenderBuffer = null;
  14956. }
  14957. if (samples > 1) {
  14958. var framebuffer = gl.createFramebuffer();
  14959. if (!framebuffer) {
  14960. throw new Error("Unable to create multi sampled framebuffer");
  14961. }
  14962. texture._MSAAFramebuffer = framebuffer;
  14963. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  14964. var colorRenderbuffer = gl.createRenderbuffer();
  14965. if (!colorRenderbuffer) {
  14966. throw new Error("Unable to create multi sampled framebuffer");
  14967. }
  14968. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  14969. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  14970. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  14971. texture._MSAARenderBuffer = colorRenderbuffer;
  14972. }
  14973. else {
  14974. this.bindUnboundFramebuffer(texture._framebuffer);
  14975. }
  14976. texture.samples = samples;
  14977. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  14978. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14979. this.bindUnboundFramebuffer(null);
  14980. return samples;
  14981. };
  14982. /**
  14983. * Update the sample count for a given multiple render target texture
  14984. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  14985. * @param textures defines the textures to update
  14986. * @param samples defines the sample count to set
  14987. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  14988. */
  14989. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  14990. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  14991. return 1;
  14992. }
  14993. if (textures[0].samples === samples) {
  14994. return samples;
  14995. }
  14996. var gl = this._gl;
  14997. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  14998. // Dispose previous render buffers
  14999. if (textures[0]._depthStencilBuffer) {
  15000. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15001. textures[0]._depthStencilBuffer = null;
  15002. }
  15003. if (textures[0]._MSAAFramebuffer) {
  15004. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15005. textures[0]._MSAAFramebuffer = null;
  15006. }
  15007. for (var i = 0; i < textures.length; i++) {
  15008. if (textures[i]._MSAARenderBuffer) {
  15009. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15010. textures[i]._MSAARenderBuffer = null;
  15011. }
  15012. }
  15013. if (samples > 1) {
  15014. var framebuffer = gl.createFramebuffer();
  15015. if (!framebuffer) {
  15016. throw new Error("Unable to create multi sampled framebuffer");
  15017. }
  15018. this.bindUnboundFramebuffer(framebuffer);
  15019. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15020. var attachments = [];
  15021. for (var i = 0; i < textures.length; i++) {
  15022. var texture = textures[i];
  15023. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15024. var colorRenderbuffer = gl.createRenderbuffer();
  15025. if (!colorRenderbuffer) {
  15026. throw new Error("Unable to create multi sampled framebuffer");
  15027. }
  15028. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15029. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15030. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15031. texture._MSAAFramebuffer = framebuffer;
  15032. texture._MSAARenderBuffer = colorRenderbuffer;
  15033. texture.samples = samples;
  15034. texture._depthStencilBuffer = depthStencilBuffer;
  15035. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15036. attachments.push(attachment);
  15037. }
  15038. gl.drawBuffers(attachments);
  15039. }
  15040. else {
  15041. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15042. }
  15043. this.bindUnboundFramebuffer(null);
  15044. return samples;
  15045. };
  15046. /** @ignore */
  15047. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15048. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15049. };
  15050. /** @ignore */
  15051. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15052. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15053. };
  15054. /**
  15055. * Creates a new render target cube texture
  15056. * @param size defines the size of the texture
  15057. * @param options defines the options used to create the texture
  15058. * @returns a new render target cube texture stored in an InternalTexture
  15059. */
  15060. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15061. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15062. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15063. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15064. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15065. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15066. }
  15067. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15068. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15069. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15070. }
  15071. var gl = this._gl;
  15072. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15073. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15074. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15075. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15076. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15077. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15078. }
  15079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15080. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15081. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15082. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15083. for (var face = 0; face < 6; face++) {
  15084. 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);
  15085. }
  15086. // Create the framebuffer
  15087. var framebuffer = gl.createFramebuffer();
  15088. this.bindUnboundFramebuffer(framebuffer);
  15089. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15090. // MipMaps
  15091. if (fullOptions.generateMipMaps) {
  15092. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15093. }
  15094. // Unbind
  15095. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15096. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15097. this.bindUnboundFramebuffer(null);
  15098. texture._framebuffer = framebuffer;
  15099. texture.width = size;
  15100. texture.height = size;
  15101. texture.isReady = true;
  15102. texture.isCube = true;
  15103. texture.samples = 1;
  15104. texture.generateMipMaps = fullOptions.generateMipMaps;
  15105. texture.samplingMode = fullOptions.samplingMode;
  15106. texture.type = fullOptions.type;
  15107. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15108. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15109. this._internalTexturesCache.push(texture);
  15110. return texture;
  15111. };
  15112. /**
  15113. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15114. * @param rootUrl defines the url where the file to load is located
  15115. * @param scene defines the current scene
  15116. * @param scale defines scale to apply to the mip map selection
  15117. * @param offset defines offset to apply to the mip map selection
  15118. * @param onLoad defines an optional callback raised when the texture is loaded
  15119. * @param onError defines an optional callback raised if there is an issue to load the texture
  15120. * @param format defines the format of the data
  15121. * @param forcedExtension defines the extension to use to pick the right loader
  15122. * @returns the cube texture as an InternalTexture
  15123. */
  15124. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15125. var _this = this;
  15126. if (onLoad === void 0) { onLoad = null; }
  15127. if (onError === void 0) { onError = null; }
  15128. if (forcedExtension === void 0) { forcedExtension = null; }
  15129. var callback = function (loadData) {
  15130. if (!loadData) {
  15131. if (onLoad) {
  15132. onLoad(null);
  15133. }
  15134. return;
  15135. }
  15136. var texture = loadData.texture;
  15137. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15138. texture._lodGenerationScale = scale;
  15139. texture._lodGenerationOffset = offset;
  15140. if (_this._caps.textureLOD) {
  15141. // Do not add extra process if texture lod is supported.
  15142. if (onLoad) {
  15143. onLoad(texture);
  15144. }
  15145. return;
  15146. }
  15147. var mipSlices = 3;
  15148. var gl = _this._gl;
  15149. var width = loadData.width;
  15150. if (!width) {
  15151. return;
  15152. }
  15153. var textures = [];
  15154. for (var i = 0; i < mipSlices; i++) {
  15155. //compute LOD from even spacing in smoothness (matching shader calculation)
  15156. var smoothness = i / (mipSlices - 1);
  15157. var roughness = 1 - smoothness;
  15158. var minLODIndex = offset; // roughness = 0
  15159. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15160. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15161. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15162. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15163. glTextureFromLod.isCube = true;
  15164. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15165. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15166. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15167. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15169. if (loadData.isDDS) {
  15170. var info = loadData.info;
  15171. var data = loadData.data;
  15172. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15173. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15174. }
  15175. else {
  15176. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15177. }
  15178. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15179. // Wrap in a base texture for easy binding.
  15180. var lodTexture = new BABYLON.BaseTexture(scene);
  15181. lodTexture.isCube = true;
  15182. lodTexture._texture = glTextureFromLod;
  15183. glTextureFromLod.isReady = true;
  15184. textures.push(lodTexture);
  15185. }
  15186. texture._lodTextureHigh = textures[2];
  15187. texture._lodTextureMid = textures[1];
  15188. texture._lodTextureLow = textures[0];
  15189. if (onLoad) {
  15190. onLoad(texture);
  15191. }
  15192. };
  15193. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15194. };
  15195. /**
  15196. * Creates a cube texture
  15197. * @param rootUrl defines the url where the files to load is located
  15198. * @param scene defines the current scene
  15199. * @param files defines the list of files to load (1 per face)
  15200. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15201. * @param onLoad defines an optional callback raised when the texture is loaded
  15202. * @param onError defines an optional callback raised if there is an issue to load the texture
  15203. * @param format defines the format of the data
  15204. * @param forcedExtension defines the extension to use to pick the right loader
  15205. * @returns the cube texture as an InternalTexture
  15206. */
  15207. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15208. var _this = this;
  15209. if (onLoad === void 0) { onLoad = null; }
  15210. if (onError === void 0) { onError = null; }
  15211. if (forcedExtension === void 0) { forcedExtension = null; }
  15212. var gl = this._gl;
  15213. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15214. texture.isCube = true;
  15215. texture.url = rootUrl;
  15216. texture.generateMipMaps = !noMipmap;
  15217. if (!this._doNotHandleContextLost) {
  15218. texture._extension = forcedExtension;
  15219. texture._files = files;
  15220. }
  15221. var isKTX = false;
  15222. var isDDS = false;
  15223. var lastDot = rootUrl.lastIndexOf('.');
  15224. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15225. if (this._textureFormatInUse) {
  15226. extension = this._textureFormatInUse;
  15227. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15228. isKTX = true;
  15229. }
  15230. else {
  15231. isDDS = (extension === ".dds");
  15232. }
  15233. var onerror = function (request, exception) {
  15234. if (onError && request) {
  15235. onError(request.status + " " + request.statusText, exception);
  15236. }
  15237. };
  15238. if (isKTX) {
  15239. this._loadFile(rootUrl, function (data) {
  15240. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15241. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15242. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15243. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15244. ktx.uploadLevels(_this._gl, !noMipmap);
  15245. _this.setCubeMapTextureParams(gl, loadMipmap);
  15246. texture.width = ktx.pixelWidth;
  15247. texture.height = ktx.pixelHeight;
  15248. texture.isReady = true;
  15249. }, undefined, undefined, true, onerror);
  15250. }
  15251. else if (isDDS) {
  15252. if (files && files.length === 6) {
  15253. this._cascadeLoadFiles(scene, function (imgs) {
  15254. var info;
  15255. var loadMipmap = false;
  15256. var width = 0;
  15257. for (var index = 0; index < imgs.length; index++) {
  15258. var data = imgs[index];
  15259. info = BABYLON.DDSTools.GetDDSInfo(data);
  15260. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15261. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15262. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15263. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15264. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15265. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15266. }
  15267. texture.width = info.width;
  15268. texture.height = info.height;
  15269. texture.type = info.textureType;
  15270. width = info.width;
  15271. }
  15272. _this.setCubeMapTextureParams(gl, loadMipmap);
  15273. texture.isReady = true;
  15274. if (onLoad) {
  15275. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15276. }
  15277. }, files, onError);
  15278. }
  15279. else {
  15280. this._loadFile(rootUrl, function (data) {
  15281. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15282. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15283. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15284. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15285. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15286. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15287. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15288. }
  15289. _this.setCubeMapTextureParams(gl, loadMipmap);
  15290. texture.width = info.width;
  15291. texture.height = info.height;
  15292. texture.isReady = true;
  15293. texture.type = info.textureType;
  15294. if (onLoad) {
  15295. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15296. }
  15297. }, undefined, undefined, true, onerror);
  15298. }
  15299. }
  15300. else {
  15301. if (!files) {
  15302. throw new Error("Cannot load cubemap because files were not defined");
  15303. }
  15304. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15305. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15306. var height = width;
  15307. _this._prepareWorkingCanvas();
  15308. if (!_this._workingCanvas || !_this._workingContext) {
  15309. return;
  15310. }
  15311. _this._workingCanvas.width = width;
  15312. _this._workingCanvas.height = height;
  15313. var faces = [
  15314. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15315. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15316. ];
  15317. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15318. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15319. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15320. for (var index = 0; index < faces.length; index++) {
  15321. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15322. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15323. }
  15324. if (!noMipmap) {
  15325. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15326. }
  15327. _this.setCubeMapTextureParams(gl, !noMipmap);
  15328. texture.width = width;
  15329. texture.height = height;
  15330. texture.isReady = true;
  15331. if (format) {
  15332. texture.format = format;
  15333. }
  15334. texture.onLoadedObservable.notifyObservers(texture);
  15335. texture.onLoadedObservable.clear();
  15336. if (onLoad) {
  15337. onLoad();
  15338. }
  15339. }, files, onError);
  15340. }
  15341. this._internalTexturesCache.push(texture);
  15342. return texture;
  15343. };
  15344. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15345. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15346. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15347. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15348. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15349. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15350. // this.resetTextureCache();
  15351. };
  15352. /**
  15353. * Update a raw cube texture
  15354. * @param texture defines the texture to udpdate
  15355. * @param data defines the data to store
  15356. * @param format defines the data format
  15357. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15358. * @param invertY defines if data must be stored with Y axis inverted
  15359. * @param compression defines the compression used (null by default)
  15360. * @param level defines which level of the texture to update
  15361. */
  15362. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15363. if (compression === void 0) { compression = null; }
  15364. if (level === void 0) { level = 0; }
  15365. texture._bufferViewArray = data;
  15366. texture.format = format;
  15367. texture.type = type;
  15368. texture.invertY = invertY;
  15369. texture._compression = compression;
  15370. var gl = this._gl;
  15371. var textureType = this._getWebGLTextureType(type);
  15372. var internalFormat = this._getInternalFormat(format);
  15373. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15374. var needConversion = false;
  15375. if (internalFormat === gl.RGB) {
  15376. internalFormat = gl.RGBA;
  15377. needConversion = true;
  15378. }
  15379. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15380. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15381. if (texture.width % 4 !== 0) {
  15382. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15383. }
  15384. // Data are known to be in +X +Y +Z -X -Y -Z
  15385. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15386. var faceData = data[faceIndex];
  15387. if (compression) {
  15388. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15389. }
  15390. else {
  15391. if (needConversion) {
  15392. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15393. }
  15394. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15395. }
  15396. }
  15397. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15398. if (isPot && texture.generateMipMaps && level === 0) {
  15399. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15400. }
  15401. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15402. // this.resetTextureCache();
  15403. texture.isReady = true;
  15404. };
  15405. /**
  15406. * Creates a new raw cube texture
  15407. * @param data defines the array of data to use to create each face
  15408. * @param size defines the size of the textures
  15409. * @param format defines the format of the data
  15410. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15411. * @param generateMipMaps defines if the engine should generate the mip levels
  15412. * @param invertY defines if data must be stored with Y axis inverted
  15413. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15414. * @param compression defines the compression used (null by default)
  15415. * @returns the cube texture as an InternalTexture
  15416. */
  15417. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15418. if (compression === void 0) { compression = null; }
  15419. var gl = this._gl;
  15420. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15421. texture.isCube = true;
  15422. texture.generateMipMaps = generateMipMaps;
  15423. texture.format = format;
  15424. texture.type = type;
  15425. if (!this._doNotHandleContextLost) {
  15426. texture._bufferViewArray = data;
  15427. }
  15428. var textureType = this._getWebGLTextureType(type);
  15429. var internalFormat = this._getInternalFormat(format);
  15430. if (internalFormat === gl.RGB) {
  15431. internalFormat = gl.RGBA;
  15432. }
  15433. var width = size;
  15434. var height = width;
  15435. texture.width = width;
  15436. texture.height = height;
  15437. // Double check on POT to generate Mips.
  15438. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15439. if (!isPot) {
  15440. generateMipMaps = false;
  15441. }
  15442. // Upload data if needed. The texture won't be ready until then.
  15443. if (data) {
  15444. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15445. }
  15446. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15447. // Filters
  15448. if (data && generateMipMaps) {
  15449. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15450. }
  15451. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15452. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15453. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15454. }
  15455. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15456. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15457. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15458. }
  15459. else {
  15460. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15463. }
  15464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15466. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15467. return texture;
  15468. };
  15469. /**
  15470. * Creates a new raw cube texture from a specified url
  15471. * @param url defines the url where the data is located
  15472. * @param scene defines the current scene
  15473. * @param size defines the size of the textures
  15474. * @param format defines the format of the data
  15475. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15476. * @param noMipmap defines if the engine should avoid generating the mip levels
  15477. * @param callback defines a callback used to extract texture data from loaded data
  15478. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15479. * @param onLoad defines a callback called when texture is loaded
  15480. * @param onError defines a callback called if there is an error
  15481. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15482. * @param invertY defines if data must be stored with Y axis inverted
  15483. * @returns the cube texture as an InternalTexture
  15484. */
  15485. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15486. var _this = this;
  15487. if (onLoad === void 0) { onLoad = null; }
  15488. if (onError === void 0) { onError = null; }
  15489. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15490. if (invertY === void 0) { invertY = false; }
  15491. var gl = this._gl;
  15492. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15493. scene._addPendingData(texture);
  15494. texture.url = url;
  15495. this._internalTexturesCache.push(texture);
  15496. var onerror = function (request, exception) {
  15497. scene._removePendingData(texture);
  15498. if (onError && request) {
  15499. onError(request.status + " " + request.statusText, exception);
  15500. }
  15501. };
  15502. var internalCallback = function (data) {
  15503. var width = texture.width;
  15504. var faceDataArrays = callback(data);
  15505. if (!faceDataArrays) {
  15506. return;
  15507. }
  15508. if (mipmapGenerator) {
  15509. var textureType = _this._getWebGLTextureType(type);
  15510. var internalFormat = _this._getInternalFormat(format);
  15511. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15512. var needConversion = false;
  15513. if (internalFormat === gl.RGB) {
  15514. internalFormat = gl.RGBA;
  15515. needConversion = true;
  15516. }
  15517. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15518. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15519. var mipData = mipmapGenerator(faceDataArrays);
  15520. for (var level = 0; level < mipData.length; level++) {
  15521. var mipSize = width >> level;
  15522. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15523. var mipFaceData = mipData[level][faceIndex];
  15524. if (needConversion) {
  15525. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15526. }
  15527. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15528. }
  15529. }
  15530. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15531. }
  15532. else {
  15533. texture.generateMipMaps = !noMipmap;
  15534. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15535. }
  15536. texture.isReady = true;
  15537. // this.resetTextureCache();
  15538. scene._removePendingData(texture);
  15539. if (onLoad) {
  15540. onLoad();
  15541. }
  15542. };
  15543. this._loadFile(url, function (data) {
  15544. internalCallback(data);
  15545. }, undefined, scene.database, true, onerror);
  15546. return texture;
  15547. };
  15548. ;
  15549. /**
  15550. * Update a raw 3D texture
  15551. * @param texture defines the texture to update
  15552. * @param data defines the data to store
  15553. * @param format defines the data format
  15554. * @param invertY defines if data must be stored with Y axis inverted
  15555. * @param compression defines the used compression (can be null)
  15556. */
  15557. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15558. if (compression === void 0) { compression = null; }
  15559. var internalFormat = this._getInternalFormat(format);
  15560. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15561. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15562. if (!this._doNotHandleContextLost) {
  15563. texture._bufferView = data;
  15564. texture.format = format;
  15565. texture.invertY = invertY;
  15566. texture._compression = compression;
  15567. }
  15568. if (texture.width % 4 !== 0) {
  15569. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15570. }
  15571. if (compression && data) {
  15572. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15573. }
  15574. else {
  15575. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15576. }
  15577. if (texture.generateMipMaps) {
  15578. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15579. }
  15580. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15581. // this.resetTextureCache();
  15582. texture.isReady = true;
  15583. };
  15584. /**
  15585. * Creates a new raw 3D texture
  15586. * @param data defines the data used to create the texture
  15587. * @param width defines the width of the texture
  15588. * @param height defines the height of the texture
  15589. * @param depth defines the depth of the texture
  15590. * @param format defines the format of the texture
  15591. * @param generateMipMaps defines if the engine must generate mip levels
  15592. * @param invertY defines if data must be stored with Y axis inverted
  15593. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15594. * @param compression defines the compressed used (can be null)
  15595. * @returns a new raw 3D texture (stored in an InternalTexture)
  15596. */
  15597. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15598. if (compression === void 0) { compression = null; }
  15599. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15600. texture.baseWidth = width;
  15601. texture.baseHeight = height;
  15602. texture.baseDepth = depth;
  15603. texture.width = width;
  15604. texture.height = height;
  15605. texture.depth = depth;
  15606. texture.format = format;
  15607. texture.generateMipMaps = generateMipMaps;
  15608. texture.samplingMode = samplingMode;
  15609. texture.is3D = true;
  15610. if (!this._doNotHandleContextLost) {
  15611. texture._bufferView = data;
  15612. }
  15613. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15614. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15615. // Filters
  15616. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15617. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15618. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15619. if (generateMipMaps) {
  15620. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15621. }
  15622. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15623. this._internalTexturesCache.push(texture);
  15624. return texture;
  15625. };
  15626. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15627. var gl = this._gl;
  15628. if (!gl) {
  15629. return;
  15630. }
  15631. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15632. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15633. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15634. if (!noMipmap && !isCompressed) {
  15635. gl.generateMipmap(gl.TEXTURE_2D);
  15636. }
  15637. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15638. // this.resetTextureCache();
  15639. if (scene) {
  15640. scene._removePendingData(texture);
  15641. }
  15642. texture.onLoadedObservable.notifyObservers(texture);
  15643. texture.onLoadedObservable.clear();
  15644. };
  15645. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15646. var _this = this;
  15647. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15648. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15649. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15650. var gl = this._gl;
  15651. if (!gl) {
  15652. return;
  15653. }
  15654. if (!texture._webGLTexture) {
  15655. // this.resetTextureCache();
  15656. if (scene) {
  15657. scene._removePendingData(texture);
  15658. }
  15659. return;
  15660. }
  15661. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15662. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15663. texture.baseWidth = width;
  15664. texture.baseHeight = height;
  15665. texture.width = potWidth;
  15666. texture.height = potHeight;
  15667. texture.isReady = true;
  15668. if (processFunction(potWidth, potHeight, function () {
  15669. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15670. })) {
  15671. // Returning as texture needs extra async steps
  15672. return;
  15673. }
  15674. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15675. };
  15676. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15677. // Create new RGBA data container.
  15678. var rgbaData;
  15679. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15680. rgbaData = new Float32Array(width * height * 4);
  15681. }
  15682. else {
  15683. rgbaData = new Uint32Array(width * height * 4);
  15684. }
  15685. // Convert each pixel.
  15686. for (var x = 0; x < width; x++) {
  15687. for (var y = 0; y < height; y++) {
  15688. var index = (y * width + x) * 3;
  15689. var newIndex = (y * width + x) * 4;
  15690. // Map Old Value to new value.
  15691. rgbaData[newIndex + 0] = rgbData[index + 0];
  15692. rgbaData[newIndex + 1] = rgbData[index + 1];
  15693. rgbaData[newIndex + 2] = rgbData[index + 2];
  15694. // Add fully opaque alpha channel.
  15695. rgbaData[newIndex + 3] = 1;
  15696. }
  15697. }
  15698. return rgbaData;
  15699. };
  15700. /** @ignore */
  15701. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15702. var gl = this._gl;
  15703. if (texture._framebuffer) {
  15704. gl.deleteFramebuffer(texture._framebuffer);
  15705. texture._framebuffer = null;
  15706. }
  15707. if (texture._depthStencilBuffer) {
  15708. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15709. texture._depthStencilBuffer = null;
  15710. }
  15711. if (texture._MSAAFramebuffer) {
  15712. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15713. texture._MSAAFramebuffer = null;
  15714. }
  15715. if (texture._MSAARenderBuffer) {
  15716. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15717. texture._MSAARenderBuffer = null;
  15718. }
  15719. };
  15720. /** @ignore */
  15721. Engine.prototype._releaseTexture = function (texture) {
  15722. var gl = this._gl;
  15723. this._releaseFramebufferObjects(texture);
  15724. gl.deleteTexture(texture._webGLTexture);
  15725. // Unbind channels
  15726. this.unbindAllTextures();
  15727. var index = this._internalTexturesCache.indexOf(texture);
  15728. if (index !== -1) {
  15729. this._internalTexturesCache.splice(index, 1);
  15730. }
  15731. // Integrated fixed lod samplers.
  15732. if (texture._lodTextureHigh) {
  15733. texture._lodTextureHigh.dispose();
  15734. }
  15735. if (texture._lodTextureMid) {
  15736. texture._lodTextureMid.dispose();
  15737. }
  15738. if (texture._lodTextureLow) {
  15739. texture._lodTextureLow.dispose();
  15740. }
  15741. // Set output texture of post process to null if the texture has been released/disposed
  15742. this.scenes.forEach(function (scene) {
  15743. scene.postProcesses.forEach(function (postProcess) {
  15744. if (postProcess._outputTexture == texture) {
  15745. postProcess._outputTexture = null;
  15746. }
  15747. });
  15748. scene.cameras.forEach(function (camera) {
  15749. camera._postProcesses.forEach(function (postProcess) {
  15750. if (postProcess) {
  15751. if (postProcess._outputTexture == texture) {
  15752. postProcess._outputTexture = null;
  15753. }
  15754. }
  15755. });
  15756. });
  15757. });
  15758. };
  15759. Engine.prototype.setProgram = function (program) {
  15760. if (this._currentProgram !== program) {
  15761. this._gl.useProgram(program);
  15762. this._currentProgram = program;
  15763. }
  15764. };
  15765. /**
  15766. * Binds an effect to the webGL context
  15767. * @param effect defines the effect to bind
  15768. */
  15769. Engine.prototype.bindSamplers = function (effect) {
  15770. this.setProgram(effect.getProgram());
  15771. var samplers = effect.getSamplers();
  15772. for (var index = 0; index < samplers.length; index++) {
  15773. var uniform = effect.getUniform(samplers[index]);
  15774. if (uniform) {
  15775. this._boundUniforms[index] = uniform;
  15776. }
  15777. }
  15778. this._currentEffect = null;
  15779. };
  15780. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  15781. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  15782. return;
  15783. }
  15784. // Remove
  15785. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15786. // Bind last to it
  15787. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  15788. // Bind to dummy
  15789. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  15790. };
  15791. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  15792. if (!internalTexture) {
  15793. return -1;
  15794. }
  15795. internalTexture._initialSlot = channel;
  15796. if (this.disableTextureBindingOptimization) {
  15797. if (channel !== internalTexture._designatedSlot) {
  15798. this._textureCollisions.addCount(1, false);
  15799. }
  15800. }
  15801. else {
  15802. if (channel !== internalTexture._designatedSlot) {
  15803. if (internalTexture._designatedSlot > -1) {
  15804. return internalTexture._designatedSlot;
  15805. }
  15806. else {
  15807. // No slot for this texture, let's pick a new one (if we find a free slot)
  15808. if (this._nextFreeTextureSlots.length) {
  15809. return this._nextFreeTextureSlots[0];
  15810. }
  15811. // We need to recycle the oldest bound texture, sorry.
  15812. this._textureCollisions.addCount(1, false);
  15813. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  15814. }
  15815. }
  15816. }
  15817. return channel;
  15818. };
  15819. Engine.prototype._linkTrackers = function (previous, next) {
  15820. previous.next = next;
  15821. next.previous = previous;
  15822. };
  15823. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  15824. var currentSlot = internalTexture._designatedSlot;
  15825. if (currentSlot === -1) {
  15826. return -1;
  15827. }
  15828. internalTexture._designatedSlot = -1;
  15829. if (this.disableTextureBindingOptimization) {
  15830. return -1;
  15831. }
  15832. // Remove from bound list
  15833. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15834. // Free the slot
  15835. this._boundTexturesCache[currentSlot] = null;
  15836. this._nextFreeTextureSlots.push(currentSlot);
  15837. return currentSlot;
  15838. };
  15839. Engine.prototype._activateCurrentTexture = function () {
  15840. if (this._currentTextureChannel !== this._activeChannel) {
  15841. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  15842. this._currentTextureChannel = this._activeChannel;
  15843. }
  15844. };
  15845. /** @ignore */
  15846. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  15847. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  15848. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  15849. this._activeChannel = texture._designatedSlot;
  15850. }
  15851. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  15852. var isTextureForRendering = texture && texture._initialSlot > -1;
  15853. if (currentTextureBound !== texture) {
  15854. if (currentTextureBound) {
  15855. this._removeDesignatedSlot(currentTextureBound);
  15856. }
  15857. this._activateCurrentTexture();
  15858. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  15859. this._boundTexturesCache[this._activeChannel] = texture;
  15860. if (texture) {
  15861. if (!this.disableTextureBindingOptimization) {
  15862. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  15863. if (slotIndex > -1) {
  15864. this._nextFreeTextureSlots.splice(slotIndex, 1);
  15865. }
  15866. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  15867. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  15868. }
  15869. texture._designatedSlot = this._activeChannel;
  15870. }
  15871. }
  15872. else if (forTextureDataUpdate) {
  15873. this._activateCurrentTexture();
  15874. }
  15875. if (isTextureForRendering && !forTextureDataUpdate) {
  15876. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  15877. }
  15878. };
  15879. /** @ignore */
  15880. Engine.prototype._bindTexture = function (channel, texture) {
  15881. if (channel < 0) {
  15882. return;
  15883. }
  15884. if (texture) {
  15885. channel = this._getCorrectTextureChannel(channel, texture);
  15886. }
  15887. this._activeChannel = channel;
  15888. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  15889. };
  15890. /**
  15891. * Sets a texture to the webGL context from a postprocess
  15892. * @param channel defines the channel to use
  15893. * @param postProcess defines the source postprocess
  15894. */
  15895. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  15896. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  15897. };
  15898. /**
  15899. * Binds the output of the passed in post process to the texture channel specified
  15900. * @param channel The channel the texture should be bound to
  15901. * @param postProcess The post process which's output should be bound
  15902. */
  15903. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  15904. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  15905. };
  15906. /**
  15907. * Unbind all textures from the webGL context
  15908. */
  15909. Engine.prototype.unbindAllTextures = function () {
  15910. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  15911. this._activeChannel = channel;
  15912. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15913. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15914. if (this.webGLVersion > 1) {
  15915. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15916. }
  15917. }
  15918. };
  15919. /**
  15920. * Sets a texture to the according uniform.
  15921. * @param channel The texture channel
  15922. * @param uniform The uniform to set
  15923. * @param texture The texture to apply
  15924. */
  15925. Engine.prototype.setTexture = function (channel, uniform, texture) {
  15926. if (channel < 0) {
  15927. return;
  15928. }
  15929. if (uniform) {
  15930. this._boundUniforms[channel] = uniform;
  15931. }
  15932. this._setTexture(channel, texture);
  15933. };
  15934. /**
  15935. * Sets a depth stencil texture from a render target to the according uniform.
  15936. * @param channel The texture channel
  15937. * @param uniform The uniform to set
  15938. * @param texture The render target texture containing the depth stencil texture to apply
  15939. */
  15940. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  15941. if (channel < 0) {
  15942. return;
  15943. }
  15944. if (uniform) {
  15945. this._boundUniforms[channel] = uniform;
  15946. }
  15947. if (!texture || !texture.depthStencilTexture) {
  15948. this._setTexture(channel, null);
  15949. }
  15950. else {
  15951. this._setTexture(channel, texture, false, true);
  15952. }
  15953. };
  15954. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  15955. var uniform = this._boundUniforms[sourceSlot];
  15956. if (uniform._currentState === destination) {
  15957. return;
  15958. }
  15959. this._gl.uniform1i(uniform, destination);
  15960. uniform._currentState = destination;
  15961. };
  15962. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  15963. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  15964. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  15965. // Not ready?
  15966. if (!texture) {
  15967. if (this._boundTexturesCache[channel] != null) {
  15968. this._activeChannel = channel;
  15969. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15970. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15971. if (this.webGLVersion > 1) {
  15972. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15973. }
  15974. }
  15975. return false;
  15976. }
  15977. // Video
  15978. if (texture.video) {
  15979. this._activeChannel = channel;
  15980. texture.update();
  15981. }
  15982. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  15983. texture.delayLoad();
  15984. return false;
  15985. }
  15986. var internalTexture;
  15987. if (depthStencilTexture) {
  15988. internalTexture = texture.depthStencilTexture;
  15989. }
  15990. else if (texture.isReady()) {
  15991. internalTexture = texture.getInternalTexture();
  15992. }
  15993. else if (texture.isCube) {
  15994. internalTexture = this.emptyCubeTexture;
  15995. }
  15996. else if (texture.is3D) {
  15997. internalTexture = this.emptyTexture3D;
  15998. }
  15999. else {
  16000. internalTexture = this.emptyTexture;
  16001. }
  16002. if (!isPartOfTextureArray) {
  16003. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16004. }
  16005. if (this._boundTexturesCache[channel] === internalTexture) {
  16006. this._moveBoundTextureOnTop(internalTexture);
  16007. if (!isPartOfTextureArray) {
  16008. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16009. }
  16010. return false;
  16011. }
  16012. this._activeChannel = channel;
  16013. if (internalTexture && internalTexture.is3D) {
  16014. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16015. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16016. internalTexture._cachedWrapU = texture.wrapU;
  16017. switch (texture.wrapU) {
  16018. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16019. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  16020. break;
  16021. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16022. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  16023. break;
  16024. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16025. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  16026. break;
  16027. }
  16028. }
  16029. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16030. internalTexture._cachedWrapV = texture.wrapV;
  16031. switch (texture.wrapV) {
  16032. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16033. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  16034. break;
  16035. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16036. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  16037. break;
  16038. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16039. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  16040. break;
  16041. }
  16042. }
  16043. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16044. internalTexture._cachedWrapR = texture.wrapR;
  16045. switch (texture.wrapR) {
  16046. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16047. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  16048. break;
  16049. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16050. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  16051. break;
  16052. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16053. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  16054. break;
  16055. }
  16056. }
  16057. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16058. }
  16059. else if (internalTexture && internalTexture.isCube) {
  16060. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16061. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16062. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16063. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16064. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16065. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  16066. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16067. }
  16068. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16069. }
  16070. else {
  16071. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16072. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16073. internalTexture._cachedWrapU = texture.wrapU;
  16074. switch (texture.wrapU) {
  16075. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16076. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  16077. break;
  16078. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16079. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  16080. break;
  16081. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16082. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  16083. break;
  16084. }
  16085. }
  16086. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16087. internalTexture._cachedWrapV = texture.wrapV;
  16088. switch (texture.wrapV) {
  16089. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16090. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  16091. break;
  16092. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16093. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  16094. break;
  16095. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16096. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  16097. break;
  16098. }
  16099. }
  16100. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16101. }
  16102. return true;
  16103. };
  16104. /**
  16105. * Sets an array of texture to the webGL context
  16106. * @param channel defines the channel where the texture array must be set
  16107. * @param uniform defines the associated uniform location
  16108. * @param textures defines the array of textures to bind
  16109. */
  16110. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16111. if (channel < 0 || !uniform) {
  16112. return;
  16113. }
  16114. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16115. this._textureUnits = new Int32Array(textures.length);
  16116. }
  16117. for (var i = 0; i < textures.length; i++) {
  16118. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16119. }
  16120. this._gl.uniform1iv(uniform, this._textureUnits);
  16121. for (var index = 0; index < textures.length; index++) {
  16122. this._setTexture(this._textureUnits[index], textures[index], true);
  16123. }
  16124. };
  16125. /** @ignore */
  16126. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  16127. var internalTexture = texture.getInternalTexture();
  16128. if (!internalTexture) {
  16129. return;
  16130. }
  16131. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16132. var value = texture.anisotropicFilteringLevel;
  16133. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16134. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16135. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16136. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16137. }
  16138. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16139. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  16140. internalTexture._cachedAnisotropicFilteringLevel = value;
  16141. }
  16142. };
  16143. /**
  16144. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16145. * @param x defines the x coordinate of the rectangle where pixels must be read
  16146. * @param y defines the y coordinate of the rectangle where pixels must be read
  16147. * @param width defines the width of the rectangle where pixels must be read
  16148. * @param height defines the height of the rectangle where pixels must be read
  16149. * @returns a Uint8Array containing RGBA colors
  16150. */
  16151. Engine.prototype.readPixels = function (x, y, width, height) {
  16152. var data = new Uint8Array(height * width * 4);
  16153. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16154. return data;
  16155. };
  16156. /**
  16157. * Add an externaly attached data from its key.
  16158. * This method call will fail and return false, if such key already exists.
  16159. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16160. * @param key the unique key that identifies the data
  16161. * @param data the data object to associate to the key for this Engine instance
  16162. * @return true if no such key were already present and the data was added successfully, false otherwise
  16163. */
  16164. Engine.prototype.addExternalData = function (key, data) {
  16165. if (!this._externalData) {
  16166. this._externalData = new BABYLON.StringDictionary();
  16167. }
  16168. return this._externalData.add(key, data);
  16169. };
  16170. /**
  16171. * Get an externaly attached data from its key
  16172. * @param key the unique key that identifies the data
  16173. * @return the associated data, if present (can be null), or undefined if not present
  16174. */
  16175. Engine.prototype.getExternalData = function (key) {
  16176. if (!this._externalData) {
  16177. this._externalData = new BABYLON.StringDictionary();
  16178. }
  16179. return this._externalData.get(key);
  16180. };
  16181. /**
  16182. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16183. * @param key the unique key that identifies the data
  16184. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16185. * @return the associated data, can be null if the factory returned null.
  16186. */
  16187. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16188. if (!this._externalData) {
  16189. this._externalData = new BABYLON.StringDictionary();
  16190. }
  16191. return this._externalData.getOrAddWithFactory(key, factory);
  16192. };
  16193. /**
  16194. * Remove an externaly attached data from the Engine instance
  16195. * @param key the unique key that identifies the data
  16196. * @return true if the data was successfully removed, false if it doesn't exist
  16197. */
  16198. Engine.prototype.removeExternalData = function (key) {
  16199. if (!this._externalData) {
  16200. this._externalData = new BABYLON.StringDictionary();
  16201. }
  16202. return this._externalData.remove(key);
  16203. };
  16204. /**
  16205. * Unbind all vertex attributes from the webGL context
  16206. */
  16207. Engine.prototype.unbindAllAttributes = function () {
  16208. if (this._mustWipeVertexAttributes) {
  16209. this._mustWipeVertexAttributes = false;
  16210. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16211. this._gl.disableVertexAttribArray(i);
  16212. this._vertexAttribArraysEnabled[i] = false;
  16213. this._currentBufferPointers[i].active = false;
  16214. }
  16215. return;
  16216. }
  16217. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16218. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16219. continue;
  16220. }
  16221. this._gl.disableVertexAttribArray(i);
  16222. this._vertexAttribArraysEnabled[i] = false;
  16223. this._currentBufferPointers[i].active = false;
  16224. }
  16225. };
  16226. /**
  16227. * 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
  16228. */
  16229. Engine.prototype.releaseEffects = function () {
  16230. for (var name in this._compiledEffects) {
  16231. this._deleteProgram(this._compiledEffects[name]._program);
  16232. }
  16233. this._compiledEffects = {};
  16234. };
  16235. /**
  16236. * Dispose and release all associated resources
  16237. */
  16238. Engine.prototype.dispose = function () {
  16239. this.hideLoadingUI();
  16240. this.stopRenderLoop();
  16241. // Release postProcesses
  16242. while (this.postProcesses.length) {
  16243. this.postProcesses[0].dispose();
  16244. }
  16245. // Empty texture
  16246. if (this._emptyTexture) {
  16247. this._releaseTexture(this._emptyTexture);
  16248. this._emptyTexture = null;
  16249. }
  16250. if (this._emptyCubeTexture) {
  16251. this._releaseTexture(this._emptyCubeTexture);
  16252. this._emptyCubeTexture = null;
  16253. }
  16254. // Rescale PP
  16255. if (this._rescalePostProcess) {
  16256. this._rescalePostProcess.dispose();
  16257. }
  16258. // Release scenes
  16259. while (this.scenes.length) {
  16260. this.scenes[0].dispose();
  16261. }
  16262. // Release audio engine
  16263. if (Engine.audioEngine) {
  16264. Engine.audioEngine.dispose();
  16265. }
  16266. // Release effects
  16267. this.releaseEffects();
  16268. // Unbind
  16269. this.unbindAllAttributes();
  16270. this._boundUniforms = [];
  16271. if (this._dummyFramebuffer) {
  16272. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16273. }
  16274. //WebVR
  16275. this.disableVR();
  16276. // Events
  16277. if (BABYLON.Tools.IsWindowObjectExist()) {
  16278. window.removeEventListener("blur", this._onBlur);
  16279. window.removeEventListener("focus", this._onFocus);
  16280. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16281. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16282. if (this._renderingCanvas) {
  16283. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16284. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16285. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16286. if (!this._doNotHandleContextLost) {
  16287. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16288. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16289. }
  16290. }
  16291. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16292. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16293. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16294. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16295. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16296. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16297. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16298. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16299. if (this._onVrDisplayConnect) {
  16300. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16301. if (this._onVrDisplayDisconnect) {
  16302. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16303. }
  16304. if (this._onVrDisplayPresentChange) {
  16305. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16306. }
  16307. this._onVrDisplayConnect = null;
  16308. this._onVrDisplayDisconnect = null;
  16309. }
  16310. }
  16311. // Remove from Instances
  16312. var index = Engine.Instances.indexOf(this);
  16313. if (index >= 0) {
  16314. Engine.Instances.splice(index, 1);
  16315. }
  16316. this._workingCanvas = null;
  16317. this._workingContext = null;
  16318. this._currentBufferPointers = [];
  16319. this._renderingCanvas = null;
  16320. this._currentProgram = null;
  16321. this._bindedRenderFunction = null;
  16322. this.onResizeObservable.clear();
  16323. this.onCanvasBlurObservable.clear();
  16324. this.onCanvasFocusObservable.clear();
  16325. this.onCanvasPointerOutObservable.clear();
  16326. this.onBeginFrameObservable.clear();
  16327. this.onEndFrameObservable.clear();
  16328. BABYLON.Effect.ResetCache();
  16329. // Abort active requests
  16330. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16331. var request = _a[_i];
  16332. request.abort();
  16333. }
  16334. };
  16335. // Loading screen
  16336. /**
  16337. * Display the loading screen
  16338. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16339. */
  16340. Engine.prototype.displayLoadingUI = function () {
  16341. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16342. return;
  16343. }
  16344. var loadingScreen = this.loadingScreen;
  16345. if (loadingScreen) {
  16346. loadingScreen.displayLoadingUI();
  16347. }
  16348. };
  16349. /**
  16350. * Hide the loading screen
  16351. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16352. */
  16353. Engine.prototype.hideLoadingUI = function () {
  16354. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16355. return;
  16356. }
  16357. var loadingScreen = this.loadingScreen;
  16358. if (loadingScreen) {
  16359. loadingScreen.hideLoadingUI();
  16360. }
  16361. };
  16362. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16363. /**
  16364. * Gets the current loading screen object
  16365. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16366. */
  16367. get: function () {
  16368. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16369. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16370. return this._loadingScreen;
  16371. },
  16372. /**
  16373. * Sets the current loading screen object
  16374. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16375. */
  16376. set: function (loadingScreen) {
  16377. this._loadingScreen = loadingScreen;
  16378. },
  16379. enumerable: true,
  16380. configurable: true
  16381. });
  16382. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16383. /**
  16384. * Sets the current loading screen text
  16385. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16386. */
  16387. set: function (text) {
  16388. this.loadingScreen.loadingUIText = text;
  16389. },
  16390. enumerable: true,
  16391. configurable: true
  16392. });
  16393. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16394. /**
  16395. * Sets the current loading screen background color
  16396. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16397. */
  16398. set: function (color) {
  16399. this.loadingScreen.loadingUIBackgroundColor = color;
  16400. },
  16401. enumerable: true,
  16402. configurable: true
  16403. });
  16404. /**
  16405. * Attach a new callback raised when context lost event is fired
  16406. * @param callback defines the callback to call
  16407. */
  16408. Engine.prototype.attachContextLostEvent = function (callback) {
  16409. if (this._renderingCanvas) {
  16410. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16411. }
  16412. };
  16413. /**
  16414. * Attach a new callback raised when context restored event is fired
  16415. * @param callback defines the callback to call
  16416. */
  16417. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16418. if (this._renderingCanvas) {
  16419. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16420. }
  16421. };
  16422. /**
  16423. * Gets the source code of the vertex shader associated with a specific webGL program
  16424. * @param program defines the program to use
  16425. * @returns a string containing the source code of the vertex shader associated with the program
  16426. */
  16427. Engine.prototype.getVertexShaderSource = function (program) {
  16428. var shaders = this._gl.getAttachedShaders(program);
  16429. if (!shaders) {
  16430. return null;
  16431. }
  16432. return this._gl.getShaderSource(shaders[0]);
  16433. };
  16434. /**
  16435. * Gets the source code of the fragment shader associated with a specific webGL program
  16436. * @param program defines the program to use
  16437. * @returns a string containing the source code of the fragment shader associated with the program
  16438. */
  16439. Engine.prototype.getFragmentShaderSource = function (program) {
  16440. var shaders = this._gl.getAttachedShaders(program);
  16441. if (!shaders) {
  16442. return null;
  16443. }
  16444. return this._gl.getShaderSource(shaders[1]);
  16445. };
  16446. /**
  16447. * Get the current error code of the webGL context
  16448. * @returns the error code
  16449. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16450. */
  16451. Engine.prototype.getError = function () {
  16452. return this._gl.getError();
  16453. };
  16454. // FPS
  16455. /**
  16456. * Gets the current framerate
  16457. * @returns a number representing the framerate
  16458. */
  16459. Engine.prototype.getFps = function () {
  16460. return this._fps;
  16461. };
  16462. /**
  16463. * Gets the time spent between current and previous frame
  16464. * @returns a number representing the delta time in ms
  16465. */
  16466. Engine.prototype.getDeltaTime = function () {
  16467. return this._deltaTime;
  16468. };
  16469. Engine.prototype._measureFps = function () {
  16470. this._performanceMonitor.sampleFrame();
  16471. this._fps = this._performanceMonitor.averageFPS;
  16472. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16473. };
  16474. /** @ignore */
  16475. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16476. if (faceIndex === void 0) { faceIndex = -1; }
  16477. var gl = this._gl;
  16478. if (!this._dummyFramebuffer) {
  16479. var dummy = gl.createFramebuffer();
  16480. if (!dummy) {
  16481. throw new Error("Unable to create dummy framebuffer");
  16482. }
  16483. this._dummyFramebuffer = dummy;
  16484. }
  16485. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16486. if (faceIndex > -1) {
  16487. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16488. }
  16489. else {
  16490. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16491. }
  16492. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16493. var buffer;
  16494. switch (readType) {
  16495. case gl.UNSIGNED_BYTE:
  16496. buffer = new Uint8Array(4 * width * height);
  16497. readType = gl.UNSIGNED_BYTE;
  16498. break;
  16499. default:
  16500. buffer = new Float32Array(4 * width * height);
  16501. readType = gl.FLOAT;
  16502. break;
  16503. }
  16504. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16505. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16506. return buffer;
  16507. };
  16508. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16509. if (this._webGLVersion > 1) {
  16510. return this._caps.colorBufferFloat;
  16511. }
  16512. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16513. };
  16514. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16515. if (this._webGLVersion > 1) {
  16516. return this._caps.colorBufferFloat;
  16517. }
  16518. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16519. };
  16520. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16521. Engine.prototype._canRenderToFramebuffer = function (type) {
  16522. var gl = this._gl;
  16523. //clear existing errors
  16524. while (gl.getError() !== gl.NO_ERROR) { }
  16525. var successful = true;
  16526. var texture = gl.createTexture();
  16527. gl.bindTexture(gl.TEXTURE_2D, texture);
  16528. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16531. var fb = gl.createFramebuffer();
  16532. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16533. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16534. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16535. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16536. successful = successful && (gl.getError() === gl.NO_ERROR);
  16537. //try render by clearing frame buffer's color buffer
  16538. if (successful) {
  16539. gl.clear(gl.COLOR_BUFFER_BIT);
  16540. successful = successful && (gl.getError() === gl.NO_ERROR);
  16541. }
  16542. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16543. if (successful) {
  16544. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16545. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16546. var readFormat = gl.RGBA;
  16547. var readType = gl.UNSIGNED_BYTE;
  16548. var buffer = new Uint8Array(4);
  16549. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16550. successful = successful && (gl.getError() === gl.NO_ERROR);
  16551. }
  16552. //clean up
  16553. gl.deleteTexture(texture);
  16554. gl.deleteFramebuffer(fb);
  16555. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16556. //clear accumulated errors
  16557. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16558. return successful;
  16559. };
  16560. /** @ignore */
  16561. Engine.prototype._getWebGLTextureType = function (type) {
  16562. if (type === Engine.TEXTURETYPE_FLOAT) {
  16563. return this._gl.FLOAT;
  16564. }
  16565. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16566. // Add Half Float Constant.
  16567. return this._gl.HALF_FLOAT_OES;
  16568. }
  16569. return this._gl.UNSIGNED_BYTE;
  16570. };
  16571. ;
  16572. Engine.prototype._getInternalFormat = function (format) {
  16573. var internalFormat = this._gl.RGBA;
  16574. switch (format) {
  16575. case Engine.TEXTUREFORMAT_ALPHA:
  16576. internalFormat = this._gl.ALPHA;
  16577. break;
  16578. case Engine.TEXTUREFORMAT_LUMINANCE:
  16579. internalFormat = this._gl.LUMINANCE;
  16580. break;
  16581. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16582. internalFormat = this._gl.LUMINANCE_ALPHA;
  16583. break;
  16584. case Engine.TEXTUREFORMAT_RGB:
  16585. case Engine.TEXTUREFORMAT_RGB32F:
  16586. internalFormat = this._gl.RGB;
  16587. break;
  16588. case Engine.TEXTUREFORMAT_RGBA:
  16589. case Engine.TEXTUREFORMAT_RGBA32F:
  16590. internalFormat = this._gl.RGBA;
  16591. break;
  16592. case Engine.TEXTUREFORMAT_R32F:
  16593. internalFormat = this._gl.RED;
  16594. break;
  16595. case Engine.TEXTUREFORMAT_RG32F:
  16596. internalFormat = this._gl.RG;
  16597. break;
  16598. }
  16599. return internalFormat;
  16600. };
  16601. /** @ignore */
  16602. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16603. if (this._webGLVersion === 1) {
  16604. if (format) {
  16605. switch (format) {
  16606. case Engine.TEXTUREFORMAT_LUMINANCE:
  16607. return this._gl.LUMINANCE;
  16608. }
  16609. }
  16610. return this._gl.RGBA;
  16611. }
  16612. if (type === Engine.TEXTURETYPE_FLOAT) {
  16613. if (format) {
  16614. switch (format) {
  16615. case Engine.TEXTUREFORMAT_R32F:
  16616. return this._gl.R32F;
  16617. case Engine.TEXTUREFORMAT_RG32F:
  16618. return this._gl.RG32F;
  16619. case Engine.TEXTUREFORMAT_RGB32F:
  16620. return this._gl.RGB32F;
  16621. }
  16622. }
  16623. return this._gl.RGBA32F;
  16624. }
  16625. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16626. return this._gl.RGBA16F;
  16627. }
  16628. if (format) {
  16629. switch (format) {
  16630. case Engine.TEXTUREFORMAT_LUMINANCE:
  16631. return this._gl.LUMINANCE;
  16632. }
  16633. }
  16634. return this._gl.RGBA;
  16635. };
  16636. ;
  16637. /** @ignore */
  16638. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16639. if (type === Engine.TEXTURETYPE_FLOAT) {
  16640. return this._gl.RGBA32F;
  16641. }
  16642. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16643. return this._gl.RGBA16F;
  16644. }
  16645. return this._gl.RGBA8;
  16646. };
  16647. ;
  16648. /**
  16649. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16650. * @return the new query
  16651. */
  16652. Engine.prototype.createQuery = function () {
  16653. return this._gl.createQuery();
  16654. };
  16655. /**
  16656. * Delete and release a webGL query
  16657. * @param query defines the query to delete
  16658. * @return the current engine
  16659. */
  16660. Engine.prototype.deleteQuery = function (query) {
  16661. this._gl.deleteQuery(query);
  16662. return this;
  16663. };
  16664. /**
  16665. * Check if a given query has resolved and got its value
  16666. * @param query defines the query to check
  16667. * @returns true if the query got its value
  16668. */
  16669. Engine.prototype.isQueryResultAvailable = function (query) {
  16670. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16671. };
  16672. /**
  16673. * Gets the value of a given query
  16674. * @param query defines the query to check
  16675. * @returns the value of the query
  16676. */
  16677. Engine.prototype.getQueryResult = function (query) {
  16678. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16679. };
  16680. /**
  16681. * Initiates an occlusion query
  16682. * @param algorithmType defines the algorithm to use
  16683. * @param query defines the query to use
  16684. * @returns the current engine
  16685. * @see http://doc.babylonjs.com/features/occlusionquery
  16686. */
  16687. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16688. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16689. this._gl.beginQuery(glAlgorithm, query);
  16690. return this;
  16691. };
  16692. /**
  16693. * Ends an occlusion query
  16694. * @see http://doc.babylonjs.com/features/occlusionquery
  16695. * @param algorithmType defines the algorithm to use
  16696. * @returns the current engine
  16697. */
  16698. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16699. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16700. this._gl.endQuery(glAlgorithm);
  16701. return this;
  16702. };
  16703. /* Time queries */
  16704. Engine.prototype._createTimeQuery = function () {
  16705. var timerQuery = this._caps.timerQuery;
  16706. if (timerQuery.createQueryEXT) {
  16707. return timerQuery.createQueryEXT();
  16708. }
  16709. return this.createQuery();
  16710. };
  16711. Engine.prototype._deleteTimeQuery = function (query) {
  16712. var timerQuery = this._caps.timerQuery;
  16713. if (timerQuery.deleteQueryEXT) {
  16714. timerQuery.deleteQueryEXT(query);
  16715. return;
  16716. }
  16717. this.deleteQuery(query);
  16718. };
  16719. Engine.prototype._getTimeQueryResult = function (query) {
  16720. var timerQuery = this._caps.timerQuery;
  16721. if (timerQuery.getQueryObjectEXT) {
  16722. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16723. }
  16724. return this.getQueryResult(query);
  16725. };
  16726. Engine.prototype._getTimeQueryAvailability = function (query) {
  16727. var timerQuery = this._caps.timerQuery;
  16728. if (timerQuery.getQueryObjectEXT) {
  16729. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16730. }
  16731. return this.isQueryResultAvailable(query);
  16732. };
  16733. /**
  16734. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16735. * Please note that only one query can be issued at a time
  16736. * @returns a time token used to track the time span
  16737. */
  16738. Engine.prototype.startTimeQuery = function () {
  16739. var timerQuery = this._caps.timerQuery;
  16740. if (!timerQuery) {
  16741. return null;
  16742. }
  16743. var token = new BABYLON._TimeToken();
  16744. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16745. if (this._caps.canUseTimestampForTimerQuery) {
  16746. token._startTimeQuery = this._createTimeQuery();
  16747. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16748. }
  16749. else {
  16750. if (this._currentNonTimestampToken) {
  16751. return this._currentNonTimestampToken;
  16752. }
  16753. token._timeElapsedQuery = this._createTimeQuery();
  16754. if (timerQuery.beginQueryEXT) {
  16755. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16756. }
  16757. else {
  16758. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16759. }
  16760. this._currentNonTimestampToken = token;
  16761. }
  16762. return token;
  16763. };
  16764. /**
  16765. * Ends a time query
  16766. * @param token defines the token used to measure the time span
  16767. * @returns the time spent (in ns)
  16768. */
  16769. Engine.prototype.endTimeQuery = function (token) {
  16770. var timerQuery = this._caps.timerQuery;
  16771. if (!timerQuery || !token) {
  16772. return -1;
  16773. }
  16774. if (this._caps.canUseTimestampForTimerQuery) {
  16775. if (!token._startTimeQuery) {
  16776. return -1;
  16777. }
  16778. if (!token._endTimeQuery) {
  16779. token._endTimeQuery = this._createTimeQuery();
  16780. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  16781. }
  16782. }
  16783. else if (!token._timeElapsedQueryEnded) {
  16784. if (!token._timeElapsedQuery) {
  16785. return -1;
  16786. }
  16787. if (timerQuery.endQueryEXT) {
  16788. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  16789. }
  16790. else {
  16791. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  16792. }
  16793. token._timeElapsedQueryEnded = true;
  16794. }
  16795. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16796. var available = false;
  16797. if (token._endTimeQuery) {
  16798. available = this._getTimeQueryAvailability(token._endTimeQuery);
  16799. }
  16800. else if (token._timeElapsedQuery) {
  16801. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  16802. }
  16803. if (available && !disjoint) {
  16804. var result = 0;
  16805. if (this._caps.canUseTimestampForTimerQuery) {
  16806. if (!token._startTimeQuery || !token._endTimeQuery) {
  16807. return -1;
  16808. }
  16809. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  16810. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  16811. result = timeEnd - timeStart;
  16812. this._deleteTimeQuery(token._startTimeQuery);
  16813. this._deleteTimeQuery(token._endTimeQuery);
  16814. token._startTimeQuery = null;
  16815. token._endTimeQuery = null;
  16816. }
  16817. else {
  16818. if (!token._timeElapsedQuery) {
  16819. return -1;
  16820. }
  16821. result = this._getTimeQueryResult(token._timeElapsedQuery);
  16822. this._deleteTimeQuery(token._timeElapsedQuery);
  16823. token._timeElapsedQuery = null;
  16824. token._timeElapsedQueryEnded = false;
  16825. this._currentNonTimestampToken = null;
  16826. }
  16827. return result;
  16828. }
  16829. return -1;
  16830. };
  16831. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  16832. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  16833. };
  16834. // Transform feedback
  16835. /**
  16836. * Creates a webGL transform feedback object
  16837. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16838. * @returns the webGL transform feedback object
  16839. */
  16840. Engine.prototype.createTransformFeedback = function () {
  16841. return this._gl.createTransformFeedback();
  16842. };
  16843. /**
  16844. * Delete a webGL transform feedback object
  16845. * @param value defines the webGL transform feedback object to delete
  16846. */
  16847. Engine.prototype.deleteTransformFeedback = function (value) {
  16848. this._gl.deleteTransformFeedback(value);
  16849. };
  16850. /**
  16851. * Bind a webGL transform feedback object to the webgl context
  16852. * @param value defines the webGL transform feedback object to bind
  16853. */
  16854. Engine.prototype.bindTransformFeedback = function (value) {
  16855. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  16856. };
  16857. /**
  16858. * Begins a transform feedback operation
  16859. * @param usePoints defines if points or triangles must be used
  16860. */
  16861. Engine.prototype.beginTransformFeedback = function (usePoints) {
  16862. if (usePoints === void 0) { usePoints = true; }
  16863. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  16864. };
  16865. /**
  16866. * Ends a transform feedback operation
  16867. */
  16868. Engine.prototype.endTransformFeedback = function () {
  16869. this._gl.endTransformFeedback();
  16870. };
  16871. /**
  16872. * Specify the varyings to use with transform feedback
  16873. * @param program defines the associated webGL program
  16874. * @param value defines the list of strings representing the varying names
  16875. */
  16876. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  16877. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  16878. };
  16879. /**
  16880. * Bind a webGL buffer for a transform feedback operation
  16881. * @param value defines the webGL buffer to bind
  16882. */
  16883. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  16884. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  16885. };
  16886. /** @ignore */
  16887. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16888. var _this = this;
  16889. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16890. this._activeRequests.push(request);
  16891. request.onCompleteObservable.add(function (request) {
  16892. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16893. });
  16894. return request;
  16895. };
  16896. /** @ignore */
  16897. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  16898. var _this = this;
  16899. return new Promise(function (resolve, reject) {
  16900. _this._loadFile(url, function (data) {
  16901. resolve(data);
  16902. }, undefined, database, useArrayBuffer, function (request, exception) {
  16903. reject(exception);
  16904. });
  16905. });
  16906. };
  16907. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  16908. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  16909. var onload = function (data) {
  16910. loadedFiles[index] = data;
  16911. loadedFiles._internalCount++;
  16912. if (loadedFiles._internalCount === 6) {
  16913. onfinish(loadedFiles);
  16914. }
  16915. };
  16916. var onerror = function (request, exception) {
  16917. if (onErrorCallBack && request) {
  16918. onErrorCallBack(request.status + " " + request.statusText, exception);
  16919. }
  16920. };
  16921. this._loadFile(url, onload, undefined, undefined, true, onerror);
  16922. };
  16923. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  16924. if (onError === void 0) { onError = null; }
  16925. var loadedFiles = [];
  16926. loadedFiles._internalCount = 0;
  16927. for (var index = 0; index < 6; index++) {
  16928. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  16929. }
  16930. };
  16931. // Statics
  16932. /**
  16933. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  16934. * @returns true if the engine can be created
  16935. * @ignoreNaming
  16936. */
  16937. Engine.isSupported = function () {
  16938. try {
  16939. var tempcanvas = document.createElement("canvas");
  16940. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  16941. return gl != null && !!window.WebGLRenderingContext;
  16942. }
  16943. catch (e) {
  16944. return false;
  16945. }
  16946. };
  16947. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  16948. Engine.ExceptionList = [
  16949. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  16950. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16951. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  16952. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16953. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  16954. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  16955. ];
  16956. /** Gets the list of created engines */
  16957. Engine.Instances = new Array();
  16958. // Const statics
  16959. Engine._ALPHA_DISABLE = 0;
  16960. Engine._ALPHA_ADD = 1;
  16961. Engine._ALPHA_COMBINE = 2;
  16962. Engine._ALPHA_SUBTRACT = 3;
  16963. Engine._ALPHA_MULTIPLY = 4;
  16964. Engine._ALPHA_MAXIMIZED = 5;
  16965. Engine._ALPHA_ONEONE = 6;
  16966. Engine._ALPHA_PREMULTIPLIED = 7;
  16967. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  16968. Engine._ALPHA_INTERPOLATE = 9;
  16969. Engine._ALPHA_SCREENMODE = 10;
  16970. Engine._DELAYLOADSTATE_NONE = 0;
  16971. Engine._DELAYLOADSTATE_LOADED = 1;
  16972. Engine._DELAYLOADSTATE_LOADING = 2;
  16973. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  16974. Engine._TEXTUREFORMAT_ALPHA = 0;
  16975. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  16976. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  16977. Engine._TEXTUREFORMAT_RGB = 4;
  16978. Engine._TEXTUREFORMAT_RGBA = 5;
  16979. Engine._TEXTUREFORMAT_R32F = 6;
  16980. Engine._TEXTUREFORMAT_RG32F = 7;
  16981. Engine._TEXTUREFORMAT_RGB32F = 8;
  16982. Engine._TEXTUREFORMAT_RGBA32F = 9;
  16983. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  16984. Engine._TEXTURETYPE_FLOAT = 1;
  16985. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  16986. // Depht or Stencil test Constants.
  16987. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  16988. 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.
  16989. 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.
  16990. 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.
  16991. 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.
  16992. 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.
  16993. 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.
  16994. 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.
  16995. // Stencil Actions Constants.
  16996. Engine._KEEP = 0x1E00;
  16997. Engine._REPLACE = 0x1E01;
  16998. Engine._INCR = 0x1E02;
  16999. Engine._DECR = 0x1E03;
  17000. Engine._INVERT = 0x150A;
  17001. Engine._INCR_WRAP = 0x8507;
  17002. Engine._DECR_WRAP = 0x8508;
  17003. // Texture rescaling mode
  17004. Engine._SCALEMODE_FLOOR = 1;
  17005. Engine._SCALEMODE_NEAREST = 2;
  17006. Engine._SCALEMODE_CEILING = 3;
  17007. // Updatable statics so stick with vars here
  17008. /**
  17009. * Gets or sets the epsilon value used by collision engine
  17010. */
  17011. Engine.CollisionsEpsilon = 0.001;
  17012. /**
  17013. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17014. */
  17015. Engine.CodeRepository = "src/";
  17016. /**
  17017. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17018. */
  17019. Engine.ShadersRepository = "src/Shaders/";
  17020. return Engine;
  17021. }());
  17022. BABYLON.Engine = Engine;
  17023. })(BABYLON || (BABYLON = {}));
  17024. //# sourceMappingURL=babylon.engine.js.map
  17025. "use strict";
  17026. var BABYLON;
  17027. (function (BABYLON) {
  17028. /**
  17029. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17030. */
  17031. var Node = /** @class */ (function () {
  17032. /**
  17033. * Creates a new Node
  17034. * @param {string} name - the name and id to be given to this node
  17035. * @param {BABYLON.Scene} the scene this node will be added to
  17036. */
  17037. function Node(name, scene) {
  17038. if (scene === void 0) { scene = null; }
  17039. /**
  17040. * Gets or sets a string used to store user defined state for the node
  17041. */
  17042. this.state = "";
  17043. /**
  17044. * Gets or sets an object used to store user defined information for the node
  17045. */
  17046. this.metadata = null;
  17047. /**
  17048. * Gets or sets a boolean used to define if the node must be serialized
  17049. */
  17050. this.doNotSerialize = false;
  17051. /** @ignore */
  17052. this._isDisposed = false;
  17053. /**
  17054. * Gets a list of Animations associated with the node
  17055. */
  17056. this.animations = new Array();
  17057. this._ranges = {};
  17058. this._isEnabled = true;
  17059. this._isReady = true;
  17060. /** @ignore */
  17061. this._currentRenderId = -1;
  17062. this._parentRenderId = -1;
  17063. this._childRenderId = -1;
  17064. this._animationPropertiesOverride = null;
  17065. /**
  17066. * An event triggered when the mesh is disposed
  17067. */
  17068. this.onDisposeObservable = new BABYLON.Observable();
  17069. // Behaviors
  17070. this._behaviors = new Array();
  17071. this.name = name;
  17072. this.id = name;
  17073. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17074. this.uniqueId = this._scene.getUniqueId();
  17075. this._initCache();
  17076. }
  17077. /**
  17078. * Gets a boolean indicating if the node has been disposed
  17079. * @returns true if the node was disposed
  17080. */
  17081. Node.prototype.isDisposed = function () {
  17082. return this._isDisposed;
  17083. };
  17084. Object.defineProperty(Node.prototype, "parent", {
  17085. get: function () {
  17086. return this._parentNode;
  17087. },
  17088. /**
  17089. * Gets or sets the parent of the node
  17090. */
  17091. set: function (parent) {
  17092. if (this._parentNode === parent) {
  17093. return;
  17094. }
  17095. // Remove self from list of children of parent
  17096. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17097. var index = this._parentNode._children.indexOf(this);
  17098. if (index !== -1) {
  17099. this._parentNode._children.splice(index, 1);
  17100. }
  17101. }
  17102. // Store new parent
  17103. this._parentNode = parent;
  17104. // Add as child to new parent
  17105. if (this._parentNode) {
  17106. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17107. this._parentNode._children = new Array();
  17108. }
  17109. this._parentNode._children.push(this);
  17110. }
  17111. },
  17112. enumerable: true,
  17113. configurable: true
  17114. });
  17115. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17116. /**
  17117. * Gets or sets the animation properties override
  17118. */
  17119. get: function () {
  17120. return this._animationPropertiesOverride;
  17121. },
  17122. set: function (value) {
  17123. this._animationPropertiesOverride = value;
  17124. },
  17125. enumerable: true,
  17126. configurable: true
  17127. });
  17128. /**
  17129. * Gets a string idenfifying the name of the class
  17130. * @returns "Node" string
  17131. */
  17132. Node.prototype.getClassName = function () {
  17133. return "Node";
  17134. };
  17135. Object.defineProperty(Node.prototype, "onDispose", {
  17136. /**
  17137. * Sets a callback that will be raised when the node will be disposed
  17138. */
  17139. set: function (callback) {
  17140. if (this._onDisposeObserver) {
  17141. this.onDisposeObservable.remove(this._onDisposeObserver);
  17142. }
  17143. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17144. },
  17145. enumerable: true,
  17146. configurable: true
  17147. });
  17148. /**
  17149. * Gets the scene of the node
  17150. * @returns a {BABYLON.Scene}
  17151. */
  17152. Node.prototype.getScene = function () {
  17153. return this._scene;
  17154. };
  17155. /**
  17156. * Gets the engine of the node
  17157. * @returns a {BABYLON.Engine}
  17158. */
  17159. Node.prototype.getEngine = function () {
  17160. return this._scene.getEngine();
  17161. };
  17162. /**
  17163. * Attach a behavior to the node
  17164. * @see http://doc.babylonjs.com/features/behaviour
  17165. * @param behavior defines the behavior to attach
  17166. * @returns the current Node
  17167. */
  17168. Node.prototype.addBehavior = function (behavior) {
  17169. var _this = this;
  17170. var index = this._behaviors.indexOf(behavior);
  17171. if (index !== -1) {
  17172. return this;
  17173. }
  17174. behavior.init();
  17175. if (this._scene.isLoading) {
  17176. // We defer the attach when the scene will be loaded
  17177. var observer = this._scene.onDataLoadedObservable.add(function () {
  17178. behavior.attach(_this);
  17179. setTimeout(function () {
  17180. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17181. _this._scene.onDataLoadedObservable.remove(observer);
  17182. }, 0);
  17183. });
  17184. }
  17185. else {
  17186. behavior.attach(this);
  17187. }
  17188. this._behaviors.push(behavior);
  17189. return this;
  17190. };
  17191. /**
  17192. * Remove an attached behavior
  17193. * @see http://doc.babylonjs.com/features/behaviour
  17194. * @param behavior defines the behavior to attach
  17195. * @returns the current Node
  17196. */
  17197. Node.prototype.removeBehavior = function (behavior) {
  17198. var index = this._behaviors.indexOf(behavior);
  17199. if (index === -1) {
  17200. return this;
  17201. }
  17202. this._behaviors[index].detach();
  17203. this._behaviors.splice(index, 1);
  17204. return this;
  17205. };
  17206. Object.defineProperty(Node.prototype, "behaviors", {
  17207. /**
  17208. * Gets the list of attached behaviors
  17209. * @see http://doc.babylonjs.com/features/behaviour
  17210. */
  17211. get: function () {
  17212. return this._behaviors;
  17213. },
  17214. enumerable: true,
  17215. configurable: true
  17216. });
  17217. /**
  17218. * Gets an attached behavior by name
  17219. * @param name defines the name of the behavior to look for
  17220. * @see http://doc.babylonjs.com/features/behaviour
  17221. * @returns null if behavior was not found else the requested behavior
  17222. */
  17223. Node.prototype.getBehaviorByName = function (name) {
  17224. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17225. var behavior = _a[_i];
  17226. if (behavior.name === name) {
  17227. return behavior;
  17228. }
  17229. }
  17230. return null;
  17231. };
  17232. /**
  17233. * Returns the world matrix of the node
  17234. * @returns a matrix containing the node's world matrix
  17235. */
  17236. Node.prototype.getWorldMatrix = function () {
  17237. return BABYLON.Matrix.Identity();
  17238. };
  17239. // override it in derived class if you add new variables to the cache
  17240. // and call the parent class method
  17241. /** @ignore */
  17242. Node.prototype._initCache = function () {
  17243. this._cache = {};
  17244. this._cache.parent = undefined;
  17245. };
  17246. /** @ignore */
  17247. Node.prototype.updateCache = function (force) {
  17248. if (!force && this.isSynchronized())
  17249. return;
  17250. this._cache.parent = this.parent;
  17251. this._updateCache();
  17252. };
  17253. // override it in derived class if you add new variables to the cache
  17254. // and call the parent class method if !ignoreParentClass
  17255. /** @ignore */
  17256. Node.prototype._updateCache = function (ignoreParentClass) {
  17257. };
  17258. // override it in derived class if you add new variables to the cache
  17259. /** @ignore */
  17260. Node.prototype._isSynchronized = function () {
  17261. return true;
  17262. };
  17263. /** @ignore */
  17264. Node.prototype._markSyncedWithParent = function () {
  17265. if (this.parent) {
  17266. this._parentRenderId = this.parent._childRenderId;
  17267. }
  17268. };
  17269. /** @ignore */
  17270. Node.prototype.isSynchronizedWithParent = function () {
  17271. if (!this.parent) {
  17272. return true;
  17273. }
  17274. if (this._parentRenderId !== this.parent._childRenderId) {
  17275. return false;
  17276. }
  17277. return this.parent.isSynchronized();
  17278. };
  17279. /** @ignore */
  17280. Node.prototype.isSynchronized = function (updateCache) {
  17281. var check = this.hasNewParent();
  17282. check = check || !this.isSynchronizedWithParent();
  17283. check = check || !this._isSynchronized();
  17284. if (updateCache)
  17285. this.updateCache(true);
  17286. return !check;
  17287. };
  17288. /** @ignore */
  17289. Node.prototype.hasNewParent = function (update) {
  17290. if (this._cache.parent === this.parent)
  17291. return false;
  17292. if (update)
  17293. this._cache.parent = this.parent;
  17294. return true;
  17295. };
  17296. /**
  17297. * Is this node ready to be used/rendered
  17298. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17299. * @return true if the node is ready
  17300. */
  17301. Node.prototype.isReady = function (completeCheck) {
  17302. if (completeCheck === void 0) { completeCheck = false; }
  17303. return this._isReady;
  17304. };
  17305. /**
  17306. * Is this node enabled?
  17307. * 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
  17308. * @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
  17309. * @return whether this node (and its parent) is enabled
  17310. */
  17311. Node.prototype.isEnabled = function (checkAncestors) {
  17312. if (checkAncestors === void 0) { checkAncestors = true; }
  17313. if (checkAncestors === false) {
  17314. return this._isEnabled;
  17315. }
  17316. if (this._isEnabled === false) {
  17317. return false;
  17318. }
  17319. if (this.parent !== undefined && this.parent !== null) {
  17320. return this.parent.isEnabled(checkAncestors);
  17321. }
  17322. return true;
  17323. };
  17324. /**
  17325. * Set the enabled state of this node
  17326. * @param value defines the new enabled state
  17327. */
  17328. Node.prototype.setEnabled = function (value) {
  17329. this._isEnabled = value;
  17330. };
  17331. /**
  17332. * Is this node a descendant of the given node?
  17333. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17334. * @param ancestor defines the parent node to inspect
  17335. * @returns a boolean indicating if this node is a descendant of the given node
  17336. */
  17337. Node.prototype.isDescendantOf = function (ancestor) {
  17338. if (this.parent) {
  17339. if (this.parent === ancestor) {
  17340. return true;
  17341. }
  17342. return this.parent.isDescendantOf(ancestor);
  17343. }
  17344. return false;
  17345. };
  17346. /** @ignore */
  17347. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17348. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17349. if (!this._children) {
  17350. return;
  17351. }
  17352. for (var index = 0; index < this._children.length; index++) {
  17353. var item = this._children[index];
  17354. if (!predicate || predicate(item)) {
  17355. results.push(item);
  17356. }
  17357. if (!directDescendantsOnly) {
  17358. item._getDescendants(results, false, predicate);
  17359. }
  17360. }
  17361. };
  17362. /**
  17363. * Will return all nodes that have this node as ascendant
  17364. * @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
  17365. * @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
  17366. * @return all children nodes of all types
  17367. */
  17368. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17369. var results = new Array();
  17370. this._getDescendants(results, directDescendantsOnly, predicate);
  17371. return results;
  17372. };
  17373. /**
  17374. * Get all child-meshes of this node
  17375. * @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
  17376. * @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
  17377. * @returns an array of {BABYLON.AbstractMesh}
  17378. */
  17379. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17380. var results = [];
  17381. this._getDescendants(results, directDescendantsOnly, function (node) {
  17382. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17383. });
  17384. return results;
  17385. };
  17386. /**
  17387. * Get all child-transformNodes of this node
  17388. * @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
  17389. * @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
  17390. * @returns an array of {BABYLON.TransformNode}
  17391. */
  17392. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17393. var results = [];
  17394. this._getDescendants(results, directDescendantsOnly, function (node) {
  17395. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17396. });
  17397. return results;
  17398. };
  17399. /**
  17400. * Get all direct children of this node
  17401. * @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
  17402. * @returns an array of {BABYLON.Node}
  17403. */
  17404. Node.prototype.getChildren = function (predicate) {
  17405. return this.getDescendants(true, predicate);
  17406. };
  17407. /** @ignore */
  17408. Node.prototype._setReady = function (state) {
  17409. if (state === this._isReady) {
  17410. return;
  17411. }
  17412. if (!state) {
  17413. this._isReady = false;
  17414. return;
  17415. }
  17416. if (this.onReady) {
  17417. this.onReady(this);
  17418. }
  17419. this._isReady = true;
  17420. };
  17421. /**
  17422. * Get an animation by name
  17423. * @param name defines the name of the animation to look for
  17424. * @returns null if not found else the requested animation
  17425. */
  17426. Node.prototype.getAnimationByName = function (name) {
  17427. for (var i = 0; i < this.animations.length; i++) {
  17428. var animation = this.animations[i];
  17429. if (animation.name === name) {
  17430. return animation;
  17431. }
  17432. }
  17433. return null;
  17434. };
  17435. /**
  17436. * Creates an animation range for this node
  17437. * @param name defines the name of the range
  17438. * @param from defines the starting key
  17439. * @param to defines the end key
  17440. */
  17441. Node.prototype.createAnimationRange = function (name, from, to) {
  17442. // check name not already in use
  17443. if (!this._ranges[name]) {
  17444. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17445. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17446. if (this.animations[i]) {
  17447. this.animations[i].createRange(name, from, to);
  17448. }
  17449. }
  17450. }
  17451. };
  17452. /**
  17453. * Delete a specific animation range
  17454. * @param name defines the name of the range to delete
  17455. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17456. */
  17457. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17458. if (deleteFrames === void 0) { deleteFrames = true; }
  17459. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17460. if (this.animations[i]) {
  17461. this.animations[i].deleteRange(name, deleteFrames);
  17462. }
  17463. }
  17464. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17465. };
  17466. /**
  17467. * Get an animation range by name
  17468. * @param name defines the name of the animation range to look for
  17469. * @returns null if not found else the requested animation range
  17470. */
  17471. Node.prototype.getAnimationRange = function (name) {
  17472. return this._ranges[name];
  17473. };
  17474. /**
  17475. * Will start the animation sequence
  17476. * @param name defines the range frames for animation sequence
  17477. * @param loop defines if the animation should loop (false by default)
  17478. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17479. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17480. * @returns the object created for this animation. If range does not exist, it will return null
  17481. */
  17482. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17483. var range = this.getAnimationRange(name);
  17484. if (!range) {
  17485. return null;
  17486. }
  17487. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17488. };
  17489. /**
  17490. * Serialize animation ranges into a JSON compatible object
  17491. * @returns serialization object
  17492. */
  17493. Node.prototype.serializeAnimationRanges = function () {
  17494. var serializationRanges = [];
  17495. for (var name in this._ranges) {
  17496. var localRange = this._ranges[name];
  17497. if (!localRange) {
  17498. continue;
  17499. }
  17500. var range = {};
  17501. range.name = name;
  17502. range.from = localRange.from;
  17503. range.to = localRange.to;
  17504. serializationRanges.push(range);
  17505. }
  17506. return serializationRanges;
  17507. };
  17508. /**
  17509. * Computes the world matrix of the node
  17510. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17511. * @returns the world matrix
  17512. */
  17513. Node.prototype.computeWorldMatrix = function (force) {
  17514. return BABYLON.Matrix.Identity();
  17515. };
  17516. /**
  17517. * Releases resources associated with this node.
  17518. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17519. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17520. */
  17521. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17522. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17523. if (!doNotRecurse) {
  17524. var nodes = this.getDescendants(true);
  17525. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17526. var node = nodes_1[_i];
  17527. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17528. }
  17529. }
  17530. else {
  17531. var transformNodes = this.getChildTransformNodes(true);
  17532. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17533. var transformNode = transformNodes_1[_a];
  17534. transformNode.parent = null;
  17535. transformNode.computeWorldMatrix(true);
  17536. }
  17537. }
  17538. this.parent = null;
  17539. // Callback
  17540. this.onDisposeObservable.notifyObservers(this);
  17541. this.onDisposeObservable.clear();
  17542. // Behaviors
  17543. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17544. var behavior = _c[_b];
  17545. behavior.detach();
  17546. }
  17547. this._behaviors = [];
  17548. this._isDisposed = true;
  17549. };
  17550. /**
  17551. * Parse animation range data from a serialization object and store them into a given node
  17552. * @param node defines where to store the animation ranges
  17553. * @param parsedNode defines the serialization object to read data from
  17554. * @param scene defines the hosting scene
  17555. */
  17556. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17557. if (parsedNode.ranges) {
  17558. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17559. var data = parsedNode.ranges[index];
  17560. node.createAnimationRange(data.name, data.from, data.to);
  17561. }
  17562. }
  17563. };
  17564. __decorate([
  17565. BABYLON.serialize()
  17566. ], Node.prototype, "name", void 0);
  17567. __decorate([
  17568. BABYLON.serialize()
  17569. ], Node.prototype, "id", void 0);
  17570. __decorate([
  17571. BABYLON.serialize()
  17572. ], Node.prototype, "uniqueId", void 0);
  17573. __decorate([
  17574. BABYLON.serialize()
  17575. ], Node.prototype, "state", void 0);
  17576. __decorate([
  17577. BABYLON.serialize()
  17578. ], Node.prototype, "metadata", void 0);
  17579. return Node;
  17580. }());
  17581. BABYLON.Node = Node;
  17582. })(BABYLON || (BABYLON = {}));
  17583. //# sourceMappingURL=babylon.node.js.map
  17584. "use strict";
  17585. var BABYLON;
  17586. (function (BABYLON) {
  17587. var BoundingSphere = /** @class */ (function () {
  17588. function BoundingSphere(minimum, maximum) {
  17589. this.minimum = minimum;
  17590. this.maximum = maximum;
  17591. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17592. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  17593. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  17594. this.radius = distance * 0.5;
  17595. this.centerWorld = BABYLON.Vector3.Zero();
  17596. this._update(BABYLON.Matrix.Identity());
  17597. }
  17598. // Methods
  17599. BoundingSphere.prototype._update = function (world) {
  17600. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17601. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17602. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17603. };
  17604. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17605. for (var i = 0; i < 6; i++) {
  17606. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17607. return false;
  17608. }
  17609. return true;
  17610. };
  17611. BoundingSphere.prototype.intersectsPoint = function (point) {
  17612. var x = this.centerWorld.x - point.x;
  17613. var y = this.centerWorld.y - point.y;
  17614. var z = this.centerWorld.z - point.z;
  17615. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17616. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17617. return false;
  17618. return true;
  17619. };
  17620. // Statics
  17621. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17622. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17623. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17624. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17625. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17626. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17627. return false;
  17628. return true;
  17629. };
  17630. return BoundingSphere;
  17631. }());
  17632. BABYLON.BoundingSphere = BoundingSphere;
  17633. })(BABYLON || (BABYLON = {}));
  17634. //# sourceMappingURL=babylon.boundingSphere.js.map
  17635. "use strict";
  17636. var BABYLON;
  17637. (function (BABYLON) {
  17638. var BoundingBox = /** @class */ (function () {
  17639. function BoundingBox(minimum, maximum) {
  17640. this.minimum = minimum;
  17641. this.maximum = maximum;
  17642. this.vectors = new Array();
  17643. this.vectorsWorld = new Array();
  17644. // Bounding vectors
  17645. this.vectors.push(this.minimum.clone());
  17646. this.vectors.push(this.maximum.clone());
  17647. this.vectors.push(this.minimum.clone());
  17648. this.vectors[2].x = this.maximum.x;
  17649. this.vectors.push(this.minimum.clone());
  17650. this.vectors[3].y = this.maximum.y;
  17651. this.vectors.push(this.minimum.clone());
  17652. this.vectors[4].z = this.maximum.z;
  17653. this.vectors.push(this.maximum.clone());
  17654. this.vectors[5].z = this.minimum.z;
  17655. this.vectors.push(this.maximum.clone());
  17656. this.vectors[6].x = this.minimum.x;
  17657. this.vectors.push(this.maximum.clone());
  17658. this.vectors[7].y = this.minimum.y;
  17659. // OBB
  17660. this.center = this.maximum.add(this.minimum).scale(0.5);
  17661. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17662. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17663. // World
  17664. for (var index = 0; index < this.vectors.length; index++) {
  17665. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17666. }
  17667. this.minimumWorld = BABYLON.Vector3.Zero();
  17668. this.maximumWorld = BABYLON.Vector3.Zero();
  17669. this.centerWorld = BABYLON.Vector3.Zero();
  17670. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17671. this._update(BABYLON.Matrix.Identity());
  17672. }
  17673. // Methods
  17674. BoundingBox.prototype.getWorldMatrix = function () {
  17675. return this._worldMatrix;
  17676. };
  17677. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17678. this._worldMatrix.copyFrom(matrix);
  17679. return this;
  17680. };
  17681. BoundingBox.prototype._update = function (world) {
  17682. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17683. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17684. for (var index = 0; index < this.vectors.length; index++) {
  17685. var v = this.vectorsWorld[index];
  17686. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17687. if (v.x < this.minimumWorld.x)
  17688. this.minimumWorld.x = v.x;
  17689. if (v.y < this.minimumWorld.y)
  17690. this.minimumWorld.y = v.y;
  17691. if (v.z < this.minimumWorld.z)
  17692. this.minimumWorld.z = v.z;
  17693. if (v.x > this.maximumWorld.x)
  17694. this.maximumWorld.x = v.x;
  17695. if (v.y > this.maximumWorld.y)
  17696. this.maximumWorld.y = v.y;
  17697. if (v.z > this.maximumWorld.z)
  17698. this.maximumWorld.z = v.z;
  17699. }
  17700. // Extend
  17701. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17702. this.extendSizeWorld.scaleInPlace(0.5);
  17703. // OBB
  17704. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17705. this.centerWorld.scaleInPlace(0.5);
  17706. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17707. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17708. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17709. this._worldMatrix = world;
  17710. };
  17711. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17712. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17713. };
  17714. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17715. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17716. };
  17717. BoundingBox.prototype.intersectsPoint = function (point) {
  17718. var delta = -BABYLON.Epsilon;
  17719. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17720. return false;
  17721. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17722. return false;
  17723. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17724. return false;
  17725. return true;
  17726. };
  17727. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17728. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17729. };
  17730. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17731. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17732. return false;
  17733. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17734. return false;
  17735. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17736. return false;
  17737. return true;
  17738. };
  17739. // Statics
  17740. BoundingBox.Intersects = function (box0, box1) {
  17741. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17742. return false;
  17743. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17744. return false;
  17745. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17746. return false;
  17747. return true;
  17748. };
  17749. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17750. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17751. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17752. return (num <= (sphereRadius * sphereRadius));
  17753. };
  17754. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17755. for (var p = 0; p < 6; p++) {
  17756. for (var i = 0; i < 8; i++) {
  17757. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17758. return false;
  17759. }
  17760. }
  17761. }
  17762. return true;
  17763. };
  17764. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17765. for (var p = 0; p < 6; p++) {
  17766. var inCount = 8;
  17767. for (var i = 0; i < 8; i++) {
  17768. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17769. --inCount;
  17770. }
  17771. else {
  17772. break;
  17773. }
  17774. }
  17775. if (inCount === 0)
  17776. return false;
  17777. }
  17778. return true;
  17779. };
  17780. return BoundingBox;
  17781. }());
  17782. BABYLON.BoundingBox = BoundingBox;
  17783. })(BABYLON || (BABYLON = {}));
  17784. //# sourceMappingURL=babylon.boundingBox.js.map
  17785. "use strict";
  17786. var BABYLON;
  17787. (function (BABYLON) {
  17788. var computeBoxExtents = function (axis, box) {
  17789. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  17790. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  17791. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  17792. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  17793. var r = r0 + r1 + r2;
  17794. return {
  17795. min: p - r,
  17796. max: p + r
  17797. };
  17798. };
  17799. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  17800. var axisOverlap = function (axis, box0, box1) {
  17801. var result0 = computeBoxExtents(axis, box0);
  17802. var result1 = computeBoxExtents(axis, box1);
  17803. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  17804. };
  17805. var BoundingInfo = /** @class */ (function () {
  17806. function BoundingInfo(minimum, maximum) {
  17807. this.minimum = minimum;
  17808. this.maximum = maximum;
  17809. this._isLocked = false;
  17810. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  17811. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  17812. }
  17813. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  17814. get: function () {
  17815. return this._isLocked;
  17816. },
  17817. set: function (value) {
  17818. this._isLocked = value;
  17819. },
  17820. enumerable: true,
  17821. configurable: true
  17822. });
  17823. // Methods
  17824. BoundingInfo.prototype.update = function (world) {
  17825. if (this._isLocked) {
  17826. return;
  17827. }
  17828. this.boundingBox._update(world);
  17829. this.boundingSphere._update(world);
  17830. };
  17831. /**
  17832. * Recreate the bounding info to be centered around a specific point given a specific extend.
  17833. * @param center New center of the bounding info
  17834. * @param extend New extend of the bounding info
  17835. */
  17836. BoundingInfo.prototype.centerOn = function (center, extend) {
  17837. this.minimum = center.subtract(extend);
  17838. this.maximum = center.add(extend);
  17839. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  17840. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  17841. return this;
  17842. };
  17843. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  17844. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  17845. return false;
  17846. return this.boundingBox.isInFrustum(frustumPlanes);
  17847. };
  17848. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  17849. /**
  17850. * Gets the world distance between the min and max points of the bounding box
  17851. */
  17852. get: function () {
  17853. var boundingBox = this.boundingBox;
  17854. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  17855. return size.length();
  17856. },
  17857. enumerable: true,
  17858. configurable: true
  17859. });
  17860. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17861. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  17862. };
  17863. BoundingInfo.prototype._checkCollision = function (collider) {
  17864. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  17865. };
  17866. BoundingInfo.prototype.intersectsPoint = function (point) {
  17867. if (!this.boundingSphere.centerWorld) {
  17868. return false;
  17869. }
  17870. if (!this.boundingSphere.intersectsPoint(point)) {
  17871. return false;
  17872. }
  17873. if (!this.boundingBox.intersectsPoint(point)) {
  17874. return false;
  17875. }
  17876. return true;
  17877. };
  17878. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  17879. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  17880. return false;
  17881. }
  17882. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  17883. return false;
  17884. }
  17885. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  17886. return false;
  17887. }
  17888. if (!precise) {
  17889. return true;
  17890. }
  17891. var box0 = this.boundingBox;
  17892. var box1 = boundingInfo.boundingBox;
  17893. if (!axisOverlap(box0.directions[0], box0, box1))
  17894. return false;
  17895. if (!axisOverlap(box0.directions[1], box0, box1))
  17896. return false;
  17897. if (!axisOverlap(box0.directions[2], box0, box1))
  17898. return false;
  17899. if (!axisOverlap(box1.directions[0], box0, box1))
  17900. return false;
  17901. if (!axisOverlap(box1.directions[1], box0, box1))
  17902. return false;
  17903. if (!axisOverlap(box1.directions[2], box0, box1))
  17904. return false;
  17905. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  17906. return false;
  17907. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  17908. return false;
  17909. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  17910. return false;
  17911. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  17912. return false;
  17913. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  17914. return false;
  17915. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  17916. return false;
  17917. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  17918. return false;
  17919. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  17920. return false;
  17921. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  17922. return false;
  17923. return true;
  17924. };
  17925. return BoundingInfo;
  17926. }());
  17927. BABYLON.BoundingInfo = BoundingInfo;
  17928. })(BABYLON || (BABYLON = {}));
  17929. //# sourceMappingURL=babylon.boundingInfo.js.map
  17930. "use strict";
  17931. var BABYLON;
  17932. (function (BABYLON) {
  17933. var TransformNode = /** @class */ (function (_super) {
  17934. __extends(TransformNode, _super);
  17935. function TransformNode(name, scene, isPure) {
  17936. if (scene === void 0) { scene = null; }
  17937. if (isPure === void 0) { isPure = true; }
  17938. var _this = _super.call(this, name, scene) || this;
  17939. _this._forward = new BABYLON.Vector3(0, 0, 1);
  17940. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  17941. _this._up = new BABYLON.Vector3(0, 1, 0);
  17942. _this._right = new BABYLON.Vector3(1, 0, 0);
  17943. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  17944. // Properties
  17945. _this._rotation = BABYLON.Vector3.Zero();
  17946. _this._scaling = BABYLON.Vector3.One();
  17947. _this._isDirty = false;
  17948. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  17949. _this.scalingDeterminant = 1;
  17950. _this.infiniteDistance = false;
  17951. _this.position = BABYLON.Vector3.Zero();
  17952. _this._localWorld = BABYLON.Matrix.Zero();
  17953. _this._worldMatrix = BABYLON.Matrix.Zero();
  17954. _this._worldMatrixDeterminant = 0;
  17955. _this._absolutePosition = BABYLON.Vector3.Zero();
  17956. _this._pivotMatrix = BABYLON.Matrix.Identity();
  17957. _this._postMultiplyPivotMatrix = false;
  17958. _this._isWorldMatrixFrozen = false;
  17959. /**
  17960. * An event triggered after the world matrix is updated
  17961. */
  17962. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  17963. _this._nonUniformScaling = false;
  17964. if (isPure) {
  17965. _this.getScene().addTransformNode(_this);
  17966. }
  17967. return _this;
  17968. }
  17969. /**
  17970. * Gets a string idenfifying the name of the class
  17971. * @returns "TransformNode" string
  17972. */
  17973. TransformNode.prototype.getClassName = function () {
  17974. return "TransformNode";
  17975. };
  17976. Object.defineProperty(TransformNode.prototype, "rotation", {
  17977. /**
  17978. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  17979. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  17980. * Default : (0.0, 0.0, 0.0)
  17981. */
  17982. get: function () {
  17983. return this._rotation;
  17984. },
  17985. set: function (newRotation) {
  17986. this._rotation = newRotation;
  17987. },
  17988. enumerable: true,
  17989. configurable: true
  17990. });
  17991. Object.defineProperty(TransformNode.prototype, "scaling", {
  17992. /**
  17993. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17994. * Default : (1.0, 1.0, 1.0)
  17995. */
  17996. get: function () {
  17997. return this._scaling;
  17998. },
  17999. /**
  18000. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18001. * Default : (1.0, 1.0, 1.0)
  18002. */
  18003. set: function (newScaling) {
  18004. this._scaling = newScaling;
  18005. },
  18006. enumerable: true,
  18007. configurable: true
  18008. });
  18009. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18010. /**
  18011. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18012. * It's null by default.
  18013. * 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)
  18014. */
  18015. get: function () {
  18016. return this._rotationQuaternion;
  18017. },
  18018. set: function (quaternion) {
  18019. this._rotationQuaternion = quaternion;
  18020. //reset the rotation vector.
  18021. if (quaternion && this.rotation.length()) {
  18022. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18023. }
  18024. },
  18025. enumerable: true,
  18026. configurable: true
  18027. });
  18028. Object.defineProperty(TransformNode.prototype, "forward", {
  18029. /**
  18030. * The forward direction of that transform in world space.
  18031. */
  18032. get: function () {
  18033. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18034. },
  18035. enumerable: true,
  18036. configurable: true
  18037. });
  18038. Object.defineProperty(TransformNode.prototype, "up", {
  18039. /**
  18040. * The up direction of that transform in world space.
  18041. */
  18042. get: function () {
  18043. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18044. },
  18045. enumerable: true,
  18046. configurable: true
  18047. });
  18048. Object.defineProperty(TransformNode.prototype, "right", {
  18049. /**
  18050. * The right direction of that transform in world space.
  18051. */
  18052. get: function () {
  18053. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18054. },
  18055. enumerable: true,
  18056. configurable: true
  18057. });
  18058. /**
  18059. * Returns the latest update of the World matrix
  18060. * Returns a Matrix.
  18061. */
  18062. TransformNode.prototype.getWorldMatrix = function () {
  18063. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18064. this.computeWorldMatrix();
  18065. }
  18066. return this._worldMatrix;
  18067. };
  18068. /**
  18069. * Returns the latest update of the World matrix determinant.
  18070. */
  18071. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18072. return this._worldMatrixDeterminant;
  18073. };
  18074. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18075. /**
  18076. * Returns directly the latest state of the mesh World matrix.
  18077. * A Matrix is returned.
  18078. */
  18079. get: function () {
  18080. return this._worldMatrix;
  18081. },
  18082. enumerable: true,
  18083. configurable: true
  18084. });
  18085. /**
  18086. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18087. * Returns the TransformNode.
  18088. */
  18089. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18090. this._poseMatrix.copyFrom(matrix);
  18091. return this;
  18092. };
  18093. /**
  18094. * Returns the mesh Pose matrix.
  18095. * Returned object : Matrix
  18096. */
  18097. TransformNode.prototype.getPoseMatrix = function () {
  18098. return this._poseMatrix;
  18099. };
  18100. TransformNode.prototype._isSynchronized = function () {
  18101. if (this._isDirty) {
  18102. return false;
  18103. }
  18104. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18105. return false;
  18106. if (this._cache.pivotMatrixUpdated) {
  18107. return false;
  18108. }
  18109. if (this.infiniteDistance) {
  18110. return false;
  18111. }
  18112. if (!this._cache.position.equals(this.position))
  18113. return false;
  18114. if (this.rotationQuaternion) {
  18115. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18116. return false;
  18117. }
  18118. if (!this._cache.rotation.equals(this.rotation))
  18119. return false;
  18120. if (!this._cache.scaling.equals(this.scaling))
  18121. return false;
  18122. return true;
  18123. };
  18124. TransformNode.prototype._initCache = function () {
  18125. _super.prototype._initCache.call(this);
  18126. this._cache.localMatrixUpdated = false;
  18127. this._cache.position = BABYLON.Vector3.Zero();
  18128. this._cache.scaling = BABYLON.Vector3.Zero();
  18129. this._cache.rotation = BABYLON.Vector3.Zero();
  18130. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18131. this._cache.billboardMode = -1;
  18132. };
  18133. TransformNode.prototype.markAsDirty = function (property) {
  18134. if (property === "rotation") {
  18135. this.rotationQuaternion = null;
  18136. }
  18137. this._currentRenderId = Number.MAX_VALUE;
  18138. this._isDirty = true;
  18139. return this;
  18140. };
  18141. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18142. /**
  18143. * Returns the current mesh absolute position.
  18144. * Retuns a Vector3.
  18145. */
  18146. get: function () {
  18147. return this._absolutePosition;
  18148. },
  18149. enumerable: true,
  18150. configurable: true
  18151. });
  18152. /**
  18153. * Sets a new matrix to apply before all other transformation
  18154. * @param matrix defines the transform matrix
  18155. * @returns the current TransformNode
  18156. */
  18157. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18158. return this.setPivotMatrix(matrix, false);
  18159. };
  18160. /**
  18161. * Sets a new pivot matrix to the current node
  18162. * @param matrix defines the new pivot matrix to use
  18163. * @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
  18164. * @returns the current TransformNode
  18165. */
  18166. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18167. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18168. this._pivotMatrix = matrix.clone();
  18169. this._cache.pivotMatrixUpdated = true;
  18170. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18171. if (this._postMultiplyPivotMatrix) {
  18172. if (!this._pivotMatrixInverse) {
  18173. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18174. }
  18175. else {
  18176. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18177. }
  18178. }
  18179. return this;
  18180. };
  18181. /**
  18182. * Returns the mesh pivot matrix.
  18183. * Default : Identity.
  18184. * A Matrix is returned.
  18185. */
  18186. TransformNode.prototype.getPivotMatrix = function () {
  18187. return this._pivotMatrix;
  18188. };
  18189. /**
  18190. * Prevents the World matrix to be computed any longer.
  18191. * Returns the TransformNode.
  18192. */
  18193. TransformNode.prototype.freezeWorldMatrix = function () {
  18194. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18195. this.computeWorldMatrix(true);
  18196. this._isWorldMatrixFrozen = true;
  18197. return this;
  18198. };
  18199. /**
  18200. * Allows back the World matrix computation.
  18201. * Returns the TransformNode.
  18202. */
  18203. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18204. this._isWorldMatrixFrozen = false;
  18205. this.computeWorldMatrix(true);
  18206. return this;
  18207. };
  18208. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18209. /**
  18210. * True if the World matrix has been frozen.
  18211. * Returns a boolean.
  18212. */
  18213. get: function () {
  18214. return this._isWorldMatrixFrozen;
  18215. },
  18216. enumerable: true,
  18217. configurable: true
  18218. });
  18219. /**
  18220. * Retuns the mesh absolute position in the World.
  18221. * Returns a Vector3.
  18222. */
  18223. TransformNode.prototype.getAbsolutePosition = function () {
  18224. this.computeWorldMatrix();
  18225. return this._absolutePosition;
  18226. };
  18227. /**
  18228. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18229. * Returns the TransformNode.
  18230. */
  18231. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18232. if (!absolutePosition) {
  18233. return this;
  18234. }
  18235. var absolutePositionX;
  18236. var absolutePositionY;
  18237. var absolutePositionZ;
  18238. if (absolutePosition.x === undefined) {
  18239. if (arguments.length < 3) {
  18240. return this;
  18241. }
  18242. absolutePositionX = arguments[0];
  18243. absolutePositionY = arguments[1];
  18244. absolutePositionZ = arguments[2];
  18245. }
  18246. else {
  18247. absolutePositionX = absolutePosition.x;
  18248. absolutePositionY = absolutePosition.y;
  18249. absolutePositionZ = absolutePosition.z;
  18250. }
  18251. if (this.parent) {
  18252. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18253. invertParentWorldMatrix.invert();
  18254. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18255. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18256. }
  18257. else {
  18258. this.position.x = absolutePositionX;
  18259. this.position.y = absolutePositionY;
  18260. this.position.z = absolutePositionZ;
  18261. }
  18262. return this;
  18263. };
  18264. /**
  18265. * Sets the mesh position in its local space.
  18266. * Returns the TransformNode.
  18267. */
  18268. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18269. this.computeWorldMatrix();
  18270. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18271. return this;
  18272. };
  18273. /**
  18274. * Returns the mesh position in the local space from the current World matrix values.
  18275. * Returns a new Vector3.
  18276. */
  18277. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18278. this.computeWorldMatrix();
  18279. var invLocalWorldMatrix = this._localWorld.clone();
  18280. invLocalWorldMatrix.invert();
  18281. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18282. };
  18283. /**
  18284. * Translates the mesh along the passed Vector3 in its local space.
  18285. * Returns the TransformNode.
  18286. */
  18287. TransformNode.prototype.locallyTranslate = function (vector3) {
  18288. this.computeWorldMatrix(true);
  18289. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18290. return this;
  18291. };
  18292. /**
  18293. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18294. * @param targetPoint the position (must be in same space as current mesh) to look at
  18295. * @param yawCor optional yaw (y-axis) correction in radians
  18296. * @param pitchCor optional pitch (x-axis) correction in radians
  18297. * @param rollCor optional roll (z-axis) correction in radians
  18298. * @param space the choosen space of the target
  18299. * @returns the TransformNode.
  18300. */
  18301. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18302. if (yawCor === void 0) { yawCor = 0; }
  18303. if (pitchCor === void 0) { pitchCor = 0; }
  18304. if (rollCor === void 0) { rollCor = 0; }
  18305. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18306. var dv = TransformNode._lookAtVectorCache;
  18307. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18308. targetPoint.subtractToRef(pos, dv);
  18309. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18310. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18311. var pitch = Math.atan2(dv.y, len);
  18312. if (this.rotationQuaternion) {
  18313. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18314. }
  18315. else {
  18316. this.rotation.x = pitch + pitchCor;
  18317. this.rotation.y = yaw + yawCor;
  18318. this.rotation.z = rollCor;
  18319. }
  18320. return this;
  18321. };
  18322. /**
  18323. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18324. * This Vector3 is expressed in the World space.
  18325. */
  18326. TransformNode.prototype.getDirection = function (localAxis) {
  18327. var result = BABYLON.Vector3.Zero();
  18328. this.getDirectionToRef(localAxis, result);
  18329. return result;
  18330. };
  18331. /**
  18332. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18333. * localAxis is expressed in the mesh local space.
  18334. * result is computed in the Wordl space from the mesh World matrix.
  18335. * Returns the TransformNode.
  18336. */
  18337. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18338. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18339. return this;
  18340. };
  18341. /**
  18342. * Sets a new pivot point to the current node
  18343. * @param point defines the new pivot point to use
  18344. * @param space defines if the point is in world or local space (local by default)
  18345. * @returns the current TransformNode
  18346. */
  18347. TransformNode.prototype.setPivotPoint = function (point, space) {
  18348. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18349. if (this.getScene().getRenderId() == 0) {
  18350. this.computeWorldMatrix(true);
  18351. }
  18352. var wm = this.getWorldMatrix();
  18353. if (space == BABYLON.Space.WORLD) {
  18354. var tmat = BABYLON.Tmp.Matrix[0];
  18355. wm.invertToRef(tmat);
  18356. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18357. }
  18358. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18359. };
  18360. /**
  18361. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18362. */
  18363. TransformNode.prototype.getPivotPoint = function () {
  18364. var point = BABYLON.Vector3.Zero();
  18365. this.getPivotPointToRef(point);
  18366. return point;
  18367. };
  18368. /**
  18369. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18370. * Returns the TransformNode.
  18371. */
  18372. TransformNode.prototype.getPivotPointToRef = function (result) {
  18373. result.x = -this._pivotMatrix.m[12];
  18374. result.y = -this._pivotMatrix.m[13];
  18375. result.z = -this._pivotMatrix.m[14];
  18376. return this;
  18377. };
  18378. /**
  18379. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18380. */
  18381. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18382. var point = BABYLON.Vector3.Zero();
  18383. this.getAbsolutePivotPointToRef(point);
  18384. return point;
  18385. };
  18386. /**
  18387. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18388. * Returns the TransformNode.
  18389. */
  18390. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18391. result.x = this._pivotMatrix.m[12];
  18392. result.y = this._pivotMatrix.m[13];
  18393. result.z = this._pivotMatrix.m[14];
  18394. this.getPivotPointToRef(result);
  18395. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18396. return this;
  18397. };
  18398. /**
  18399. * Defines the passed node as the parent of the current node.
  18400. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18401. * Returns the TransformNode.
  18402. */
  18403. TransformNode.prototype.setParent = function (node) {
  18404. if (node === null) {
  18405. var rotation = BABYLON.Tmp.Quaternion[0];
  18406. var position = BABYLON.Tmp.Vector3[0];
  18407. var scale = BABYLON.Tmp.Vector3[1];
  18408. if (this.parent && this.parent.computeWorldMatrix) {
  18409. this.parent.computeWorldMatrix(true);
  18410. }
  18411. this.computeWorldMatrix(true);
  18412. this.getWorldMatrix().decompose(scale, rotation, position);
  18413. if (this.rotationQuaternion) {
  18414. this.rotationQuaternion.copyFrom(rotation);
  18415. }
  18416. else {
  18417. rotation.toEulerAnglesToRef(this.rotation);
  18418. }
  18419. this.scaling.x = scale.x;
  18420. this.scaling.y = scale.y;
  18421. this.scaling.z = scale.z;
  18422. this.position.x = position.x;
  18423. this.position.y = position.y;
  18424. this.position.z = position.z;
  18425. }
  18426. else {
  18427. var rotation = BABYLON.Tmp.Quaternion[0];
  18428. var position = BABYLON.Tmp.Vector3[0];
  18429. var scale = BABYLON.Tmp.Vector3[1];
  18430. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18431. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18432. this.computeWorldMatrix(true);
  18433. node.computeWorldMatrix(true);
  18434. node.getWorldMatrix().invertToRef(invParentMatrix);
  18435. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18436. diffMatrix.decompose(scale, rotation, position);
  18437. if (this.rotationQuaternion) {
  18438. this.rotationQuaternion.copyFrom(rotation);
  18439. }
  18440. else {
  18441. rotation.toEulerAnglesToRef(this.rotation);
  18442. }
  18443. this.position.x = position.x;
  18444. this.position.y = position.y;
  18445. this.position.z = position.z;
  18446. this.scaling.x = scale.x;
  18447. this.scaling.y = scale.y;
  18448. this.scaling.z = scale.z;
  18449. }
  18450. this.parent = node;
  18451. return this;
  18452. };
  18453. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18454. get: function () {
  18455. return this._nonUniformScaling;
  18456. },
  18457. enumerable: true,
  18458. configurable: true
  18459. });
  18460. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18461. if (this._nonUniformScaling === value) {
  18462. return false;
  18463. }
  18464. this._nonUniformScaling = true;
  18465. return true;
  18466. };
  18467. /**
  18468. * Attach the current TransformNode to another TransformNode associated with a bone
  18469. * @param bone Bone affecting the TransformNode
  18470. * @param affectedTransformNode TransformNode associated with the bone
  18471. */
  18472. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18473. this._transformToBoneReferal = affectedTransformNode;
  18474. this.parent = bone;
  18475. if (bone.getWorldMatrix().determinant() < 0) {
  18476. this.scalingDeterminant *= -1;
  18477. }
  18478. return this;
  18479. };
  18480. TransformNode.prototype.detachFromBone = function () {
  18481. if (!this.parent) {
  18482. return this;
  18483. }
  18484. if (this.parent.getWorldMatrix().determinant() < 0) {
  18485. this.scalingDeterminant *= -1;
  18486. }
  18487. this._transformToBoneReferal = null;
  18488. this.parent = null;
  18489. return this;
  18490. };
  18491. /**
  18492. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18493. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18494. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18495. * The passed axis is also normalized.
  18496. * Returns the TransformNode.
  18497. */
  18498. TransformNode.prototype.rotate = function (axis, amount, space) {
  18499. axis.normalize();
  18500. if (!this.rotationQuaternion) {
  18501. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18502. this.rotation = BABYLON.Vector3.Zero();
  18503. }
  18504. var rotationQuaternion;
  18505. if (!space || space === BABYLON.Space.LOCAL) {
  18506. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18507. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18508. }
  18509. else {
  18510. if (this.parent) {
  18511. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18512. invertParentWorldMatrix.invert();
  18513. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18514. }
  18515. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18516. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18517. }
  18518. return this;
  18519. };
  18520. /**
  18521. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18522. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18523. * The passed axis is also normalized.
  18524. * Returns the TransformNode.
  18525. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18526. */
  18527. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18528. axis.normalize();
  18529. if (!this.rotationQuaternion) {
  18530. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18531. this.rotation.copyFromFloats(0, 0, 0);
  18532. }
  18533. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18534. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18535. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18536. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18537. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18538. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18539. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18540. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18541. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18542. return this;
  18543. };
  18544. /**
  18545. * Translates the mesh along the axis vector for the passed distance in the given space.
  18546. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18547. * Returns the TransformNode.
  18548. */
  18549. TransformNode.prototype.translate = function (axis, distance, space) {
  18550. var displacementVector = axis.scale(distance);
  18551. if (!space || space === BABYLON.Space.LOCAL) {
  18552. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18553. this.setPositionWithLocalVector(tempV3);
  18554. }
  18555. else {
  18556. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18557. }
  18558. return this;
  18559. };
  18560. /**
  18561. * Adds a rotation step to the mesh current rotation.
  18562. * x, y, z are Euler angles expressed in radians.
  18563. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18564. * This means this rotation is made in the mesh local space only.
  18565. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18566. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18567. * ```javascript
  18568. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18569. * ```
  18570. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18571. * 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.
  18572. * Returns the TransformNode.
  18573. */
  18574. TransformNode.prototype.addRotation = function (x, y, z) {
  18575. var rotationQuaternion;
  18576. if (this.rotationQuaternion) {
  18577. rotationQuaternion = this.rotationQuaternion;
  18578. }
  18579. else {
  18580. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18581. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18582. }
  18583. var accumulation = BABYLON.Tmp.Quaternion[0];
  18584. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18585. rotationQuaternion.multiplyInPlace(accumulation);
  18586. if (!this.rotationQuaternion) {
  18587. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18588. }
  18589. return this;
  18590. };
  18591. /**
  18592. * Computes the mesh World matrix and returns it.
  18593. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18594. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18595. * If the parameter `force`is set to `true`, the actual computation is done.
  18596. * Returns the mesh World Matrix.
  18597. */
  18598. TransformNode.prototype.computeWorldMatrix = function (force) {
  18599. if (this._isWorldMatrixFrozen) {
  18600. return this._worldMatrix;
  18601. }
  18602. if (!force && this.isSynchronized(true)) {
  18603. this._currentRenderId = this.getScene().getRenderId();
  18604. return this._worldMatrix;
  18605. }
  18606. this._cache.position.copyFrom(this.position);
  18607. this._cache.scaling.copyFrom(this.scaling);
  18608. this._cache.pivotMatrixUpdated = false;
  18609. this._cache.billboardMode = this.billboardMode;
  18610. this._currentRenderId = this.getScene().getRenderId();
  18611. this._childRenderId = this.getScene().getRenderId();
  18612. this._isDirty = false;
  18613. // Scaling
  18614. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18615. // Rotation
  18616. //rotate, if quaternion is set and rotation was used
  18617. if (this.rotationQuaternion) {
  18618. var len = this.rotation.length();
  18619. if (len) {
  18620. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18621. this.rotation.copyFromFloats(0, 0, 0);
  18622. }
  18623. }
  18624. if (this.rotationQuaternion) {
  18625. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18626. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18627. }
  18628. else {
  18629. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18630. this._cache.rotation.copyFrom(this.rotation);
  18631. }
  18632. // Translation
  18633. var camera = this.getScene().activeCamera;
  18634. if (this.infiniteDistance && !this.parent && camera) {
  18635. var cameraWorldMatrix = camera.getWorldMatrix();
  18636. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18637. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18638. }
  18639. else {
  18640. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18641. }
  18642. // Composing transformations
  18643. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18644. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18645. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18646. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18647. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18648. // Need to decompose each rotation here
  18649. var currentPosition = BABYLON.Tmp.Vector3[3];
  18650. if (this.parent && this.parent.getWorldMatrix) {
  18651. if (this._transformToBoneReferal) {
  18652. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18653. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18654. }
  18655. else {
  18656. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18657. }
  18658. }
  18659. else {
  18660. currentPosition.copyFrom(this.position);
  18661. }
  18662. currentPosition.subtractInPlace(camera.globalPosition);
  18663. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18664. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18665. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18666. }
  18667. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18668. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18669. }
  18670. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18671. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18672. }
  18673. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18674. }
  18675. else {
  18676. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18677. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18678. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18679. }
  18680. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18681. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18682. }
  18683. // Local world
  18684. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18685. // Parent
  18686. if (this.parent && this.parent.getWorldMatrix) {
  18687. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18688. if (this._transformToBoneReferal) {
  18689. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18690. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18691. }
  18692. else {
  18693. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18694. }
  18695. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18696. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18697. this._worldMatrix.copyFrom(this._localWorld);
  18698. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18699. }
  18700. else {
  18701. if (this._transformToBoneReferal) {
  18702. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18703. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18704. }
  18705. else {
  18706. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18707. }
  18708. }
  18709. this._markSyncedWithParent();
  18710. }
  18711. else {
  18712. this._worldMatrix.copyFrom(this._localWorld);
  18713. }
  18714. // Post multiply inverse of pivotMatrix
  18715. if (this._postMultiplyPivotMatrix) {
  18716. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18717. }
  18718. // Normal matrix
  18719. if (this.scaling.isNonUniform) {
  18720. this._updateNonUniformScalingState(true);
  18721. }
  18722. else if (this.parent && this.parent._nonUniformScaling) {
  18723. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18724. }
  18725. else {
  18726. this._updateNonUniformScalingState(false);
  18727. }
  18728. this._afterComputeWorldMatrix();
  18729. // Absolute position
  18730. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18731. // Callbacks
  18732. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18733. if (!this._poseMatrix) {
  18734. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18735. }
  18736. // Cache the determinant
  18737. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18738. return this._worldMatrix;
  18739. };
  18740. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18741. };
  18742. /**
  18743. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18744. * @param func: callback function to add
  18745. *
  18746. * Returns the TransformNode.
  18747. */
  18748. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18749. this.onAfterWorldMatrixUpdateObservable.add(func);
  18750. return this;
  18751. };
  18752. /**
  18753. * Removes a registered callback function.
  18754. * Returns the TransformNode.
  18755. */
  18756. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18757. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18758. return this;
  18759. };
  18760. /**
  18761. * Clone the current transform node
  18762. * Returns the new transform node
  18763. * @param name Name of the new clone
  18764. * @param newParent New parent for the clone
  18765. * @param doNotCloneChildren Do not clone children hierarchy
  18766. */
  18767. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18768. var _this = this;
  18769. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18770. result.name = name;
  18771. result.id = name;
  18772. if (newParent) {
  18773. result.parent = newParent;
  18774. }
  18775. if (!doNotCloneChildren) {
  18776. // Children
  18777. var directDescendants = this.getDescendants(true);
  18778. for (var index = 0; index < directDescendants.length; index++) {
  18779. var child = directDescendants[index];
  18780. if (child.clone) {
  18781. child.clone(name + "." + child.name, result);
  18782. }
  18783. }
  18784. }
  18785. return result;
  18786. };
  18787. TransformNode.prototype.serialize = function (currentSerializationObject) {
  18788. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  18789. serializationObject.type = this.getClassName();
  18790. // Parent
  18791. if (this.parent) {
  18792. serializationObject.parentId = this.parent.id;
  18793. }
  18794. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  18795. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18796. }
  18797. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  18798. serializationObject.isEnabled = this.isEnabled();
  18799. // Parent
  18800. if (this.parent) {
  18801. serializationObject.parentId = this.parent.id;
  18802. }
  18803. return serializationObject;
  18804. };
  18805. // Statics
  18806. /**
  18807. * Returns a new TransformNode object parsed from the source provided.
  18808. * The parameter `parsedMesh` is the source.
  18809. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18810. */
  18811. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  18812. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  18813. if (BABYLON.Tags) {
  18814. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  18815. }
  18816. if (parsedTransformNode.localMatrix) {
  18817. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  18818. }
  18819. else if (parsedTransformNode.pivotMatrix) {
  18820. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  18821. }
  18822. transformNode.setEnabled(parsedTransformNode.isEnabled);
  18823. // Parent
  18824. if (parsedTransformNode.parentId) {
  18825. transformNode._waitingParentId = parsedTransformNode.parentId;
  18826. }
  18827. return transformNode;
  18828. };
  18829. /**
  18830. * Releases resources associated with this transform node.
  18831. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18832. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18833. */
  18834. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18835. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18836. // Animations
  18837. this.getScene().stopAnimation(this);
  18838. // Remove from scene
  18839. this.getScene().removeTransformNode(this);
  18840. this.onAfterWorldMatrixUpdateObservable.clear();
  18841. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18842. };
  18843. // Statics
  18844. TransformNode.BILLBOARDMODE_NONE = 0;
  18845. TransformNode.BILLBOARDMODE_X = 1;
  18846. TransformNode.BILLBOARDMODE_Y = 2;
  18847. TransformNode.BILLBOARDMODE_Z = 4;
  18848. TransformNode.BILLBOARDMODE_ALL = 7;
  18849. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  18850. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  18851. __decorate([
  18852. BABYLON.serializeAsVector3()
  18853. ], TransformNode.prototype, "_rotation", void 0);
  18854. __decorate([
  18855. BABYLON.serializeAsQuaternion()
  18856. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  18857. __decorate([
  18858. BABYLON.serializeAsVector3()
  18859. ], TransformNode.prototype, "_scaling", void 0);
  18860. __decorate([
  18861. BABYLON.serialize()
  18862. ], TransformNode.prototype, "billboardMode", void 0);
  18863. __decorate([
  18864. BABYLON.serialize()
  18865. ], TransformNode.prototype, "scalingDeterminant", void 0);
  18866. __decorate([
  18867. BABYLON.serialize()
  18868. ], TransformNode.prototype, "infiniteDistance", void 0);
  18869. __decorate([
  18870. BABYLON.serializeAsVector3()
  18871. ], TransformNode.prototype, "position", void 0);
  18872. return TransformNode;
  18873. }(BABYLON.Node));
  18874. BABYLON.TransformNode = TransformNode;
  18875. })(BABYLON || (BABYLON = {}));
  18876. //# sourceMappingURL=babylon.transformNode.js.map
  18877. "use strict";
  18878. var BABYLON;
  18879. (function (BABYLON) {
  18880. var AbstractMesh = /** @class */ (function (_super) {
  18881. __extends(AbstractMesh, _super);
  18882. // Constructor
  18883. function AbstractMesh(name, scene) {
  18884. if (scene === void 0) { scene = null; }
  18885. var _this = _super.call(this, name, scene, false) || this;
  18886. _this._facetNb = 0; // facet number
  18887. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  18888. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  18889. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  18890. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  18891. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  18892. _this._subDiv = {
  18893. max: 1,
  18894. X: 1,
  18895. Y: 1,
  18896. Z: 1
  18897. };
  18898. _this._facetDepthSort = false; // is the facet depth sort to be computed
  18899. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  18900. // Events
  18901. /**
  18902. * An event triggered when this mesh collides with another one
  18903. */
  18904. _this.onCollideObservable = new BABYLON.Observable();
  18905. /**
  18906. * An event triggered when the collision's position changes
  18907. */
  18908. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  18909. /**
  18910. * An event triggered when material is changed
  18911. */
  18912. _this.onMaterialChangedObservable = new BABYLON.Observable();
  18913. // Properties
  18914. _this.definedFacingForward = true; // orientation for POV movement & rotation
  18915. /**
  18916. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  18917. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  18918. * or
  18919. * 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.
  18920. * for more info check WebGl documentations
  18921. */
  18922. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  18923. /**
  18924. * 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:
  18925. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  18926. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  18927. * 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.
  18928. */
  18929. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  18930. /**
  18931. * 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.
  18932. * The default value is -1 which means don't break the query and wait till the result.
  18933. */
  18934. _this.occlusionRetryCount = -1;
  18935. _this._occlusionInternalRetryCounter = 0;
  18936. _this._isOccluded = false;
  18937. _this._isOcclusionQueryInProgress = false;
  18938. _this._visibility = 1.0;
  18939. _this.alphaIndex = Number.MAX_VALUE;
  18940. _this.isVisible = true;
  18941. _this.isPickable = true;
  18942. _this.showBoundingBox = false;
  18943. _this.showSubMeshesBoundingBox = false;
  18944. _this.isBlocker = false;
  18945. _this.enablePointerMoveEvents = false;
  18946. _this.renderingGroupId = 0;
  18947. _this._receiveShadows = false;
  18948. _this.renderOutline = false;
  18949. _this.outlineColor = BABYLON.Color3.Red();
  18950. _this.outlineWidth = 0.02;
  18951. _this.renderOverlay = false;
  18952. _this.overlayColor = BABYLON.Color3.Red();
  18953. _this.overlayAlpha = 0.5;
  18954. _this._hasVertexAlpha = false;
  18955. _this._useVertexColors = true;
  18956. _this._computeBonesUsingShaders = true;
  18957. _this._numBoneInfluencers = 4;
  18958. _this._applyFog = true;
  18959. _this.useOctreeForRenderingSelection = true;
  18960. _this.useOctreeForPicking = true;
  18961. _this.useOctreeForCollisions = true;
  18962. _this._layerMask = 0x0FFFFFFF;
  18963. /**
  18964. * True if the mesh must be rendered in any case.
  18965. */
  18966. _this.alwaysSelectAsActiveMesh = false;
  18967. /**
  18968. * This scene's action manager
  18969. */
  18970. _this.actionManager = null;
  18971. // Physics
  18972. _this.physicsImpostor = null;
  18973. // Collisions
  18974. _this._checkCollisions = false;
  18975. _this._collisionMask = -1;
  18976. _this._collisionGroup = -1;
  18977. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  18978. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  18979. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  18980. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  18981. // Edges
  18982. _this.edgesWidth = 1;
  18983. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  18984. // Cache
  18985. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  18986. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  18987. _this._renderId = 0;
  18988. _this._intersectionsInProgress = new Array();
  18989. _this._unIndexed = false;
  18990. _this._lightSources = new Array();
  18991. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18992. if (collidedMesh === void 0) { collidedMesh = null; }
  18993. //TODO move this to the collision coordinator!
  18994. if (_this.getScene().workerCollisions)
  18995. newPosition.multiplyInPlace(_this._collider._radius);
  18996. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  18997. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  18998. _this.position.addInPlace(_this._diffPositionForCollisions);
  18999. }
  19000. if (collidedMesh) {
  19001. _this.onCollideObservable.notifyObservers(collidedMesh);
  19002. }
  19003. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19004. };
  19005. _this.getScene().addMesh(_this);
  19006. _this._resyncLightSources();
  19007. return _this;
  19008. }
  19009. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19010. get: function () {
  19011. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19012. },
  19013. enumerable: true,
  19014. configurable: true
  19015. });
  19016. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19017. get: function () {
  19018. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19019. },
  19020. enumerable: true,
  19021. configurable: true
  19022. });
  19023. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19024. get: function () {
  19025. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19026. },
  19027. enumerable: true,
  19028. configurable: true
  19029. });
  19030. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19031. get: function () {
  19032. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19033. },
  19034. enumerable: true,
  19035. configurable: true
  19036. });
  19037. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19038. get: function () {
  19039. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19040. },
  19041. enumerable: true,
  19042. configurable: true
  19043. });
  19044. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19045. /**
  19046. * Read-only : the number of facets in the mesh
  19047. */
  19048. get: function () {
  19049. return this._facetNb;
  19050. },
  19051. enumerable: true,
  19052. configurable: true
  19053. });
  19054. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19055. /**
  19056. * The number (integer) of subdivisions per axis in the partioning space
  19057. */
  19058. get: function () {
  19059. return this._partitioningSubdivisions;
  19060. },
  19061. set: function (nb) {
  19062. this._partitioningSubdivisions = nb;
  19063. },
  19064. enumerable: true,
  19065. configurable: true
  19066. });
  19067. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19068. /**
  19069. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19070. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  19071. */
  19072. get: function () {
  19073. return this._partitioningBBoxRatio;
  19074. },
  19075. set: function (ratio) {
  19076. this._partitioningBBoxRatio = ratio;
  19077. },
  19078. enumerable: true,
  19079. configurable: true
  19080. });
  19081. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19082. /**
  19083. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  19084. * Works only for updatable meshes.
  19085. * Doesn't work with multi-materials.
  19086. */
  19087. get: function () {
  19088. return this._facetDepthSort;
  19089. },
  19090. set: function (sort) {
  19091. this._facetDepthSort = sort;
  19092. },
  19093. enumerable: true,
  19094. configurable: true
  19095. });
  19096. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19097. /**
  19098. * The location (Vector3) where the facet depth sort must be computed from.
  19099. * By default, the active camera position.
  19100. * Used only when facet depth sort is enabled.
  19101. */
  19102. get: function () {
  19103. return this._facetDepthSortFrom;
  19104. },
  19105. set: function (location) {
  19106. this._facetDepthSortFrom = location;
  19107. },
  19108. enumerable: true,
  19109. configurable: true
  19110. });
  19111. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19112. /**
  19113. * Read-only boolean : is the feature facetData enabled ?
  19114. */
  19115. get: function () {
  19116. return this._facetDataEnabled;
  19117. },
  19118. enumerable: true,
  19119. configurable: true
  19120. });
  19121. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19122. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19123. return false;
  19124. }
  19125. this._markSubMeshesAsMiscDirty();
  19126. return true;
  19127. };
  19128. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19129. set: function (callback) {
  19130. if (this._onCollideObserver) {
  19131. this.onCollideObservable.remove(this._onCollideObserver);
  19132. }
  19133. this._onCollideObserver = this.onCollideObservable.add(callback);
  19134. },
  19135. enumerable: true,
  19136. configurable: true
  19137. });
  19138. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19139. set: function (callback) {
  19140. if (this._onCollisionPositionChangeObserver) {
  19141. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19142. }
  19143. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19144. },
  19145. enumerable: true,
  19146. configurable: true
  19147. });
  19148. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19149. /**
  19150. * Property isOccluded : 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.
  19151. */
  19152. get: function () {
  19153. return this._isOccluded;
  19154. },
  19155. set: function (value) {
  19156. this._isOccluded = value;
  19157. },
  19158. enumerable: true,
  19159. configurable: true
  19160. });
  19161. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19162. /**
  19163. * Flag to check the progress status of the query
  19164. */
  19165. get: function () {
  19166. return this._isOcclusionQueryInProgress;
  19167. },
  19168. enumerable: true,
  19169. configurable: true
  19170. });
  19171. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19172. /**
  19173. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19174. */
  19175. get: function () {
  19176. return this._visibility;
  19177. },
  19178. /**
  19179. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19180. */
  19181. set: function (value) {
  19182. if (this._visibility === value) {
  19183. return;
  19184. }
  19185. this._visibility = value;
  19186. this._markSubMeshesAsMiscDirty();
  19187. },
  19188. enumerable: true,
  19189. configurable: true
  19190. });
  19191. Object.defineProperty(AbstractMesh.prototype, "material", {
  19192. get: function () {
  19193. return this._material;
  19194. },
  19195. set: function (value) {
  19196. if (this._material === value) {
  19197. return;
  19198. }
  19199. this._material = value;
  19200. if (this.onMaterialChangedObservable.hasObservers) {
  19201. this.onMaterialChangedObservable.notifyObservers(this);
  19202. }
  19203. if (!this.subMeshes) {
  19204. return;
  19205. }
  19206. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19207. var subMesh = _a[_i];
  19208. subMesh.setEffect(null);
  19209. }
  19210. },
  19211. enumerable: true,
  19212. configurable: true
  19213. });
  19214. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19215. get: function () {
  19216. return this._receiveShadows;
  19217. },
  19218. set: function (value) {
  19219. if (this._receiveShadows === value) {
  19220. return;
  19221. }
  19222. this._receiveShadows = value;
  19223. this._markSubMeshesAsLightDirty();
  19224. },
  19225. enumerable: true,
  19226. configurable: true
  19227. });
  19228. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19229. get: function () {
  19230. return this._hasVertexAlpha;
  19231. },
  19232. set: function (value) {
  19233. if (this._hasVertexAlpha === value) {
  19234. return;
  19235. }
  19236. this._hasVertexAlpha = value;
  19237. this._markSubMeshesAsAttributesDirty();
  19238. this._markSubMeshesAsMiscDirty();
  19239. },
  19240. enumerable: true,
  19241. configurable: true
  19242. });
  19243. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19244. get: function () {
  19245. return this._useVertexColors;
  19246. },
  19247. set: function (value) {
  19248. if (this._useVertexColors === value) {
  19249. return;
  19250. }
  19251. this._useVertexColors = value;
  19252. this._markSubMeshesAsAttributesDirty();
  19253. },
  19254. enumerable: true,
  19255. configurable: true
  19256. });
  19257. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19258. get: function () {
  19259. return this._computeBonesUsingShaders;
  19260. },
  19261. set: function (value) {
  19262. if (this._computeBonesUsingShaders === value) {
  19263. return;
  19264. }
  19265. this._computeBonesUsingShaders = value;
  19266. this._markSubMeshesAsAttributesDirty();
  19267. },
  19268. enumerable: true,
  19269. configurable: true
  19270. });
  19271. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19272. get: function () {
  19273. return this._numBoneInfluencers;
  19274. },
  19275. set: function (value) {
  19276. if (this._numBoneInfluencers === value) {
  19277. return;
  19278. }
  19279. this._numBoneInfluencers = value;
  19280. this._markSubMeshesAsAttributesDirty();
  19281. },
  19282. enumerable: true,
  19283. configurable: true
  19284. });
  19285. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19286. get: function () {
  19287. return this._applyFog;
  19288. },
  19289. set: function (value) {
  19290. if (this._applyFog === value) {
  19291. return;
  19292. }
  19293. this._applyFog = value;
  19294. this._markSubMeshesAsMiscDirty();
  19295. },
  19296. enumerable: true,
  19297. configurable: true
  19298. });
  19299. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19300. get: function () {
  19301. return this._layerMask;
  19302. },
  19303. set: function (value) {
  19304. if (value === this._layerMask) {
  19305. return;
  19306. }
  19307. this._layerMask = value;
  19308. this._resyncLightSources();
  19309. },
  19310. enumerable: true,
  19311. configurable: true
  19312. });
  19313. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19314. get: function () {
  19315. return this._collisionMask;
  19316. },
  19317. set: function (mask) {
  19318. this._collisionMask = !isNaN(mask) ? mask : -1;
  19319. },
  19320. enumerable: true,
  19321. configurable: true
  19322. });
  19323. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19324. get: function () {
  19325. return this._collisionGroup;
  19326. },
  19327. set: function (mask) {
  19328. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19329. },
  19330. enumerable: true,
  19331. configurable: true
  19332. });
  19333. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19334. get: function () {
  19335. return null;
  19336. },
  19337. enumerable: true,
  19338. configurable: true
  19339. });
  19340. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19341. get: function () {
  19342. return this._skeleton;
  19343. },
  19344. set: function (value) {
  19345. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19346. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19347. }
  19348. if (value && value.needInitialSkinMatrix) {
  19349. value._registerMeshWithPoseMatrix(this);
  19350. }
  19351. this._skeleton = value;
  19352. if (!this._skeleton) {
  19353. this._bonesTransformMatrices = null;
  19354. }
  19355. this._markSubMeshesAsAttributesDirty();
  19356. },
  19357. enumerable: true,
  19358. configurable: true
  19359. });
  19360. /**
  19361. * Returns the string "AbstractMesh"
  19362. */
  19363. AbstractMesh.prototype.getClassName = function () {
  19364. return "AbstractMesh";
  19365. };
  19366. /**
  19367. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19368. */
  19369. AbstractMesh.prototype.toString = function (fullDetails) {
  19370. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19371. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19372. if (this._skeleton) {
  19373. ret += ", skeleton: " + this._skeleton.name;
  19374. }
  19375. if (fullDetails) {
  19376. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19377. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19378. }
  19379. return ret;
  19380. };
  19381. AbstractMesh.prototype._rebuild = function () {
  19382. if (this._occlusionQuery) {
  19383. this._occlusionQuery = null;
  19384. }
  19385. if (this._edgesRenderer) {
  19386. this._edgesRenderer._rebuild();
  19387. }
  19388. if (!this.subMeshes) {
  19389. return;
  19390. }
  19391. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19392. var subMesh = _a[_i];
  19393. subMesh._rebuild();
  19394. }
  19395. };
  19396. AbstractMesh.prototype._resyncLightSources = function () {
  19397. this._lightSources.length = 0;
  19398. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19399. var light = _a[_i];
  19400. if (!light.isEnabled()) {
  19401. continue;
  19402. }
  19403. if (light.canAffectMesh(this)) {
  19404. this._lightSources.push(light);
  19405. }
  19406. }
  19407. this._markSubMeshesAsLightDirty();
  19408. };
  19409. AbstractMesh.prototype._resyncLighSource = function (light) {
  19410. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19411. var index = this._lightSources.indexOf(light);
  19412. if (index === -1) {
  19413. if (!isIn) {
  19414. return;
  19415. }
  19416. this._lightSources.push(light);
  19417. }
  19418. else {
  19419. if (isIn) {
  19420. return;
  19421. }
  19422. this._lightSources.splice(index, 1);
  19423. }
  19424. this._markSubMeshesAsLightDirty();
  19425. };
  19426. AbstractMesh.prototype._removeLightSource = function (light) {
  19427. var index = this._lightSources.indexOf(light);
  19428. if (index === -1) {
  19429. return;
  19430. }
  19431. this._lightSources.splice(index, 1);
  19432. this._markSubMeshesAsLightDirty();
  19433. };
  19434. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19435. if (!this.subMeshes) {
  19436. return;
  19437. }
  19438. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19439. var subMesh = _a[_i];
  19440. if (subMesh._materialDefines) {
  19441. func(subMesh._materialDefines);
  19442. }
  19443. }
  19444. };
  19445. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19446. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19447. };
  19448. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19449. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19450. };
  19451. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19452. if (!this.subMeshes) {
  19453. return;
  19454. }
  19455. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19456. var subMesh = _a[_i];
  19457. var material = subMesh.getMaterial();
  19458. if (material) {
  19459. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19460. }
  19461. }
  19462. };
  19463. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19464. /**
  19465. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19466. * Default : (1.0, 1.0, 1.0)
  19467. */
  19468. get: function () {
  19469. return this._scaling;
  19470. },
  19471. /**
  19472. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19473. * Default : (1.0, 1.0, 1.0)
  19474. */
  19475. set: function (newScaling) {
  19476. this._scaling = newScaling;
  19477. if (this.physicsImpostor) {
  19478. this.physicsImpostor.forceUpdate();
  19479. }
  19480. },
  19481. enumerable: true,
  19482. configurable: true
  19483. });
  19484. // Methods
  19485. /**
  19486. * Disables the mesh edger rendering mode.
  19487. * Returns the AbstractMesh.
  19488. */
  19489. AbstractMesh.prototype.disableEdgesRendering = function () {
  19490. if (this._edgesRenderer) {
  19491. this._edgesRenderer.dispose();
  19492. this._edgesRenderer = null;
  19493. }
  19494. return this;
  19495. };
  19496. /**
  19497. * Enables the edge rendering mode on the mesh.
  19498. * This mode makes the mesh edges visible.
  19499. * Returns the AbstractMesh.
  19500. */
  19501. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19502. if (epsilon === void 0) { epsilon = 0.95; }
  19503. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19504. this.disableEdgesRendering();
  19505. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19506. return this;
  19507. };
  19508. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19509. /**
  19510. * Returns true if the mesh is blocked. Used by the class Mesh.
  19511. * Returns the boolean `false` by default.
  19512. */
  19513. get: function () {
  19514. return false;
  19515. },
  19516. enumerable: true,
  19517. configurable: true
  19518. });
  19519. /**
  19520. * Returns the mesh itself by default, used by the class Mesh.
  19521. * Returned type : AbstractMesh
  19522. */
  19523. AbstractMesh.prototype.getLOD = function (camera) {
  19524. return this;
  19525. };
  19526. /**
  19527. * Returns 0 by default, used by the class Mesh.
  19528. * Returns an integer.
  19529. */
  19530. AbstractMesh.prototype.getTotalVertices = function () {
  19531. return 0;
  19532. };
  19533. /**
  19534. * Returns null by default, used by the class Mesh.
  19535. * Returned type : integer array
  19536. */
  19537. AbstractMesh.prototype.getIndices = function () {
  19538. return null;
  19539. };
  19540. /**
  19541. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19542. * Returned type : float array or Float32Array
  19543. */
  19544. AbstractMesh.prototype.getVerticesData = function (kind) {
  19545. return null;
  19546. };
  19547. /**
  19548. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19549. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19550. * The `data` are either a numeric array either a Float32Array.
  19551. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19552. * 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).
  19553. * Note that a new underlying VertexBuffer object is created each call.
  19554. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19555. *
  19556. * Possible `kind` values :
  19557. * - BABYLON.VertexBuffer.PositionKind
  19558. * - BABYLON.VertexBuffer.UVKind
  19559. * - BABYLON.VertexBuffer.UV2Kind
  19560. * - BABYLON.VertexBuffer.UV3Kind
  19561. * - BABYLON.VertexBuffer.UV4Kind
  19562. * - BABYLON.VertexBuffer.UV5Kind
  19563. * - BABYLON.VertexBuffer.UV6Kind
  19564. * - BABYLON.VertexBuffer.ColorKind
  19565. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19566. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19567. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19568. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19569. *
  19570. * Returns the Mesh.
  19571. */
  19572. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19573. return this;
  19574. };
  19575. /**
  19576. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19577. * If the mesh has no geometry, it is simply returned as it is.
  19578. * The `data` are either a numeric array either a Float32Array.
  19579. * No new underlying VertexBuffer object is created.
  19580. * 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.
  19581. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19582. *
  19583. * Possible `kind` values :
  19584. * - BABYLON.VertexBuffer.PositionKind
  19585. * - BABYLON.VertexBuffer.UVKind
  19586. * - BABYLON.VertexBuffer.UV2Kind
  19587. * - BABYLON.VertexBuffer.UV3Kind
  19588. * - BABYLON.VertexBuffer.UV4Kind
  19589. * - BABYLON.VertexBuffer.UV5Kind
  19590. * - BABYLON.VertexBuffer.UV6Kind
  19591. * - BABYLON.VertexBuffer.ColorKind
  19592. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19593. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19594. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19595. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19596. *
  19597. * Returns the Mesh.
  19598. */
  19599. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19600. return this;
  19601. };
  19602. /**
  19603. * Sets the mesh indices.
  19604. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19605. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19606. * This method creates a new index buffer each call.
  19607. * Returns the Mesh.
  19608. */
  19609. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19610. return this;
  19611. };
  19612. /** Returns false by default, used by the class Mesh.
  19613. * Returns a boolean
  19614. */
  19615. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19616. return false;
  19617. };
  19618. /**
  19619. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19620. * Returns a BoundingInfo
  19621. */
  19622. AbstractMesh.prototype.getBoundingInfo = function () {
  19623. if (this._masterMesh) {
  19624. return this._masterMesh.getBoundingInfo();
  19625. }
  19626. if (!this._boundingInfo) {
  19627. // this._boundingInfo is being created here
  19628. this._updateBoundingInfo();
  19629. }
  19630. // cannot be null.
  19631. return this._boundingInfo;
  19632. };
  19633. /**
  19634. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19635. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19636. */
  19637. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19638. if (includeDescendants === void 0) { includeDescendants = true; }
  19639. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19640. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19641. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19642. if (maxDimension === 0) {
  19643. return this;
  19644. }
  19645. var scale = 1 / maxDimension;
  19646. this.scaling.scaleInPlace(scale);
  19647. return this;
  19648. };
  19649. /**
  19650. * Sets a mesh new object BoundingInfo.
  19651. * Returns the AbstractMesh.
  19652. */
  19653. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19654. this._boundingInfo = boundingInfo;
  19655. return this;
  19656. };
  19657. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19658. get: function () {
  19659. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19660. },
  19661. enumerable: true,
  19662. configurable: true
  19663. });
  19664. AbstractMesh.prototype._preActivate = function () {
  19665. };
  19666. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19667. };
  19668. AbstractMesh.prototype._activate = function (renderId) {
  19669. this._renderId = renderId;
  19670. };
  19671. /**
  19672. * Returns the latest update of the World matrix
  19673. * Returns a Matrix.
  19674. */
  19675. AbstractMesh.prototype.getWorldMatrix = function () {
  19676. if (this._masterMesh) {
  19677. return this._masterMesh.getWorldMatrix();
  19678. }
  19679. return _super.prototype.getWorldMatrix.call(this);
  19680. };
  19681. /**
  19682. * Returns the latest update of the World matrix determinant.
  19683. */
  19684. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19685. if (this._masterMesh) {
  19686. return this._masterMesh._getWorldMatrixDeterminant();
  19687. }
  19688. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19689. };
  19690. // ================================== Point of View Movement =================================
  19691. /**
  19692. * Perform relative position change from the point of view of behind the front of the mesh.
  19693. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19694. * Supports definition of mesh facing forward or backward.
  19695. * @param {number} amountRight
  19696. * @param {number} amountUp
  19697. * @param {number} amountForward
  19698. *
  19699. * Returns the AbstractMesh.
  19700. */
  19701. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19702. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19703. return this;
  19704. };
  19705. /**
  19706. * Calculate relative position change from the point of view of behind the front of the mesh.
  19707. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19708. * Supports definition of mesh facing forward or backward.
  19709. * @param {number} amountRight
  19710. * @param {number} amountUp
  19711. * @param {number} amountForward
  19712. *
  19713. * Returns a new Vector3.
  19714. */
  19715. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19716. var rotMatrix = new BABYLON.Matrix();
  19717. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19718. rotQuaternion.toRotationMatrix(rotMatrix);
  19719. var translationDelta = BABYLON.Vector3.Zero();
  19720. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19721. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19722. return translationDelta;
  19723. };
  19724. // ================================== Point of View Rotation =================================
  19725. /**
  19726. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19727. * Supports definition of mesh facing forward or backward.
  19728. * @param {number} flipBack
  19729. * @param {number} twirlClockwise
  19730. * @param {number} tiltRight
  19731. *
  19732. * Returns the AbstractMesh.
  19733. */
  19734. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19735. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19736. return this;
  19737. };
  19738. /**
  19739. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19740. * Supports definition of mesh facing forward or backward.
  19741. * @param {number} flipBack
  19742. * @param {number} twirlClockwise
  19743. * @param {number} tiltRight
  19744. *
  19745. * Returns a new Vector3.
  19746. */
  19747. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19748. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19749. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19750. };
  19751. /**
  19752. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19753. * @param includeDescendants Include bounding info from descendants as well (true by default).
  19754. */
  19755. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  19756. if (includeDescendants === void 0) { includeDescendants = true; }
  19757. this.computeWorldMatrix(true);
  19758. var min;
  19759. var max;
  19760. var boundingInfo = this.getBoundingInfo();
  19761. if (!this.subMeshes) {
  19762. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19763. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19764. }
  19765. else {
  19766. min = boundingInfo.boundingBox.minimumWorld;
  19767. max = boundingInfo.boundingBox.maximumWorld;
  19768. }
  19769. if (includeDescendants) {
  19770. var descendants = this.getDescendants(false);
  19771. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  19772. var descendant = descendants_1[_i];
  19773. var childMesh = descendant;
  19774. childMesh.computeWorldMatrix(true);
  19775. //make sure we have the needed params to get mix and max
  19776. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  19777. continue;
  19778. }
  19779. var childBoundingInfo = childMesh.getBoundingInfo();
  19780. var boundingBox = childBoundingInfo.boundingBox;
  19781. var minBox = boundingBox.minimumWorld;
  19782. var maxBox = boundingBox.maximumWorld;
  19783. BABYLON.Tools.CheckExtends(minBox, min, max);
  19784. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19785. }
  19786. }
  19787. return {
  19788. min: min,
  19789. max: max
  19790. };
  19791. };
  19792. /**
  19793. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  19794. * Returns the AbstractMesh.
  19795. */
  19796. AbstractMesh.prototype._updateBoundingInfo = function () {
  19797. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  19798. this._boundingInfo.update(this.worldMatrixFromCache);
  19799. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19800. return this;
  19801. };
  19802. /**
  19803. * Update a mesh's children BoundingInfo objects only.
  19804. * Returns the AbstractMesh.
  19805. */
  19806. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  19807. if (!this.subMeshes) {
  19808. return this;
  19809. }
  19810. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  19811. var subMesh = this.subMeshes[subIndex];
  19812. if (!subMesh.IsGlobal) {
  19813. subMesh.updateBoundingInfo(matrix);
  19814. }
  19815. }
  19816. return this;
  19817. };
  19818. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  19819. // Bounding info
  19820. this._updateBoundingInfo();
  19821. };
  19822. /**
  19823. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  19824. * A mesh is in the frustum if its bounding box intersects the frustum.
  19825. * Boolean returned.
  19826. */
  19827. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  19828. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  19829. };
  19830. /**
  19831. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  19832. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  19833. * Boolean returned.
  19834. */
  19835. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19836. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  19837. ;
  19838. };
  19839. /**
  19840. * True if the mesh intersects another mesh or a SolidParticle object.
  19841. * 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)
  19842. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  19843. * Returns a boolean.
  19844. */
  19845. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  19846. if (precise === void 0) { precise = false; }
  19847. if (!this._boundingInfo || !mesh._boundingInfo) {
  19848. return false;
  19849. }
  19850. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  19851. return true;
  19852. }
  19853. if (includeDescendants) {
  19854. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  19855. var child = _a[_i];
  19856. if (child.intersectsMesh(mesh, precise, true)) {
  19857. return true;
  19858. }
  19859. }
  19860. }
  19861. return false;
  19862. };
  19863. /**
  19864. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  19865. * Returns a boolean.
  19866. */
  19867. AbstractMesh.prototype.intersectsPoint = function (point) {
  19868. if (!this._boundingInfo) {
  19869. return false;
  19870. }
  19871. return this._boundingInfo.intersectsPoint(point);
  19872. };
  19873. AbstractMesh.prototype.getPhysicsImpostor = function () {
  19874. return this.physicsImpostor;
  19875. };
  19876. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  19877. if (camera === void 0) { camera = null; }
  19878. if (!camera) {
  19879. camera = this.getScene().activeCamera;
  19880. }
  19881. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  19882. };
  19883. /**
  19884. * Returns the distance from the mesh to the active camera.
  19885. * Returns a float.
  19886. */
  19887. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  19888. if (camera === void 0) { camera = null; }
  19889. if (!camera) {
  19890. camera = this.getScene().activeCamera;
  19891. }
  19892. return this.absolutePosition.subtract(camera.position).length();
  19893. };
  19894. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  19895. if (!this.physicsImpostor) {
  19896. return this;
  19897. }
  19898. this.physicsImpostor.applyImpulse(force, contactPoint);
  19899. return this;
  19900. };
  19901. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  19902. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  19903. return this;
  19904. }
  19905. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  19906. mainPivot: pivot1,
  19907. connectedPivot: pivot2,
  19908. nativeParams: options
  19909. });
  19910. return this;
  19911. };
  19912. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  19913. // Collisions
  19914. /**
  19915. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  19916. * Default `false`.
  19917. */
  19918. get: function () {
  19919. return this._checkCollisions;
  19920. },
  19921. set: function (collisionEnabled) {
  19922. this._checkCollisions = collisionEnabled;
  19923. if (this.getScene().workerCollisions) {
  19924. this.getScene().collisionCoordinator.onMeshUpdated(this);
  19925. }
  19926. },
  19927. enumerable: true,
  19928. configurable: true
  19929. });
  19930. Object.defineProperty(AbstractMesh.prototype, "collider", {
  19931. /**
  19932. * Gets Collider object used to compute collisions (not physics)
  19933. */
  19934. get: function () {
  19935. return this._collider;
  19936. },
  19937. enumerable: true,
  19938. configurable: true
  19939. });
  19940. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  19941. var globalPosition = this.getAbsolutePosition();
  19942. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  19943. if (!this._collider) {
  19944. this._collider = new BABYLON.Collider();
  19945. }
  19946. this._collider._radius = this.ellipsoid;
  19947. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  19948. return this;
  19949. };
  19950. // Submeshes octree
  19951. /**
  19952. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  19953. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  19954. * Returns an Octree of submeshes.
  19955. */
  19956. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  19957. if (maxCapacity === void 0) { maxCapacity = 64; }
  19958. if (maxDepth === void 0) { maxDepth = 2; }
  19959. if (!this._submeshesOctree) {
  19960. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  19961. }
  19962. this.computeWorldMatrix(true);
  19963. var boundingInfo = this.getBoundingInfo();
  19964. // Update octree
  19965. var bbox = boundingInfo.boundingBox;
  19966. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  19967. return this._submeshesOctree;
  19968. };
  19969. // Collisions
  19970. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  19971. this._generatePointsArray();
  19972. if (!this._positions) {
  19973. return this;
  19974. }
  19975. // Transformation
  19976. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  19977. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  19978. subMesh._lastColliderWorldVertices = [];
  19979. subMesh._trianglePlanes = [];
  19980. var start = subMesh.verticesStart;
  19981. var end = (subMesh.verticesStart + subMesh.verticesCount);
  19982. for (var i = start; i < end; i++) {
  19983. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  19984. }
  19985. }
  19986. // Collide
  19987. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  19988. if (collider.collisionFound) {
  19989. collider.collidedMesh = this;
  19990. }
  19991. return this;
  19992. };
  19993. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  19994. var subMeshes;
  19995. var len;
  19996. // Octrees
  19997. if (this._submeshesOctree && this.useOctreeForCollisions) {
  19998. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  19999. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20000. len = intersections.length;
  20001. subMeshes = intersections.data;
  20002. }
  20003. else {
  20004. subMeshes = this.subMeshes;
  20005. len = subMeshes.length;
  20006. }
  20007. for (var index = 0; index < len; index++) {
  20008. var subMesh = subMeshes[index];
  20009. // Bounding test
  20010. if (len > 1 && !subMesh._checkCollision(collider))
  20011. continue;
  20012. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20013. }
  20014. return this;
  20015. };
  20016. AbstractMesh.prototype._checkCollision = function (collider) {
  20017. // Bounding box test
  20018. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20019. return this;
  20020. // Transformation matrix
  20021. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20022. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20023. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20024. return this;
  20025. };
  20026. // Picking
  20027. AbstractMesh.prototype._generatePointsArray = function () {
  20028. return false;
  20029. };
  20030. /**
  20031. * Checks if the passed Ray intersects with the mesh.
  20032. * Returns an object PickingInfo.
  20033. */
  20034. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20035. var pickingInfo = new BABYLON.PickingInfo();
  20036. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20037. return pickingInfo;
  20038. }
  20039. if (!this._generatePointsArray()) {
  20040. return pickingInfo;
  20041. }
  20042. var intersectInfo = null;
  20043. // Octrees
  20044. var subMeshes;
  20045. var len;
  20046. if (this._submeshesOctree && this.useOctreeForPicking) {
  20047. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20048. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20049. len = intersections.length;
  20050. subMeshes = intersections.data;
  20051. }
  20052. else {
  20053. subMeshes = this.subMeshes;
  20054. len = subMeshes.length;
  20055. }
  20056. for (var index = 0; index < len; index++) {
  20057. var subMesh = subMeshes[index];
  20058. // Bounding test
  20059. if (len > 1 && !subMesh.canIntersects(ray))
  20060. continue;
  20061. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20062. if (currentIntersectInfo) {
  20063. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20064. intersectInfo = currentIntersectInfo;
  20065. intersectInfo.subMeshId = index;
  20066. if (fastCheck) {
  20067. break;
  20068. }
  20069. }
  20070. }
  20071. }
  20072. if (intersectInfo) {
  20073. // Get picked point
  20074. var world = this.getWorldMatrix();
  20075. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20076. var direction = ray.direction.clone();
  20077. direction = direction.scale(intersectInfo.distance);
  20078. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20079. var pickedPoint = worldOrigin.add(worldDirection);
  20080. // Return result
  20081. pickingInfo.hit = true;
  20082. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20083. pickingInfo.pickedPoint = pickedPoint;
  20084. pickingInfo.pickedMesh = this;
  20085. pickingInfo.bu = intersectInfo.bu || 0;
  20086. pickingInfo.bv = intersectInfo.bv || 0;
  20087. pickingInfo.faceId = intersectInfo.faceId;
  20088. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20089. return pickingInfo;
  20090. }
  20091. return pickingInfo;
  20092. };
  20093. /**
  20094. * Clones the mesh, used by the class Mesh.
  20095. * Just returns `null` for an AbstractMesh.
  20096. */
  20097. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20098. return null;
  20099. };
  20100. /**
  20101. * Disposes all the mesh submeshes.
  20102. * Returns the AbstractMesh.
  20103. */
  20104. AbstractMesh.prototype.releaseSubMeshes = function () {
  20105. if (this.subMeshes) {
  20106. while (this.subMeshes.length) {
  20107. this.subMeshes[0].dispose();
  20108. }
  20109. }
  20110. else {
  20111. this.subMeshes = new Array();
  20112. }
  20113. return this;
  20114. };
  20115. /**
  20116. * Releases resources associated with this abstract mesh.
  20117. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20118. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20119. */
  20120. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20121. var _this = this;
  20122. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20123. var index;
  20124. // Smart Array Retainers.
  20125. this.getScene().freeActiveMeshes();
  20126. this.getScene().freeRenderingGroups();
  20127. // Action manager
  20128. if (this.actionManager !== undefined && this.actionManager !== null) {
  20129. this.actionManager.dispose();
  20130. this.actionManager = null;
  20131. }
  20132. // Skeleton
  20133. this._skeleton = null;
  20134. // Physics
  20135. if (this.physicsImpostor) {
  20136. this.physicsImpostor.dispose();
  20137. }
  20138. // Intersections in progress
  20139. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20140. var other = this._intersectionsInProgress[index];
  20141. var pos = other._intersectionsInProgress.indexOf(this);
  20142. other._intersectionsInProgress.splice(pos, 1);
  20143. }
  20144. this._intersectionsInProgress = [];
  20145. // Lights
  20146. var lights = this.getScene().lights;
  20147. lights.forEach(function (light) {
  20148. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20149. if (meshIndex !== -1) {
  20150. light.includedOnlyMeshes.splice(meshIndex, 1);
  20151. }
  20152. meshIndex = light.excludedMeshes.indexOf(_this);
  20153. if (meshIndex !== -1) {
  20154. light.excludedMeshes.splice(meshIndex, 1);
  20155. }
  20156. // Shadow generators
  20157. var generator = light.getShadowGenerator();
  20158. if (generator) {
  20159. var shadowMap = generator.getShadowMap();
  20160. if (shadowMap && shadowMap.renderList) {
  20161. meshIndex = shadowMap.renderList.indexOf(_this);
  20162. if (meshIndex !== -1) {
  20163. shadowMap.renderList.splice(meshIndex, 1);
  20164. }
  20165. }
  20166. }
  20167. });
  20168. // Edges
  20169. if (this._edgesRenderer) {
  20170. this._edgesRenderer.dispose();
  20171. this._edgesRenderer = null;
  20172. }
  20173. // SubMeshes
  20174. if (this.getClassName() !== "InstancedMesh") {
  20175. this.releaseSubMeshes();
  20176. }
  20177. // Octree
  20178. var sceneOctree = this.getScene().selectionOctree;
  20179. if (sceneOctree !== undefined && sceneOctree !== null) {
  20180. var index = sceneOctree.dynamicContent.indexOf(this);
  20181. if (index !== -1) {
  20182. sceneOctree.dynamicContent.splice(index, 1);
  20183. }
  20184. }
  20185. // Query
  20186. var engine = this.getScene().getEngine();
  20187. if (this._occlusionQuery) {
  20188. this._isOcclusionQueryInProgress = false;
  20189. engine.deleteQuery(this._occlusionQuery);
  20190. this._occlusionQuery = null;
  20191. }
  20192. // Engine
  20193. engine.wipeCaches();
  20194. // Remove from scene
  20195. this.getScene().removeMesh(this);
  20196. if (disposeMaterialAndTextures) {
  20197. if (this.material) {
  20198. this.material.dispose(false, true);
  20199. }
  20200. }
  20201. if (!doNotRecurse) {
  20202. // Particles
  20203. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20204. if (this.getScene().particleSystems[index].emitter === this) {
  20205. this.getScene().particleSystems[index].dispose();
  20206. index--;
  20207. }
  20208. }
  20209. }
  20210. // facet data
  20211. if (this._facetDataEnabled) {
  20212. this.disableFacetData();
  20213. }
  20214. this.onAfterWorldMatrixUpdateObservable.clear();
  20215. this.onCollideObservable.clear();
  20216. this.onCollisionPositionChangeObservable.clear();
  20217. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20218. };
  20219. /**
  20220. * Adds the passed mesh as a child to the current mesh.
  20221. * Returns the AbstractMesh.
  20222. */
  20223. AbstractMesh.prototype.addChild = function (mesh) {
  20224. mesh.setParent(this);
  20225. return this;
  20226. };
  20227. /**
  20228. * Removes the passed mesh from the current mesh children list.
  20229. * Returns the AbstractMesh.
  20230. */
  20231. AbstractMesh.prototype.removeChild = function (mesh) {
  20232. mesh.setParent(null);
  20233. return this;
  20234. };
  20235. // Facet data
  20236. /**
  20237. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  20238. * Returns the AbstractMesh.
  20239. */
  20240. AbstractMesh.prototype._initFacetData = function () {
  20241. if (!this._facetNormals) {
  20242. this._facetNormals = new Array();
  20243. }
  20244. if (!this._facetPositions) {
  20245. this._facetPositions = new Array();
  20246. }
  20247. if (!this._facetPartitioning) {
  20248. this._facetPartitioning = new Array();
  20249. }
  20250. this._facetNb = (this.getIndices().length / 3) | 0;
  20251. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20252. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20253. for (var f = 0; f < this._facetNb; f++) {
  20254. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20255. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20256. }
  20257. this._facetDataEnabled = true;
  20258. return this;
  20259. };
  20260. /**
  20261. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20262. * This method can be called within the render loop.
  20263. * 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.
  20264. * Returns the AbstractMesh.
  20265. */
  20266. AbstractMesh.prototype.updateFacetData = function () {
  20267. if (!this._facetDataEnabled) {
  20268. this._initFacetData();
  20269. }
  20270. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20271. var indices = this.getIndices();
  20272. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20273. var bInfo = this.getBoundingInfo();
  20274. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20275. // init arrays, matrix and sort function on first call
  20276. this._facetDepthSortEnabled = true;
  20277. if (indices instanceof Uint16Array) {
  20278. this._depthSortedIndices = new Uint16Array(indices);
  20279. }
  20280. else if (indices instanceof Uint32Array) {
  20281. this._depthSortedIndices = new Uint32Array(indices);
  20282. }
  20283. else {
  20284. var needs32bits = false;
  20285. for (var i = 0; i < indices.length; i++) {
  20286. if (indices[i] > 65535) {
  20287. needs32bits = true;
  20288. break;
  20289. }
  20290. }
  20291. if (needs32bits) {
  20292. this._depthSortedIndices = new Uint32Array(indices);
  20293. }
  20294. else {
  20295. this._depthSortedIndices = new Uint16Array(indices);
  20296. }
  20297. }
  20298. this._facetDepthSortFunction = function (f1, f2) {
  20299. return (f2.sqDistance - f1.sqDistance);
  20300. };
  20301. if (!this._facetDepthSortFrom) {
  20302. var camera = this.getScene().activeCamera;
  20303. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20304. }
  20305. this._depthSortedFacets = [];
  20306. for (var f = 0; f < this._facetNb; f++) {
  20307. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20308. this._depthSortedFacets.push(depthSortedFacet);
  20309. }
  20310. this._invertedMatrix = BABYLON.Matrix.Identity();
  20311. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20312. }
  20313. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20314. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20315. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20316. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20317. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20318. this._subDiv.max = this._partitioningSubdivisions;
  20319. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20320. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20321. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20322. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20323. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20324. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20325. // set the parameters for ComputeNormals()
  20326. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20327. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20328. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20329. this._facetParameters.bInfo = bInfo;
  20330. this._facetParameters.bbSize = this._bbSize;
  20331. this._facetParameters.subDiv = this._subDiv;
  20332. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20333. this._facetParameters.depthSort = this._facetDepthSort;
  20334. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20335. this.computeWorldMatrix(true);
  20336. this._worldMatrix.invertToRef(this._invertedMatrix);
  20337. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20338. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20339. }
  20340. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20341. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20342. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20343. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20344. var l = (this._depthSortedIndices.length / 3) | 0;
  20345. for (var f = 0; f < l; f++) {
  20346. var sind = this._depthSortedFacets[f].ind;
  20347. this._depthSortedIndices[f * 3] = indices[sind];
  20348. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20349. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20350. }
  20351. this.updateIndices(this._depthSortedIndices);
  20352. }
  20353. return this;
  20354. };
  20355. /**
  20356. * Returns the facetLocalNormals array.
  20357. * The normals are expressed in the mesh local space.
  20358. */
  20359. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20360. if (!this._facetNormals) {
  20361. this.updateFacetData();
  20362. }
  20363. return this._facetNormals;
  20364. };
  20365. /**
  20366. * Returns the facetLocalPositions array.
  20367. * The facet positions are expressed in the mesh local space.
  20368. */
  20369. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20370. if (!this._facetPositions) {
  20371. this.updateFacetData();
  20372. }
  20373. return this._facetPositions;
  20374. };
  20375. /**
  20376. * Returns the facetLocalPartioning array.
  20377. */
  20378. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20379. if (!this._facetPartitioning) {
  20380. this.updateFacetData();
  20381. }
  20382. return this._facetPartitioning;
  20383. };
  20384. /**
  20385. * Returns the i-th facet position in the world system.
  20386. * This method allocates a new Vector3 per call.
  20387. */
  20388. AbstractMesh.prototype.getFacetPosition = function (i) {
  20389. var pos = BABYLON.Vector3.Zero();
  20390. this.getFacetPositionToRef(i, pos);
  20391. return pos;
  20392. };
  20393. /**
  20394. * Sets the reference Vector3 with the i-th facet position in the world system.
  20395. * Returns the AbstractMesh.
  20396. */
  20397. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20398. var localPos = (this.getFacetLocalPositions())[i];
  20399. var world = this.getWorldMatrix();
  20400. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20401. return this;
  20402. };
  20403. /**
  20404. * Returns the i-th facet normal in the world system.
  20405. * This method allocates a new Vector3 per call.
  20406. */
  20407. AbstractMesh.prototype.getFacetNormal = function (i) {
  20408. var norm = BABYLON.Vector3.Zero();
  20409. this.getFacetNormalToRef(i, norm);
  20410. return norm;
  20411. };
  20412. /**
  20413. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20414. * Returns the AbstractMesh.
  20415. */
  20416. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20417. var localNorm = (this.getFacetLocalNormals())[i];
  20418. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20419. return this;
  20420. };
  20421. /**
  20422. * 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).
  20423. */
  20424. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20425. var bInfo = this.getBoundingInfo();
  20426. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20427. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20428. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20429. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20430. return null;
  20431. }
  20432. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20433. };
  20434. /**
  20435. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20436. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20437. * If checkFace is 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.
  20438. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20439. * 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.
  20440. */
  20441. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20442. if (checkFace === void 0) { checkFace = false; }
  20443. if (facing === void 0) { facing = true; }
  20444. var world = this.getWorldMatrix();
  20445. var invMat = BABYLON.Tmp.Matrix[5];
  20446. world.invertToRef(invMat);
  20447. var invVect = BABYLON.Tmp.Vector3[8];
  20448. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20449. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20450. if (projected) {
  20451. // tranform the local computed projected vector to world coordinates
  20452. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20453. }
  20454. return closest;
  20455. };
  20456. /**
  20457. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20458. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20459. * If checkFace is 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.
  20460. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20461. * 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.
  20462. */
  20463. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20464. if (checkFace === void 0) { checkFace = false; }
  20465. if (facing === void 0) { facing = true; }
  20466. var closest = null;
  20467. var tmpx = 0.0;
  20468. var tmpy = 0.0;
  20469. var tmpz = 0.0;
  20470. var d = 0.0; // tmp dot facet normal * facet position
  20471. var t0 = 0.0;
  20472. var projx = 0.0;
  20473. var projy = 0.0;
  20474. var projz = 0.0;
  20475. // Get all the facets in the same partitioning block than (x, y, z)
  20476. var facetPositions = this.getFacetLocalPositions();
  20477. var facetNormals = this.getFacetLocalNormals();
  20478. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20479. if (!facetsInBlock) {
  20480. return null;
  20481. }
  20482. // Get the closest facet to (x, y, z)
  20483. var shortest = Number.MAX_VALUE; // init distance vars
  20484. var tmpDistance = shortest;
  20485. var fib; // current facet in the block
  20486. var norm; // current facet normal
  20487. var p0; // current facet barycenter position
  20488. // loop on all the facets in the current partitioning block
  20489. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20490. fib = facetsInBlock[idx];
  20491. norm = facetNormals[fib];
  20492. p0 = facetPositions[fib];
  20493. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20494. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20495. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20496. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20497. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20498. projx = x + norm.x * t0;
  20499. projy = y + norm.y * t0;
  20500. projz = z + norm.z * t0;
  20501. tmpx = projx - x;
  20502. tmpy = projy - y;
  20503. tmpz = projz - z;
  20504. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20505. if (tmpDistance < shortest) {
  20506. shortest = tmpDistance;
  20507. closest = fib;
  20508. if (projected) {
  20509. projected.x = projx;
  20510. projected.y = projy;
  20511. projected.z = projz;
  20512. }
  20513. }
  20514. }
  20515. }
  20516. return closest;
  20517. };
  20518. /**
  20519. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20520. */
  20521. AbstractMesh.prototype.getFacetDataParameters = function () {
  20522. return this._facetParameters;
  20523. };
  20524. /**
  20525. * Disables the feature FacetData and frees the related memory.
  20526. * Returns the AbstractMesh.
  20527. */
  20528. AbstractMesh.prototype.disableFacetData = function () {
  20529. if (this._facetDataEnabled) {
  20530. this._facetDataEnabled = false;
  20531. this._facetPositions = new Array();
  20532. this._facetNormals = new Array();
  20533. this._facetPartitioning = new Array();
  20534. this._facetParameters = null;
  20535. this._depthSortedIndices = new Uint32Array(0);
  20536. }
  20537. return this;
  20538. };
  20539. /**
  20540. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20541. * Returns the mesh.
  20542. */
  20543. AbstractMesh.prototype.updateIndices = function (indices) {
  20544. return this;
  20545. };
  20546. /**
  20547. * The mesh Geometry. Actually used by the Mesh object.
  20548. * Returns a blank geometry object.
  20549. */
  20550. /**
  20551. * Creates new normals data for the mesh.
  20552. * @param updatable.
  20553. */
  20554. AbstractMesh.prototype.createNormals = function (updatable) {
  20555. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20556. var indices = this.getIndices();
  20557. var normals;
  20558. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20559. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20560. }
  20561. else {
  20562. normals = [];
  20563. }
  20564. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20565. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20566. };
  20567. /**
  20568. * Align the mesh with a normal.
  20569. * Returns the mesh.
  20570. */
  20571. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20572. if (!upDirection) {
  20573. upDirection = BABYLON.Axis.Y;
  20574. }
  20575. var axisX = BABYLON.Tmp.Vector3[0];
  20576. var axisZ = BABYLON.Tmp.Vector3[1];
  20577. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20578. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20579. if (this.rotationQuaternion) {
  20580. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20581. }
  20582. else {
  20583. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20584. }
  20585. return this;
  20586. };
  20587. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20588. var engine = this.getEngine();
  20589. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20590. this._isOccluded = false;
  20591. return;
  20592. }
  20593. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20594. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20595. if (isOcclusionQueryAvailable) {
  20596. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20597. this._isOcclusionQueryInProgress = false;
  20598. this._occlusionInternalRetryCounter = 0;
  20599. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20600. }
  20601. else {
  20602. this._occlusionInternalRetryCounter++;
  20603. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20604. this._isOcclusionQueryInProgress = false;
  20605. this._occlusionInternalRetryCounter = 0;
  20606. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20607. // if strict continue the last state of the object.
  20608. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20609. }
  20610. else {
  20611. return;
  20612. }
  20613. }
  20614. }
  20615. var scene = this.getScene();
  20616. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20617. if (!this._occlusionQuery) {
  20618. this._occlusionQuery = engine.createQuery();
  20619. }
  20620. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20621. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20622. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20623. this._isOcclusionQueryInProgress = true;
  20624. };
  20625. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20626. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20627. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20628. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20629. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20630. return AbstractMesh;
  20631. }(BABYLON.TransformNode));
  20632. BABYLON.AbstractMesh = AbstractMesh;
  20633. })(BABYLON || (BABYLON = {}));
  20634. //# sourceMappingURL=babylon.abstractMesh.js.map
  20635. "use strict";
  20636. var BABYLON;
  20637. (function (BABYLON) {
  20638. /**
  20639. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20640. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20641. * 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.
  20642. */
  20643. var Light = /** @class */ (function (_super) {
  20644. __extends(Light, _super);
  20645. /**
  20646. * Creates a Light object in the scene.
  20647. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20648. * @param name The firendly name of the light
  20649. * @param scene The scene the light belongs too
  20650. */
  20651. function Light(name, scene) {
  20652. var _this = _super.call(this, name, scene) || this;
  20653. /**
  20654. * Diffuse gives the basic color to an object.
  20655. */
  20656. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20657. /**
  20658. * Specular produces a highlight color on an object.
  20659. * Note: This is note affecting PBR materials.
  20660. */
  20661. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20662. /**
  20663. * Strength of the light.
  20664. * Note: By default it is define in the framework own unit.
  20665. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20666. */
  20667. _this.intensity = 1.0;
  20668. /**
  20669. * Defines how far from the source the light is impacting in scene units.
  20670. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20671. */
  20672. _this.range = Number.MAX_VALUE;
  20673. /**
  20674. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20675. * of light.
  20676. */
  20677. _this._photometricScale = 1.0;
  20678. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20679. _this._radius = 0.00001;
  20680. /**
  20681. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20682. * exceeding the number allowed of the materials.
  20683. */
  20684. _this.renderPriority = 0;
  20685. /**
  20686. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20687. * the current shadow generator.
  20688. */
  20689. _this.shadowEnabled = true;
  20690. _this._excludeWithLayerMask = 0;
  20691. _this._includeOnlyWithLayerMask = 0;
  20692. _this._lightmapMode = 0;
  20693. /**
  20694. * @ignore Internal use only.
  20695. */
  20696. _this._excludedMeshesIds = new Array();
  20697. /**
  20698. * @ignore Internal use only.
  20699. */
  20700. _this._includedOnlyMeshesIds = new Array();
  20701. _this.getScene().addLight(_this);
  20702. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20703. _this._buildUniformLayout();
  20704. _this.includedOnlyMeshes = new Array();
  20705. _this.excludedMeshes = new Array();
  20706. _this._resyncMeshes();
  20707. return _this;
  20708. }
  20709. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20710. /**
  20711. * If every light affecting the material is in this lightmapMode,
  20712. * material.lightmapTexture adds or multiplies
  20713. * (depends on material.useLightmapAsShadowmap)
  20714. * after every other light calculations.
  20715. */
  20716. get: function () {
  20717. return Light._LIGHTMAP_DEFAULT;
  20718. },
  20719. enumerable: true,
  20720. configurable: true
  20721. });
  20722. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20723. /**
  20724. * material.lightmapTexture as only diffuse lighting from this light
  20725. * adds only specular lighting from this light
  20726. * adds dynamic shadows
  20727. */
  20728. get: function () {
  20729. return Light._LIGHTMAP_SPECULAR;
  20730. },
  20731. enumerable: true,
  20732. configurable: true
  20733. });
  20734. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20735. /**
  20736. * material.lightmapTexture as only lighting
  20737. * no light calculation from this light
  20738. * only adds dynamic shadows from this light
  20739. */
  20740. get: function () {
  20741. return Light._LIGHTMAP_SHADOWSONLY;
  20742. },
  20743. enumerable: true,
  20744. configurable: true
  20745. });
  20746. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20747. /**
  20748. * Each light type uses the default quantity according to its type:
  20749. * point/spot lights use luminous intensity
  20750. * directional lights use illuminance
  20751. */
  20752. get: function () {
  20753. return Light._INTENSITYMODE_AUTOMATIC;
  20754. },
  20755. enumerable: true,
  20756. configurable: true
  20757. });
  20758. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  20759. /**
  20760. * lumen (lm)
  20761. */
  20762. get: function () {
  20763. return Light._INTENSITYMODE_LUMINOUSPOWER;
  20764. },
  20765. enumerable: true,
  20766. configurable: true
  20767. });
  20768. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  20769. /**
  20770. * candela (lm/sr)
  20771. */
  20772. get: function () {
  20773. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  20774. },
  20775. enumerable: true,
  20776. configurable: true
  20777. });
  20778. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  20779. /**
  20780. * lux (lm/m^2)
  20781. */
  20782. get: function () {
  20783. return Light._INTENSITYMODE_ILLUMINANCE;
  20784. },
  20785. enumerable: true,
  20786. configurable: true
  20787. });
  20788. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  20789. /**
  20790. * nit (cd/m^2)
  20791. */
  20792. get: function () {
  20793. return Light._INTENSITYMODE_LUMINANCE;
  20794. },
  20795. enumerable: true,
  20796. configurable: true
  20797. });
  20798. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  20799. /**
  20800. * Light type const id of the point light.
  20801. */
  20802. get: function () {
  20803. return Light._LIGHTTYPEID_POINTLIGHT;
  20804. },
  20805. enumerable: true,
  20806. configurable: true
  20807. });
  20808. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  20809. /**
  20810. * Light type const id of the directional light.
  20811. */
  20812. get: function () {
  20813. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  20814. },
  20815. enumerable: true,
  20816. configurable: true
  20817. });
  20818. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  20819. /**
  20820. * Light type const id of the spot light.
  20821. */
  20822. get: function () {
  20823. return Light._LIGHTTYPEID_SPOTLIGHT;
  20824. },
  20825. enumerable: true,
  20826. configurable: true
  20827. });
  20828. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  20829. /**
  20830. * Light type const id of the hemispheric light.
  20831. */
  20832. get: function () {
  20833. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  20834. },
  20835. enumerable: true,
  20836. configurable: true
  20837. });
  20838. Object.defineProperty(Light.prototype, "intensityMode", {
  20839. /**
  20840. * Gets the photometric scale used to interpret the intensity.
  20841. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20842. */
  20843. get: function () {
  20844. return this._intensityMode;
  20845. },
  20846. /**
  20847. * Sets the photometric scale used to interpret the intensity.
  20848. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  20849. */
  20850. set: function (value) {
  20851. this._intensityMode = value;
  20852. this._computePhotometricScale();
  20853. },
  20854. enumerable: true,
  20855. configurable: true
  20856. });
  20857. ;
  20858. ;
  20859. Object.defineProperty(Light.prototype, "radius", {
  20860. /**
  20861. * Gets the light radius used by PBR Materials to simulate soft area lights.
  20862. */
  20863. get: function () {
  20864. return this._radius;
  20865. },
  20866. /**
  20867. * sets the light radius used by PBR Materials to simulate soft area lights.
  20868. */
  20869. set: function (value) {
  20870. this._radius = value;
  20871. this._computePhotometricScale();
  20872. },
  20873. enumerable: true,
  20874. configurable: true
  20875. });
  20876. ;
  20877. ;
  20878. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  20879. /**
  20880. * Gets the only meshes impacted by this light.
  20881. */
  20882. get: function () {
  20883. return this._includedOnlyMeshes;
  20884. },
  20885. /**
  20886. * Sets the only meshes impacted by this light.
  20887. */
  20888. set: function (value) {
  20889. this._includedOnlyMeshes = value;
  20890. this._hookArrayForIncludedOnly(value);
  20891. },
  20892. enumerable: true,
  20893. configurable: true
  20894. });
  20895. Object.defineProperty(Light.prototype, "excludedMeshes", {
  20896. /**
  20897. * Gets the meshes not impacted by this light.
  20898. */
  20899. get: function () {
  20900. return this._excludedMeshes;
  20901. },
  20902. /**
  20903. * Sets the meshes not impacted by this light.
  20904. */
  20905. set: function (value) {
  20906. this._excludedMeshes = value;
  20907. this._hookArrayForExcluded(value);
  20908. },
  20909. enumerable: true,
  20910. configurable: true
  20911. });
  20912. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  20913. /**
  20914. * Gets the layer id use to find what meshes are not impacted by the light.
  20915. * Inactive if 0
  20916. */
  20917. get: function () {
  20918. return this._excludeWithLayerMask;
  20919. },
  20920. /**
  20921. * Sets the layer id use to find what meshes are not impacted by the light.
  20922. * Inactive if 0
  20923. */
  20924. set: function (value) {
  20925. this._excludeWithLayerMask = value;
  20926. this._resyncMeshes();
  20927. },
  20928. enumerable: true,
  20929. configurable: true
  20930. });
  20931. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  20932. /**
  20933. * Gets the layer id use to find what meshes are impacted by the light.
  20934. * Inactive if 0
  20935. */
  20936. get: function () {
  20937. return this._includeOnlyWithLayerMask;
  20938. },
  20939. /**
  20940. * Sets the layer id use to find what meshes are impacted by the light.
  20941. * Inactive if 0
  20942. */
  20943. set: function (value) {
  20944. this._includeOnlyWithLayerMask = value;
  20945. this._resyncMeshes();
  20946. },
  20947. enumerable: true,
  20948. configurable: true
  20949. });
  20950. Object.defineProperty(Light.prototype, "lightmapMode", {
  20951. /**
  20952. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20953. */
  20954. get: function () {
  20955. return this._lightmapMode;
  20956. },
  20957. /**
  20958. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  20959. */
  20960. set: function (value) {
  20961. if (this._lightmapMode === value) {
  20962. return;
  20963. }
  20964. this._lightmapMode = value;
  20965. this._markMeshesAsLightDirty();
  20966. },
  20967. enumerable: true,
  20968. configurable: true
  20969. });
  20970. /**
  20971. * Returns the string "Light".
  20972. * @returns the class name
  20973. */
  20974. Light.prototype.getClassName = function () {
  20975. return "Light";
  20976. };
  20977. /**
  20978. * Converts the light information to a readable string for debug purpose.
  20979. * @param fullDetails Supports for multiple levels of logging within scene loading
  20980. * @returns the human readable light info
  20981. */
  20982. Light.prototype.toString = function (fullDetails) {
  20983. var ret = "Name: " + this.name;
  20984. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  20985. if (this.animations) {
  20986. for (var i = 0; i < this.animations.length; i++) {
  20987. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20988. }
  20989. }
  20990. if (fullDetails) {
  20991. }
  20992. return ret;
  20993. };
  20994. /**
  20995. * Set the enabled state of this node.
  20996. * @param value - the new enabled state
  20997. */
  20998. Light.prototype.setEnabled = function (value) {
  20999. _super.prototype.setEnabled.call(this, value);
  21000. this._resyncMeshes();
  21001. };
  21002. /**
  21003. * Returns the Light associated shadow generator if any.
  21004. * @return the associated shadow generator.
  21005. */
  21006. Light.prototype.getShadowGenerator = function () {
  21007. return this._shadowGenerator;
  21008. };
  21009. /**
  21010. * Returns a Vector3, the absolute light position in the World.
  21011. * @returns the world space position of the light
  21012. */
  21013. Light.prototype.getAbsolutePosition = function () {
  21014. return BABYLON.Vector3.Zero();
  21015. };
  21016. /**
  21017. * Specifies if the light will affect the passed mesh.
  21018. * @param mesh The mesh to test against the light
  21019. * @return true the mesh is affected otherwise, false.
  21020. */
  21021. Light.prototype.canAffectMesh = function (mesh) {
  21022. if (!mesh) {
  21023. return true;
  21024. }
  21025. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21026. return false;
  21027. }
  21028. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21029. return false;
  21030. }
  21031. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21032. return false;
  21033. }
  21034. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21035. return false;
  21036. }
  21037. return true;
  21038. };
  21039. /**
  21040. * Computes and Returns the light World matrix.
  21041. * @returns the world matrix
  21042. */
  21043. Light.prototype.getWorldMatrix = function () {
  21044. this._currentRenderId = this.getScene().getRenderId();
  21045. this._childRenderId = this._currentRenderId;
  21046. var worldMatrix = this._getWorldMatrix();
  21047. if (this.parent && this.parent.getWorldMatrix) {
  21048. if (!this._parentedWorldMatrix) {
  21049. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21050. }
  21051. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21052. this._markSyncedWithParent();
  21053. return this._parentedWorldMatrix;
  21054. }
  21055. return worldMatrix;
  21056. };
  21057. /**
  21058. * Sort function to order lights for rendering.
  21059. * @param a First Light object to compare to second.
  21060. * @param b Second Light object to compare first.
  21061. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21062. */
  21063. Light.CompareLightsPriority = function (a, b) {
  21064. //shadow-casting lights have priority over non-shadow-casting lights
  21065. //the renderPrioirty is a secondary sort criterion
  21066. if (a.shadowEnabled !== b.shadowEnabled) {
  21067. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21068. }
  21069. return b.renderPriority - a.renderPriority;
  21070. };
  21071. /**
  21072. * Releases resources associated with this node.
  21073. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21074. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21075. */
  21076. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21077. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21078. if (this._shadowGenerator) {
  21079. this._shadowGenerator.dispose();
  21080. this._shadowGenerator = null;
  21081. }
  21082. // Animations
  21083. this.getScene().stopAnimation(this);
  21084. // Remove from meshes
  21085. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21086. var mesh = _a[_i];
  21087. mesh._removeLightSource(this);
  21088. }
  21089. this._uniformBuffer.dispose();
  21090. // Remove from scene
  21091. this.getScene().removeLight(this);
  21092. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21093. };
  21094. /**
  21095. * Returns the light type ID (integer).
  21096. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21097. */
  21098. Light.prototype.getTypeID = function () {
  21099. return 0;
  21100. };
  21101. /**
  21102. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21103. * @returns the scaled intensity in intensity mode unit
  21104. */
  21105. Light.prototype.getScaledIntensity = function () {
  21106. return this._photometricScale * this.intensity;
  21107. };
  21108. /**
  21109. * Returns a new Light object, named "name", from the current one.
  21110. * @param name The name of the cloned light
  21111. * @returns the new created light
  21112. */
  21113. Light.prototype.clone = function (name) {
  21114. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21115. if (!constructor) {
  21116. return null;
  21117. }
  21118. return BABYLON.SerializationHelper.Clone(constructor, this);
  21119. };
  21120. /**
  21121. * Serializes the current light into a Serialization object.
  21122. * @returns the serialized object.
  21123. */
  21124. Light.prototype.serialize = function () {
  21125. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21126. // Type
  21127. serializationObject.type = this.getTypeID();
  21128. // Parent
  21129. if (this.parent) {
  21130. serializationObject.parentId = this.parent.id;
  21131. }
  21132. // Inclusion / exclusions
  21133. if (this.excludedMeshes.length > 0) {
  21134. serializationObject.excludedMeshesIds = [];
  21135. this.excludedMeshes.forEach(function (mesh) {
  21136. serializationObject.excludedMeshesIds.push(mesh.id);
  21137. });
  21138. }
  21139. if (this.includedOnlyMeshes.length > 0) {
  21140. serializationObject.includedOnlyMeshesIds = [];
  21141. this.includedOnlyMeshes.forEach(function (mesh) {
  21142. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21143. });
  21144. }
  21145. // Animations
  21146. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21147. serializationObject.ranges = this.serializeAnimationRanges();
  21148. return serializationObject;
  21149. };
  21150. /**
  21151. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21152. * This new light is named "name" and added to the passed scene.
  21153. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21154. * @param name The friendly name of the light
  21155. * @param scene The scene the new light will belong to
  21156. * @returns the constructor function
  21157. */
  21158. Light.GetConstructorFromName = function (type, name, scene) {
  21159. switch (type) {
  21160. case 0:
  21161. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21162. case 1:
  21163. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21164. case 2:
  21165. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21166. case 3:
  21167. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21168. }
  21169. return null;
  21170. };
  21171. /**
  21172. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21173. * @param parsedLight The JSON representation of the light
  21174. * @param scene The scene to create the parsed light in
  21175. * @returns the created light after parsing
  21176. */
  21177. Light.Parse = function (parsedLight, scene) {
  21178. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21179. if (!constructor) {
  21180. return null;
  21181. }
  21182. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21183. // Inclusion / exclusions
  21184. if (parsedLight.excludedMeshesIds) {
  21185. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21186. }
  21187. if (parsedLight.includedOnlyMeshesIds) {
  21188. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21189. }
  21190. // Parent
  21191. if (parsedLight.parentId) {
  21192. light._waitingParentId = parsedLight.parentId;
  21193. }
  21194. // Animations
  21195. if (parsedLight.animations) {
  21196. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21197. var parsedAnimation = parsedLight.animations[animationIndex];
  21198. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21199. }
  21200. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21201. }
  21202. if (parsedLight.autoAnimate) {
  21203. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21204. }
  21205. return light;
  21206. };
  21207. Light.prototype._hookArrayForExcluded = function (array) {
  21208. var _this = this;
  21209. var oldPush = array.push;
  21210. array.push = function () {
  21211. var items = [];
  21212. for (var _i = 0; _i < arguments.length; _i++) {
  21213. items[_i] = arguments[_i];
  21214. }
  21215. var result = oldPush.apply(array, items);
  21216. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21217. var item = items_1[_a];
  21218. item._resyncLighSource(_this);
  21219. }
  21220. return result;
  21221. };
  21222. var oldSplice = array.splice;
  21223. array.splice = function (index, deleteCount) {
  21224. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21225. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21226. var item = deleted_1[_i];
  21227. item._resyncLighSource(_this);
  21228. }
  21229. return deleted;
  21230. };
  21231. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21232. var item = array_1[_i];
  21233. item._resyncLighSource(this);
  21234. }
  21235. };
  21236. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21237. var _this = this;
  21238. var oldPush = array.push;
  21239. array.push = function () {
  21240. var items = [];
  21241. for (var _i = 0; _i < arguments.length; _i++) {
  21242. items[_i] = arguments[_i];
  21243. }
  21244. var result = oldPush.apply(array, items);
  21245. _this._resyncMeshes();
  21246. return result;
  21247. };
  21248. var oldSplice = array.splice;
  21249. array.splice = function (index, deleteCount) {
  21250. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21251. _this._resyncMeshes();
  21252. return deleted;
  21253. };
  21254. this._resyncMeshes();
  21255. };
  21256. Light.prototype._resyncMeshes = function () {
  21257. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21258. var mesh = _a[_i];
  21259. mesh._resyncLighSource(this);
  21260. }
  21261. };
  21262. /**
  21263. * Forces the meshes to update their light related information in their rendering used effects
  21264. * @ignore Internal Use Only
  21265. */
  21266. Light.prototype._markMeshesAsLightDirty = function () {
  21267. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21268. var mesh = _a[_i];
  21269. if (mesh._lightSources.indexOf(this) !== -1) {
  21270. mesh._markSubMeshesAsLightDirty();
  21271. }
  21272. }
  21273. };
  21274. /**
  21275. * Recomputes the cached photometric scale if needed.
  21276. */
  21277. Light.prototype._computePhotometricScale = function () {
  21278. this._photometricScale = this._getPhotometricScale();
  21279. this.getScene().resetCachedMaterial();
  21280. };
  21281. /**
  21282. * Returns the Photometric Scale according to the light type and intensity mode.
  21283. */
  21284. Light.prototype._getPhotometricScale = function () {
  21285. var photometricScale = 0.0;
  21286. var lightTypeID = this.getTypeID();
  21287. //get photometric mode
  21288. var photometricMode = this.intensityMode;
  21289. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21290. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21291. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21292. }
  21293. else {
  21294. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21295. }
  21296. }
  21297. //compute photometric scale
  21298. switch (lightTypeID) {
  21299. case Light.LIGHTTYPEID_POINTLIGHT:
  21300. case Light.LIGHTTYPEID_SPOTLIGHT:
  21301. switch (photometricMode) {
  21302. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21303. photometricScale = 1.0 / (4.0 * Math.PI);
  21304. break;
  21305. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21306. photometricScale = 1.0;
  21307. break;
  21308. case Light.INTENSITYMODE_LUMINANCE:
  21309. photometricScale = this.radius * this.radius;
  21310. break;
  21311. }
  21312. break;
  21313. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21314. switch (photometricMode) {
  21315. case Light.INTENSITYMODE_ILLUMINANCE:
  21316. photometricScale = 1.0;
  21317. break;
  21318. case Light.INTENSITYMODE_LUMINANCE:
  21319. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21320. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21321. var apexAngleRadians = this.radius;
  21322. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21323. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21324. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21325. photometricScale = solidAngle;
  21326. break;
  21327. }
  21328. break;
  21329. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21330. // No fall off in hemisperic light.
  21331. photometricScale = 1.0;
  21332. break;
  21333. }
  21334. return photometricScale;
  21335. };
  21336. /**
  21337. * Reorder the light in the scene according to their defined priority.
  21338. * @ignore Internal Use Only
  21339. */
  21340. Light.prototype._reorderLightsInScene = function () {
  21341. var scene = this.getScene();
  21342. if (this._renderPriority != 0) {
  21343. scene.requireLightSorting = true;
  21344. }
  21345. this.getScene().sortLightsByPriority();
  21346. };
  21347. //lightmapMode Consts
  21348. Light._LIGHTMAP_DEFAULT = 0;
  21349. Light._LIGHTMAP_SPECULAR = 1;
  21350. Light._LIGHTMAP_SHADOWSONLY = 2;
  21351. // Intensity Mode Consts
  21352. Light._INTENSITYMODE_AUTOMATIC = 0;
  21353. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21354. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21355. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21356. Light._INTENSITYMODE_LUMINANCE = 4;
  21357. // Light types ids const.
  21358. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21359. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21360. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21361. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21362. __decorate([
  21363. BABYLON.serializeAsColor3()
  21364. ], Light.prototype, "diffuse", void 0);
  21365. __decorate([
  21366. BABYLON.serializeAsColor3()
  21367. ], Light.prototype, "specular", void 0);
  21368. __decorate([
  21369. BABYLON.serialize()
  21370. ], Light.prototype, "intensity", void 0);
  21371. __decorate([
  21372. BABYLON.serialize()
  21373. ], Light.prototype, "range", void 0);
  21374. __decorate([
  21375. BABYLON.serialize()
  21376. ], Light.prototype, "intensityMode", null);
  21377. __decorate([
  21378. BABYLON.serialize()
  21379. ], Light.prototype, "radius", null);
  21380. __decorate([
  21381. BABYLON.serialize()
  21382. ], Light.prototype, "_renderPriority", void 0);
  21383. __decorate([
  21384. BABYLON.expandToProperty("_reorderLightsInScene")
  21385. ], Light.prototype, "renderPriority", void 0);
  21386. __decorate([
  21387. BABYLON.serialize()
  21388. ], Light.prototype, "shadowEnabled", void 0);
  21389. __decorate([
  21390. BABYLON.serialize("excludeWithLayerMask")
  21391. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21392. __decorate([
  21393. BABYLON.serialize("includeOnlyWithLayerMask")
  21394. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21395. __decorate([
  21396. BABYLON.serialize("lightmapMode")
  21397. ], Light.prototype, "_lightmapMode", void 0);
  21398. return Light;
  21399. }(BABYLON.Node));
  21400. BABYLON.Light = Light;
  21401. })(BABYLON || (BABYLON = {}));
  21402. //# sourceMappingURL=babylon.light.js.map
  21403. "use strict";
  21404. var BABYLON;
  21405. (function (BABYLON) {
  21406. var Camera = /** @class */ (function (_super) {
  21407. __extends(Camera, _super);
  21408. function Camera(name, position, scene) {
  21409. var _this = _super.call(this, name, scene) || this;
  21410. /**
  21411. * The vector the camera should consider as up.
  21412. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21413. */
  21414. _this.upVector = BABYLON.Vector3.Up();
  21415. _this.orthoLeft = null;
  21416. _this.orthoRight = null;
  21417. _this.orthoBottom = null;
  21418. _this.orthoTop = null;
  21419. /**
  21420. * FOV is set in Radians. (default is 0.8)
  21421. */
  21422. _this.fov = 0.8;
  21423. _this.minZ = 1;
  21424. _this.maxZ = 10000.0;
  21425. _this.inertia = 0.9;
  21426. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21427. _this.isIntermediate = false;
  21428. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21429. /**
  21430. * Restricts the camera to viewing objects with the same layerMask.
  21431. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21432. */
  21433. _this.layerMask = 0x0FFFFFFF;
  21434. /**
  21435. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21436. */
  21437. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21438. // Camera rig members
  21439. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21440. _this._rigCameras = new Array();
  21441. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21442. _this._skipRendering = false;
  21443. _this.customRenderTargets = new Array();
  21444. // Observables
  21445. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21446. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21447. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21448. _this.onRestoreStateObservable = new BABYLON.Observable();
  21449. // Cache
  21450. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21451. _this._projectionMatrix = new BABYLON.Matrix();
  21452. _this._doNotComputeProjectionMatrix = false;
  21453. _this._postProcesses = new Array();
  21454. _this._transformMatrix = BABYLON.Matrix.Zero();
  21455. _this._activeMeshes = new BABYLON.SmartArray(256);
  21456. _this._globalPosition = BABYLON.Vector3.Zero();
  21457. _this._refreshFrustumPlanes = true;
  21458. _this.getScene().addCamera(_this);
  21459. if (!_this.getScene().activeCamera) {
  21460. _this.getScene().activeCamera = _this;
  21461. }
  21462. _this.position = position;
  21463. return _this;
  21464. }
  21465. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21466. get: function () {
  21467. return Camera._PERSPECTIVE_CAMERA;
  21468. },
  21469. enumerable: true,
  21470. configurable: true
  21471. });
  21472. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21473. get: function () {
  21474. return Camera._ORTHOGRAPHIC_CAMERA;
  21475. },
  21476. enumerable: true,
  21477. configurable: true
  21478. });
  21479. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21480. /**
  21481. * This is the default FOV mode for perspective cameras.
  21482. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21483. *
  21484. */
  21485. get: function () {
  21486. return Camera._FOVMODE_VERTICAL_FIXED;
  21487. },
  21488. enumerable: true,
  21489. configurable: true
  21490. });
  21491. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21492. /**
  21493. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21494. *
  21495. */
  21496. get: function () {
  21497. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21498. },
  21499. enumerable: true,
  21500. configurable: true
  21501. });
  21502. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21503. get: function () {
  21504. return Camera._RIG_MODE_NONE;
  21505. },
  21506. enumerable: true,
  21507. configurable: true
  21508. });
  21509. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21510. get: function () {
  21511. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21512. },
  21513. enumerable: true,
  21514. configurable: true
  21515. });
  21516. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21517. get: function () {
  21518. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21519. },
  21520. enumerable: true,
  21521. configurable: true
  21522. });
  21523. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21524. get: function () {
  21525. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21526. },
  21527. enumerable: true,
  21528. configurable: true
  21529. });
  21530. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21531. get: function () {
  21532. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21538. get: function () {
  21539. return Camera._RIG_MODE_VR;
  21540. },
  21541. enumerable: true,
  21542. configurable: true
  21543. });
  21544. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21545. get: function () {
  21546. return Camera._RIG_MODE_WEBVR;
  21547. },
  21548. enumerable: true,
  21549. configurable: true
  21550. });
  21551. /**
  21552. * Store current camera state (fov, position, etc..)
  21553. */
  21554. Camera.prototype.storeState = function () {
  21555. this._stateStored = true;
  21556. this._storedFov = this.fov;
  21557. return this;
  21558. };
  21559. /**
  21560. * Restores the camera state values if it has been stored. You must call storeState() first
  21561. */
  21562. Camera.prototype._restoreStateValues = function () {
  21563. if (!this._stateStored) {
  21564. return false;
  21565. }
  21566. this.fov = this._storedFov;
  21567. return true;
  21568. };
  21569. /**
  21570. * Restored camera state. You must call storeState() first
  21571. */
  21572. Camera.prototype.restoreState = function () {
  21573. if (this._restoreStateValues()) {
  21574. this.onRestoreStateObservable.notifyObservers(this);
  21575. return true;
  21576. }
  21577. return false;
  21578. };
  21579. Camera.prototype.getClassName = function () {
  21580. return "Camera";
  21581. };
  21582. /**
  21583. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21584. */
  21585. Camera.prototype.toString = function (fullDetails) {
  21586. var ret = "Name: " + this.name;
  21587. ret += ", type: " + this.getClassName();
  21588. if (this.animations) {
  21589. for (var i = 0; i < this.animations.length; i++) {
  21590. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21591. }
  21592. }
  21593. if (fullDetails) {
  21594. }
  21595. return ret;
  21596. };
  21597. Object.defineProperty(Camera.prototype, "globalPosition", {
  21598. get: function () {
  21599. return this._globalPosition;
  21600. },
  21601. enumerable: true,
  21602. configurable: true
  21603. });
  21604. Camera.prototype.getActiveMeshes = function () {
  21605. return this._activeMeshes;
  21606. };
  21607. Camera.prototype.isActiveMesh = function (mesh) {
  21608. return (this._activeMeshes.indexOf(mesh) !== -1);
  21609. };
  21610. /**
  21611. * Is this camera ready to be used/rendered
  21612. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21613. * @return true if the camera is ready
  21614. */
  21615. Camera.prototype.isReady = function (completeCheck) {
  21616. if (completeCheck === void 0) { completeCheck = false; }
  21617. if (completeCheck) {
  21618. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21619. var pp = _a[_i];
  21620. if (pp && !pp.isReady()) {
  21621. return false;
  21622. }
  21623. }
  21624. }
  21625. return _super.prototype.isReady.call(this, completeCheck);
  21626. };
  21627. //Cache
  21628. Camera.prototype._initCache = function () {
  21629. _super.prototype._initCache.call(this);
  21630. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21631. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21632. this._cache.mode = undefined;
  21633. this._cache.minZ = undefined;
  21634. this._cache.maxZ = undefined;
  21635. this._cache.fov = undefined;
  21636. this._cache.fovMode = undefined;
  21637. this._cache.aspectRatio = undefined;
  21638. this._cache.orthoLeft = undefined;
  21639. this._cache.orthoRight = undefined;
  21640. this._cache.orthoBottom = undefined;
  21641. this._cache.orthoTop = undefined;
  21642. this._cache.renderWidth = undefined;
  21643. this._cache.renderHeight = undefined;
  21644. };
  21645. Camera.prototype._updateCache = function (ignoreParentClass) {
  21646. if (!ignoreParentClass) {
  21647. _super.prototype._updateCache.call(this);
  21648. }
  21649. this._cache.position.copyFrom(this.position);
  21650. this._cache.upVector.copyFrom(this.upVector);
  21651. };
  21652. // Synchronized
  21653. Camera.prototype._isSynchronized = function () {
  21654. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21655. };
  21656. Camera.prototype._isSynchronizedViewMatrix = function () {
  21657. if (!_super.prototype._isSynchronized.call(this))
  21658. return false;
  21659. return this._cache.position.equals(this.position)
  21660. && this._cache.upVector.equals(this.upVector)
  21661. && this.isSynchronizedWithParent();
  21662. };
  21663. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21664. var check = this._cache.mode === this.mode
  21665. && this._cache.minZ === this.minZ
  21666. && this._cache.maxZ === this.maxZ;
  21667. if (!check) {
  21668. return false;
  21669. }
  21670. var engine = this.getEngine();
  21671. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21672. check = this._cache.fov === this.fov
  21673. && this._cache.fovMode === this.fovMode
  21674. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21675. }
  21676. else {
  21677. check = this._cache.orthoLeft === this.orthoLeft
  21678. && this._cache.orthoRight === this.orthoRight
  21679. && this._cache.orthoBottom === this.orthoBottom
  21680. && this._cache.orthoTop === this.orthoTop
  21681. && this._cache.renderWidth === engine.getRenderWidth()
  21682. && this._cache.renderHeight === engine.getRenderHeight();
  21683. }
  21684. return check;
  21685. };
  21686. // Controls
  21687. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21688. };
  21689. Camera.prototype.detachControl = function (element) {
  21690. };
  21691. Camera.prototype.update = function () {
  21692. this._checkInputs();
  21693. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21694. this._updateRigCameras();
  21695. }
  21696. };
  21697. Camera.prototype._checkInputs = function () {
  21698. this.onAfterCheckInputsObservable.notifyObservers(this);
  21699. };
  21700. Object.defineProperty(Camera.prototype, "rigCameras", {
  21701. get: function () {
  21702. return this._rigCameras;
  21703. },
  21704. enumerable: true,
  21705. configurable: true
  21706. });
  21707. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21708. get: function () {
  21709. return this._rigPostProcess;
  21710. },
  21711. enumerable: true,
  21712. configurable: true
  21713. });
  21714. /**
  21715. * Internal, gets the first post proces.
  21716. * @returns the first post process to be run on this camera.
  21717. */
  21718. Camera.prototype._getFirstPostProcess = function () {
  21719. for (var pp in this._postProcesses) {
  21720. if (this._postProcesses[pp] !== null) {
  21721. return this._postProcesses[pp];
  21722. }
  21723. }
  21724. return null;
  21725. };
  21726. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21727. // invalidate framebuffer
  21728. var firstPostProcess = this._getFirstPostProcess();
  21729. if (firstPostProcess) {
  21730. firstPostProcess.markTextureDirty();
  21731. }
  21732. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21733. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21734. var cam = this._rigCameras[i];
  21735. var rigPostProcess = cam._rigPostProcess;
  21736. // for VR rig, there does not have to be a post process
  21737. if (rigPostProcess) {
  21738. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21739. if (isPass) {
  21740. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21741. cam.isIntermediate = this._postProcesses.length === 0;
  21742. }
  21743. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21744. rigPostProcess.markTextureDirty();
  21745. }
  21746. else {
  21747. cam._postProcesses = this._postProcesses.slice(0);
  21748. }
  21749. }
  21750. };
  21751. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21752. if (insertAt === void 0) { insertAt = null; }
  21753. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21754. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21755. return 0;
  21756. }
  21757. if (insertAt == null || insertAt < 0) {
  21758. this._postProcesses.push(postProcess);
  21759. }
  21760. else if (this._postProcesses[insertAt] === null) {
  21761. this._postProcesses[insertAt] = postProcess;
  21762. }
  21763. else {
  21764. this._postProcesses.splice(insertAt, 0, postProcess);
  21765. }
  21766. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21767. return this._postProcesses.indexOf(postProcess);
  21768. };
  21769. Camera.prototype.detachPostProcess = function (postProcess) {
  21770. var idx = this._postProcesses.indexOf(postProcess);
  21771. if (idx !== -1) {
  21772. this._postProcesses[idx] = null;
  21773. }
  21774. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  21775. };
  21776. Camera.prototype.getWorldMatrix = function () {
  21777. if (!this._worldMatrix) {
  21778. this._worldMatrix = BABYLON.Matrix.Identity();
  21779. }
  21780. var viewMatrix = this.getViewMatrix();
  21781. viewMatrix.invertToRef(this._worldMatrix);
  21782. return this._worldMatrix;
  21783. };
  21784. Camera.prototype._getViewMatrix = function () {
  21785. return BABYLON.Matrix.Identity();
  21786. };
  21787. Camera.prototype.getViewMatrix = function (force) {
  21788. if (!force && this._isSynchronizedViewMatrix()) {
  21789. return this._computedViewMatrix;
  21790. }
  21791. this.updateCache();
  21792. this._computedViewMatrix = this._getViewMatrix();
  21793. this._currentRenderId = this.getScene().getRenderId();
  21794. this._childRenderId = this._currentRenderId;
  21795. this._refreshFrustumPlanes = true;
  21796. if (!this.parent || !this.parent.getWorldMatrix) {
  21797. this._globalPosition.copyFrom(this.position);
  21798. }
  21799. else {
  21800. if (!this._worldMatrix) {
  21801. this._worldMatrix = BABYLON.Matrix.Identity();
  21802. }
  21803. this._computedViewMatrix.invertToRef(this._worldMatrix);
  21804. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  21805. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  21806. this._computedViewMatrix.invert();
  21807. this._markSyncedWithParent();
  21808. }
  21809. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  21810. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  21811. }
  21812. this.onViewMatrixChangedObservable.notifyObservers(this);
  21813. return this._computedViewMatrix;
  21814. };
  21815. Camera.prototype.freezeProjectionMatrix = function (projection) {
  21816. this._doNotComputeProjectionMatrix = true;
  21817. if (projection !== undefined) {
  21818. this._projectionMatrix = projection;
  21819. }
  21820. };
  21821. ;
  21822. Camera.prototype.unfreezeProjectionMatrix = function () {
  21823. this._doNotComputeProjectionMatrix = false;
  21824. };
  21825. ;
  21826. Camera.prototype.getProjectionMatrix = function (force) {
  21827. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  21828. return this._projectionMatrix;
  21829. }
  21830. // Cache
  21831. this._cache.mode = this.mode;
  21832. this._cache.minZ = this.minZ;
  21833. this._cache.maxZ = this.maxZ;
  21834. // Matrix
  21835. this._refreshFrustumPlanes = true;
  21836. var engine = this.getEngine();
  21837. var scene = this.getScene();
  21838. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21839. this._cache.fov = this.fov;
  21840. this._cache.fovMode = this.fovMode;
  21841. this._cache.aspectRatio = engine.getAspectRatio(this);
  21842. if (this.minZ <= 0) {
  21843. this.minZ = 0.1;
  21844. }
  21845. if (scene.useRightHandedSystem) {
  21846. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21847. }
  21848. else {
  21849. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  21850. }
  21851. }
  21852. else {
  21853. var halfWidth = engine.getRenderWidth() / 2.0;
  21854. var halfHeight = engine.getRenderHeight() / 2.0;
  21855. if (scene.useRightHandedSystem) {
  21856. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21857. }
  21858. else {
  21859. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  21860. }
  21861. this._cache.orthoLeft = this.orthoLeft;
  21862. this._cache.orthoRight = this.orthoRight;
  21863. this._cache.orthoBottom = this.orthoBottom;
  21864. this._cache.orthoTop = this.orthoTop;
  21865. this._cache.renderWidth = engine.getRenderWidth();
  21866. this._cache.renderHeight = engine.getRenderHeight();
  21867. }
  21868. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  21869. return this._projectionMatrix;
  21870. };
  21871. Camera.prototype.getTranformationMatrix = function () {
  21872. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21873. return this._transformMatrix;
  21874. };
  21875. Camera.prototype.updateFrustumPlanes = function () {
  21876. if (!this._refreshFrustumPlanes) {
  21877. return;
  21878. }
  21879. this.getTranformationMatrix();
  21880. if (!this._frustumPlanes) {
  21881. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21882. }
  21883. else {
  21884. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21885. }
  21886. this._refreshFrustumPlanes = false;
  21887. };
  21888. Camera.prototype.isInFrustum = function (target) {
  21889. this.updateFrustumPlanes();
  21890. return target.isInFrustum(this._frustumPlanes);
  21891. };
  21892. Camera.prototype.isCompletelyInFrustum = function (target) {
  21893. this.updateFrustumPlanes();
  21894. return target.isCompletelyInFrustum(this._frustumPlanes);
  21895. };
  21896. Camera.prototype.getForwardRay = function (length, transform, origin) {
  21897. if (length === void 0) { length = 100; }
  21898. if (!transform) {
  21899. transform = this.getWorldMatrix();
  21900. }
  21901. if (!origin) {
  21902. origin = this.position;
  21903. }
  21904. var forward = new BABYLON.Vector3(0, 0, 1);
  21905. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  21906. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  21907. return new BABYLON.Ray(origin, direction, length);
  21908. };
  21909. /**
  21910. * Releases resources associated with this node.
  21911. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21912. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21913. */
  21914. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21915. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21916. // Observables
  21917. this.onViewMatrixChangedObservable.clear();
  21918. this.onProjectionMatrixChangedObservable.clear();
  21919. this.onAfterCheckInputsObservable.clear();
  21920. this.onRestoreStateObservable.clear();
  21921. // Inputs
  21922. if (this.inputs) {
  21923. this.inputs.clear();
  21924. }
  21925. // Animations
  21926. this.getScene().stopAnimation(this);
  21927. // Remove from scene
  21928. this.getScene().removeCamera(this);
  21929. while (this._rigCameras.length > 0) {
  21930. var camera = this._rigCameras.pop();
  21931. if (camera) {
  21932. camera.dispose();
  21933. }
  21934. }
  21935. // Postprocesses
  21936. if (this._rigPostProcess) {
  21937. this._rigPostProcess.dispose(this);
  21938. this._rigPostProcess = null;
  21939. this._postProcesses = [];
  21940. }
  21941. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21942. this._rigPostProcess = null;
  21943. this._postProcesses = [];
  21944. }
  21945. else {
  21946. var i = this._postProcesses.length;
  21947. while (--i >= 0) {
  21948. var postProcess = this._postProcesses[i];
  21949. if (postProcess) {
  21950. postProcess.dispose(this);
  21951. }
  21952. }
  21953. }
  21954. // Render targets
  21955. var i = this.customRenderTargets.length;
  21956. while (--i >= 0) {
  21957. this.customRenderTargets[i].dispose();
  21958. }
  21959. this.customRenderTargets = [];
  21960. // Active Meshes
  21961. this._activeMeshes.dispose();
  21962. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21963. };
  21964. Object.defineProperty(Camera.prototype, "leftCamera", {
  21965. // ---- Camera rigs section ----
  21966. get: function () {
  21967. if (this._rigCameras.length < 1) {
  21968. return null;
  21969. }
  21970. return this._rigCameras[0];
  21971. },
  21972. enumerable: true,
  21973. configurable: true
  21974. });
  21975. Object.defineProperty(Camera.prototype, "rightCamera", {
  21976. get: function () {
  21977. if (this._rigCameras.length < 2) {
  21978. return null;
  21979. }
  21980. return this._rigCameras[1];
  21981. },
  21982. enumerable: true,
  21983. configurable: true
  21984. });
  21985. Camera.prototype.getLeftTarget = function () {
  21986. if (this._rigCameras.length < 1) {
  21987. return null;
  21988. }
  21989. return this._rigCameras[0].getTarget();
  21990. };
  21991. Camera.prototype.getRightTarget = function () {
  21992. if (this._rigCameras.length < 2) {
  21993. return null;
  21994. }
  21995. return this._rigCameras[1].getTarget();
  21996. };
  21997. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  21998. if (this.cameraRigMode === mode) {
  21999. return;
  22000. }
  22001. while (this._rigCameras.length > 0) {
  22002. var camera = this._rigCameras.pop();
  22003. if (camera) {
  22004. camera.dispose();
  22005. }
  22006. }
  22007. this.cameraRigMode = mode;
  22008. this._cameraRigParams = {};
  22009. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22010. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22011. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22012. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22013. // create the rig cameras, unless none
  22014. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22015. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22016. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22017. if (leftCamera && rightCamera) {
  22018. this._rigCameras.push(leftCamera);
  22019. this._rigCameras.push(rightCamera);
  22020. }
  22021. }
  22022. switch (this.cameraRigMode) {
  22023. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22024. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22025. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22026. break;
  22027. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22028. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22029. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22030. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22031. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22032. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22033. break;
  22034. case Camera.RIG_MODE_VR:
  22035. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22036. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22037. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22038. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22039. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22040. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22041. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22042. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22043. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22044. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22045. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22046. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22047. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22048. if (metrics.compensateDistortion) {
  22049. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22050. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22051. }
  22052. break;
  22053. case Camera.RIG_MODE_WEBVR:
  22054. if (rigParams.vrDisplay) {
  22055. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22056. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22057. //Left eye
  22058. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22059. this._rigCameras[0].setCameraRigParameter("left", true);
  22060. //leaving this for future reference
  22061. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22062. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22063. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22064. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22065. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22066. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22067. this._rigCameras[0].parent = this;
  22068. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22069. //Right eye
  22070. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22071. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22072. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22073. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22074. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22075. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22076. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22077. this._rigCameras[1].parent = this;
  22078. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22079. if (Camera.UseAlternateWebVRRendering) {
  22080. this._rigCameras[1]._skipRendering = true;
  22081. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22082. }
  22083. }
  22084. break;
  22085. }
  22086. this._cascadePostProcessesToRigCams();
  22087. this.update();
  22088. };
  22089. Camera.prototype._getVRProjectionMatrix = function () {
  22090. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22091. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22092. return this._projectionMatrix;
  22093. };
  22094. Camera.prototype._updateCameraRotationMatrix = function () {
  22095. //Here for WebVR
  22096. };
  22097. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22098. //Here for WebVR
  22099. };
  22100. /**
  22101. * This function MUST be overwritten by the different WebVR cameras available.
  22102. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22103. */
  22104. Camera.prototype._getWebVRProjectionMatrix = function () {
  22105. return BABYLON.Matrix.Identity();
  22106. };
  22107. /**
  22108. * This function MUST be overwritten by the different WebVR cameras available.
  22109. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22110. */
  22111. Camera.prototype._getWebVRViewMatrix = function () {
  22112. return BABYLON.Matrix.Identity();
  22113. };
  22114. Camera.prototype.setCameraRigParameter = function (name, value) {
  22115. if (!this._cameraRigParams) {
  22116. this._cameraRigParams = {};
  22117. }
  22118. this._cameraRigParams[name] = value;
  22119. //provisionnally:
  22120. if (name === "interaxialDistance") {
  22121. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22122. }
  22123. };
  22124. /**
  22125. * needs to be overridden by children so sub has required properties to be copied
  22126. */
  22127. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22128. return null;
  22129. };
  22130. /**
  22131. * May need to be overridden by children
  22132. */
  22133. Camera.prototype._updateRigCameras = function () {
  22134. for (var i = 0; i < this._rigCameras.length; i++) {
  22135. this._rigCameras[i].minZ = this.minZ;
  22136. this._rigCameras[i].maxZ = this.maxZ;
  22137. this._rigCameras[i].fov = this.fov;
  22138. }
  22139. // only update viewport when ANAGLYPH
  22140. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22141. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22142. }
  22143. };
  22144. Camera.prototype._setupInputs = function () {
  22145. };
  22146. Camera.prototype.serialize = function () {
  22147. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22148. // Type
  22149. serializationObject.type = this.getClassName();
  22150. // Parent
  22151. if (this.parent) {
  22152. serializationObject.parentId = this.parent.id;
  22153. }
  22154. if (this.inputs) {
  22155. this.inputs.serialize(serializationObject);
  22156. }
  22157. // Animations
  22158. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22159. serializationObject.ranges = this.serializeAnimationRanges();
  22160. return serializationObject;
  22161. };
  22162. Camera.prototype.clone = function (name) {
  22163. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22164. };
  22165. Camera.prototype.getDirection = function (localAxis) {
  22166. var result = BABYLON.Vector3.Zero();
  22167. this.getDirectionToRef(localAxis, result);
  22168. return result;
  22169. };
  22170. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22171. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22172. };
  22173. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22174. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22175. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22176. switch (type) {
  22177. case "ArcRotateCamera":
  22178. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22179. case "DeviceOrientationCamera":
  22180. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22181. case "FollowCamera":
  22182. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22183. case "ArcFollowCamera":
  22184. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22185. case "GamepadCamera":
  22186. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22187. case "TouchCamera":
  22188. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22189. case "VirtualJoysticksCamera":
  22190. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22191. case "WebVRFreeCamera":
  22192. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22193. case "WebVRGamepadCamera":
  22194. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22195. case "VRDeviceOrientationFreeCamera":
  22196. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22197. case "VRDeviceOrientationGamepadCamera":
  22198. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22199. case "AnaglyphArcRotateCamera":
  22200. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22201. case "AnaglyphFreeCamera":
  22202. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22203. case "AnaglyphGamepadCamera":
  22204. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22205. case "AnaglyphUniversalCamera":
  22206. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22207. case "StereoscopicArcRotateCamera":
  22208. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22209. case "StereoscopicFreeCamera":
  22210. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22211. case "StereoscopicGamepadCamera":
  22212. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22213. case "StereoscopicUniversalCamera":
  22214. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22215. case "FreeCamera":// Forcing Universal here
  22216. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22217. default:// Universal Camera is the default value
  22218. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22219. }
  22220. };
  22221. Camera.prototype.computeWorldMatrix = function () {
  22222. return this.getWorldMatrix();
  22223. };
  22224. Camera.Parse = function (parsedCamera, scene) {
  22225. var type = parsedCamera.type;
  22226. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22227. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22228. // Parent
  22229. if (parsedCamera.parentId) {
  22230. camera._waitingParentId = parsedCamera.parentId;
  22231. }
  22232. //If camera has an input manager, let it parse inputs settings
  22233. if (camera.inputs) {
  22234. camera.inputs.parse(parsedCamera);
  22235. camera._setupInputs();
  22236. }
  22237. if (camera.setPosition) {
  22238. camera.position.copyFromFloats(0, 0, 0);
  22239. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22240. }
  22241. // Target
  22242. if (parsedCamera.target) {
  22243. if (camera.setTarget) {
  22244. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22245. }
  22246. }
  22247. // Apply 3d rig, when found
  22248. if (parsedCamera.cameraRigMode) {
  22249. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22250. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22251. }
  22252. // Animations
  22253. if (parsedCamera.animations) {
  22254. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22255. var parsedAnimation = parsedCamera.animations[animationIndex];
  22256. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22257. }
  22258. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22259. }
  22260. if (parsedCamera.autoAnimate) {
  22261. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22262. }
  22263. return camera;
  22264. };
  22265. // Statics
  22266. Camera._PERSPECTIVE_CAMERA = 0;
  22267. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22268. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22269. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22270. Camera._RIG_MODE_NONE = 0;
  22271. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22272. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22273. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22274. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22275. Camera._RIG_MODE_VR = 20;
  22276. Camera._RIG_MODE_WEBVR = 21;
  22277. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22278. Camera.UseAlternateWebVRRendering = false;
  22279. __decorate([
  22280. BABYLON.serializeAsVector3()
  22281. ], Camera.prototype, "position", void 0);
  22282. __decorate([
  22283. BABYLON.serializeAsVector3()
  22284. ], Camera.prototype, "upVector", void 0);
  22285. __decorate([
  22286. BABYLON.serialize()
  22287. ], Camera.prototype, "orthoLeft", void 0);
  22288. __decorate([
  22289. BABYLON.serialize()
  22290. ], Camera.prototype, "orthoRight", void 0);
  22291. __decorate([
  22292. BABYLON.serialize()
  22293. ], Camera.prototype, "orthoBottom", void 0);
  22294. __decorate([
  22295. BABYLON.serialize()
  22296. ], Camera.prototype, "orthoTop", void 0);
  22297. __decorate([
  22298. BABYLON.serialize()
  22299. ], Camera.prototype, "fov", void 0);
  22300. __decorate([
  22301. BABYLON.serialize()
  22302. ], Camera.prototype, "minZ", void 0);
  22303. __decorate([
  22304. BABYLON.serialize()
  22305. ], Camera.prototype, "maxZ", void 0);
  22306. __decorate([
  22307. BABYLON.serialize()
  22308. ], Camera.prototype, "inertia", void 0);
  22309. __decorate([
  22310. BABYLON.serialize()
  22311. ], Camera.prototype, "mode", void 0);
  22312. __decorate([
  22313. BABYLON.serialize()
  22314. ], Camera.prototype, "layerMask", void 0);
  22315. __decorate([
  22316. BABYLON.serialize()
  22317. ], Camera.prototype, "fovMode", void 0);
  22318. __decorate([
  22319. BABYLON.serialize()
  22320. ], Camera.prototype, "cameraRigMode", void 0);
  22321. __decorate([
  22322. BABYLON.serialize()
  22323. ], Camera.prototype, "interaxialDistance", void 0);
  22324. __decorate([
  22325. BABYLON.serialize()
  22326. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22327. return Camera;
  22328. }(BABYLON.Node));
  22329. BABYLON.Camera = Camera;
  22330. })(BABYLON || (BABYLON = {}));
  22331. //# sourceMappingURL=babylon.camera.js.map
  22332. "use strict";
  22333. var BABYLON;
  22334. (function (BABYLON) {
  22335. var RenderingManager = /** @class */ (function () {
  22336. function RenderingManager(scene) {
  22337. this._renderingGroups = new Array();
  22338. this._autoClearDepthStencil = {};
  22339. this._customOpaqueSortCompareFn = {};
  22340. this._customAlphaTestSortCompareFn = {};
  22341. this._customTransparentSortCompareFn = {};
  22342. this._renderinGroupInfo = null;
  22343. this._scene = scene;
  22344. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22345. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22346. }
  22347. }
  22348. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22349. if (depth === void 0) { depth = true; }
  22350. if (stencil === void 0) { stencil = true; }
  22351. if (this._depthStencilBufferAlreadyCleaned) {
  22352. return;
  22353. }
  22354. this._scene.getEngine().clear(null, false, depth, stencil);
  22355. this._depthStencilBufferAlreadyCleaned = true;
  22356. };
  22357. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22358. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22359. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22360. var info = null;
  22361. if (observable) {
  22362. if (!this._renderinGroupInfo) {
  22363. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22364. }
  22365. info = this._renderinGroupInfo;
  22366. info.scene = this._scene;
  22367. info.camera = this._scene.activeCamera;
  22368. }
  22369. // Dispatch sprites
  22370. if (renderSprites) {
  22371. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22372. var manager = this._scene.spriteManagers[index];
  22373. this.dispatchSprites(manager);
  22374. }
  22375. }
  22376. // Render
  22377. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22378. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22379. var renderingGroup = this._renderingGroups[index];
  22380. if (!renderingGroup && !observable)
  22381. continue;
  22382. var renderingGroupMask = 0;
  22383. // Fire PRECLEAR stage
  22384. if (observable && info) {
  22385. renderingGroupMask = Math.pow(2, index);
  22386. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22387. info.renderingGroupId = index;
  22388. observable.notifyObservers(info, renderingGroupMask);
  22389. }
  22390. // Clear depth/stencil if needed
  22391. if (RenderingManager.AUTOCLEAR) {
  22392. var autoClear = this._autoClearDepthStencil[index];
  22393. if (autoClear && autoClear.autoClear) {
  22394. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22395. }
  22396. }
  22397. if (observable && info) {
  22398. // Fire PREOPAQUE stage
  22399. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22400. observable.notifyObservers(info, renderingGroupMask);
  22401. // Fire PRETRANSPARENT stage
  22402. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22403. observable.notifyObservers(info, renderingGroupMask);
  22404. }
  22405. if (renderingGroup)
  22406. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22407. // Fire POSTTRANSPARENT stage
  22408. if (observable && info) {
  22409. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22410. observable.notifyObservers(info, renderingGroupMask);
  22411. }
  22412. }
  22413. };
  22414. RenderingManager.prototype.reset = function () {
  22415. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22416. var renderingGroup = this._renderingGroups[index];
  22417. if (renderingGroup) {
  22418. renderingGroup.prepare();
  22419. }
  22420. }
  22421. };
  22422. RenderingManager.prototype.dispose = function () {
  22423. this.freeRenderingGroups();
  22424. this._renderingGroups.length = 0;
  22425. };
  22426. /**
  22427. * Clear the info related to rendering groups preventing retention points during dispose.
  22428. */
  22429. RenderingManager.prototype.freeRenderingGroups = function () {
  22430. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22431. var renderingGroup = this._renderingGroups[index];
  22432. if (renderingGroup) {
  22433. renderingGroup.dispose();
  22434. }
  22435. }
  22436. };
  22437. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22438. if (this._renderingGroups[renderingGroupId] === undefined) {
  22439. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22440. }
  22441. };
  22442. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22443. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22444. this._prepareRenderingGroup(renderingGroupId);
  22445. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22446. };
  22447. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22448. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22449. this._prepareRenderingGroup(renderingGroupId);
  22450. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22451. };
  22452. /**
  22453. * @param subMesh The submesh to dispatch
  22454. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22455. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22456. */
  22457. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22458. if (mesh === undefined) {
  22459. mesh = subMesh.getMesh();
  22460. }
  22461. var renderingGroupId = mesh.renderingGroupId || 0;
  22462. this._prepareRenderingGroup(renderingGroupId);
  22463. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22464. };
  22465. /**
  22466. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22467. * This allowed control for front to back rendering or reversly depending of the special needs.
  22468. *
  22469. * @param renderingGroupId The rendering group id corresponding to its index
  22470. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22471. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22472. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22473. */
  22474. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22475. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22476. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22477. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22478. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22479. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22480. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22481. if (this._renderingGroups[renderingGroupId]) {
  22482. var group = this._renderingGroups[renderingGroupId];
  22483. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22484. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22485. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22486. }
  22487. };
  22488. /**
  22489. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22490. *
  22491. * @param renderingGroupId The rendering group id corresponding to its index
  22492. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22493. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22494. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22495. */
  22496. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22497. if (depth === void 0) { depth = true; }
  22498. if (stencil === void 0) { stencil = true; }
  22499. this._autoClearDepthStencil[renderingGroupId] = {
  22500. autoClear: autoClearDepthStencil,
  22501. depth: depth,
  22502. stencil: stencil
  22503. };
  22504. };
  22505. /**
  22506. * The max id used for rendering groups (not included)
  22507. */
  22508. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22509. /**
  22510. * The min id used for rendering groups (included)
  22511. */
  22512. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22513. /**
  22514. * Used to globally prevent autoclearing scenes.
  22515. */
  22516. RenderingManager.AUTOCLEAR = true;
  22517. return RenderingManager;
  22518. }());
  22519. BABYLON.RenderingManager = RenderingManager;
  22520. })(BABYLON || (BABYLON = {}));
  22521. //# sourceMappingURL=babylon.renderingManager.js.map
  22522. "use strict";
  22523. var BABYLON;
  22524. (function (BABYLON) {
  22525. var RenderingGroup = /** @class */ (function () {
  22526. /**
  22527. * Creates a new rendering group.
  22528. * @param index The rendering group index
  22529. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22530. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22531. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22532. */
  22533. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22534. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22535. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22536. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22537. this.index = index;
  22538. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22539. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22540. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22541. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22542. this._particleSystems = new BABYLON.SmartArray(256);
  22543. this._spriteManagers = new BABYLON.SmartArray(256);
  22544. this._edgesRenderers = new BABYLON.SmartArray(16);
  22545. this._scene = scene;
  22546. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22547. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22548. this.transparentSortCompareFn = transparentSortCompareFn;
  22549. }
  22550. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22551. /**
  22552. * Set the opaque sort comparison function.
  22553. * If null the sub meshes will be render in the order they were created
  22554. */
  22555. set: function (value) {
  22556. this._opaqueSortCompareFn = value;
  22557. if (value) {
  22558. this._renderOpaque = this.renderOpaqueSorted;
  22559. }
  22560. else {
  22561. this._renderOpaque = RenderingGroup.renderUnsorted;
  22562. }
  22563. },
  22564. enumerable: true,
  22565. configurable: true
  22566. });
  22567. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22568. /**
  22569. * Set the alpha test sort comparison function.
  22570. * If null the sub meshes will be render in the order they were created
  22571. */
  22572. set: function (value) {
  22573. this._alphaTestSortCompareFn = value;
  22574. if (value) {
  22575. this._renderAlphaTest = this.renderAlphaTestSorted;
  22576. }
  22577. else {
  22578. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22579. }
  22580. },
  22581. enumerable: true,
  22582. configurable: true
  22583. });
  22584. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22585. /**
  22586. * Set the transparent sort comparison function.
  22587. * If null the sub meshes will be render in the order they were created
  22588. */
  22589. set: function (value) {
  22590. if (value) {
  22591. this._transparentSortCompareFn = value;
  22592. }
  22593. else {
  22594. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22595. }
  22596. this._renderTransparent = this.renderTransparentSorted;
  22597. },
  22598. enumerable: true,
  22599. configurable: true
  22600. });
  22601. /**
  22602. * Render all the sub meshes contained in the group.
  22603. * @param customRenderFunction Used to override the default render behaviour of the group.
  22604. * @returns true if rendered some submeshes.
  22605. */
  22606. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22607. if (customRenderFunction) {
  22608. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22609. return;
  22610. }
  22611. var engine = this._scene.getEngine();
  22612. // Depth only
  22613. if (this._depthOnlySubMeshes.length !== 0) {
  22614. engine.setColorWrite(false);
  22615. this._renderAlphaTest(this._depthOnlySubMeshes);
  22616. engine.setColorWrite(true);
  22617. }
  22618. // Opaque
  22619. if (this._opaqueSubMeshes.length !== 0) {
  22620. this._renderOpaque(this._opaqueSubMeshes);
  22621. }
  22622. // Alpha test
  22623. if (this._alphaTestSubMeshes.length !== 0) {
  22624. this._renderAlphaTest(this._alphaTestSubMeshes);
  22625. }
  22626. var stencilState = engine.getStencilBuffer();
  22627. engine.setStencilBuffer(false);
  22628. // Sprites
  22629. if (renderSprites) {
  22630. this._renderSprites();
  22631. }
  22632. // Particles
  22633. if (renderParticles) {
  22634. this._renderParticles(activeMeshes);
  22635. }
  22636. if (this.onBeforeTransparentRendering) {
  22637. this.onBeforeTransparentRendering();
  22638. }
  22639. // Transparent
  22640. if (this._transparentSubMeshes.length !== 0) {
  22641. this._renderTransparent(this._transparentSubMeshes);
  22642. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22643. }
  22644. // Set back stencil to false in case it changes before the edge renderer.
  22645. engine.setStencilBuffer(false);
  22646. // Edges
  22647. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22648. this._edgesRenderers.data[edgesRendererIndex].render();
  22649. }
  22650. // Restore Stencil state.
  22651. engine.setStencilBuffer(stencilState);
  22652. };
  22653. /**
  22654. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22655. * @param subMeshes The submeshes to render
  22656. */
  22657. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22658. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22659. };
  22660. /**
  22661. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22662. * @param subMeshes The submeshes to render
  22663. */
  22664. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22665. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22666. };
  22667. /**
  22668. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22669. * @param subMeshes The submeshes to render
  22670. */
  22671. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22672. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22673. };
  22674. /**
  22675. * Renders the submeshes in a specified order.
  22676. * @param subMeshes The submeshes to sort before render
  22677. * @param sortCompareFn The comparison function use to sort
  22678. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22679. * @param transparent Specifies to activate blending if true
  22680. */
  22681. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22682. var subIndex = 0;
  22683. var subMesh;
  22684. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22685. for (; subIndex < subMeshes.length; subIndex++) {
  22686. subMesh = subMeshes.data[subIndex];
  22687. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22688. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22689. }
  22690. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22691. if (sortCompareFn) {
  22692. sortedArray.sort(sortCompareFn);
  22693. }
  22694. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22695. subMesh = sortedArray[subIndex];
  22696. if (transparent) {
  22697. var material = subMesh.getMaterial();
  22698. if (material && material.needDepthPrePass) {
  22699. var engine = material.getScene().getEngine();
  22700. engine.setColorWrite(false);
  22701. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22702. subMesh.render(false);
  22703. engine.setColorWrite(true);
  22704. }
  22705. }
  22706. subMesh.render(transparent);
  22707. }
  22708. };
  22709. /**
  22710. * Renders the submeshes in the order they were dispatched (no sort applied).
  22711. * @param subMeshes The submeshes to render
  22712. */
  22713. RenderingGroup.renderUnsorted = function (subMeshes) {
  22714. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22715. var submesh = subMeshes.data[subIndex];
  22716. submesh.render(false);
  22717. }
  22718. };
  22719. /**
  22720. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22721. * are rendered back to front if in the same alpha index.
  22722. *
  22723. * @param a The first submesh
  22724. * @param b The second submesh
  22725. * @returns The result of the comparison
  22726. */
  22727. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22728. // Alpha index first
  22729. if (a._alphaIndex > b._alphaIndex) {
  22730. return 1;
  22731. }
  22732. if (a._alphaIndex < b._alphaIndex) {
  22733. return -1;
  22734. }
  22735. // Then distance to camera
  22736. return RenderingGroup.backToFrontSortCompare(a, b);
  22737. };
  22738. /**
  22739. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22740. * are rendered back to front.
  22741. *
  22742. * @param a The first submesh
  22743. * @param b The second submesh
  22744. * @returns The result of the comparison
  22745. */
  22746. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22747. // Then distance to camera
  22748. if (a._distanceToCamera < b._distanceToCamera) {
  22749. return 1;
  22750. }
  22751. if (a._distanceToCamera > b._distanceToCamera) {
  22752. return -1;
  22753. }
  22754. return 0;
  22755. };
  22756. /**
  22757. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22758. * are rendered front to back (prevent overdraw).
  22759. *
  22760. * @param a The first submesh
  22761. * @param b The second submesh
  22762. * @returns The result of the comparison
  22763. */
  22764. RenderingGroup.frontToBackSortCompare = function (a, b) {
  22765. // Then distance to camera
  22766. if (a._distanceToCamera < b._distanceToCamera) {
  22767. return -1;
  22768. }
  22769. if (a._distanceToCamera > b._distanceToCamera) {
  22770. return 1;
  22771. }
  22772. return 0;
  22773. };
  22774. /**
  22775. * Resets the different lists of submeshes to prepare a new frame.
  22776. */
  22777. RenderingGroup.prototype.prepare = function () {
  22778. this._opaqueSubMeshes.reset();
  22779. this._transparentSubMeshes.reset();
  22780. this._alphaTestSubMeshes.reset();
  22781. this._depthOnlySubMeshes.reset();
  22782. this._particleSystems.reset();
  22783. this._spriteManagers.reset();
  22784. this._edgesRenderers.reset();
  22785. };
  22786. RenderingGroup.prototype.dispose = function () {
  22787. this._opaqueSubMeshes.dispose();
  22788. this._transparentSubMeshes.dispose();
  22789. this._alphaTestSubMeshes.dispose();
  22790. this._depthOnlySubMeshes.dispose();
  22791. this._particleSystems.dispose();
  22792. this._spriteManagers.dispose();
  22793. this._edgesRenderers.dispose();
  22794. };
  22795. /**
  22796. * Inserts the submesh in its correct queue depending on its material.
  22797. * @param subMesh The submesh to dispatch
  22798. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22799. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22800. */
  22801. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  22802. // Get mesh and materials if not provided
  22803. if (mesh === undefined) {
  22804. mesh = subMesh.getMesh();
  22805. }
  22806. if (material === undefined) {
  22807. material = subMesh.getMaterial();
  22808. }
  22809. if (material === null || material === undefined) {
  22810. return;
  22811. }
  22812. if (material.needAlphaBlendingForMesh(mesh)) {
  22813. this._transparentSubMeshes.push(subMesh);
  22814. }
  22815. else if (material.needAlphaTesting()) {
  22816. if (material.needDepthPrePass) {
  22817. this._depthOnlySubMeshes.push(subMesh);
  22818. }
  22819. this._alphaTestSubMeshes.push(subMesh);
  22820. }
  22821. else {
  22822. if (material.needDepthPrePass) {
  22823. this._depthOnlySubMeshes.push(subMesh);
  22824. }
  22825. this._opaqueSubMeshes.push(subMesh); // Opaque
  22826. }
  22827. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  22828. this._edgesRenderers.push(mesh._edgesRenderer);
  22829. }
  22830. };
  22831. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  22832. this._spriteManagers.push(spriteManager);
  22833. };
  22834. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  22835. this._particleSystems.push(particleSystem);
  22836. };
  22837. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  22838. if (this._particleSystems.length === 0) {
  22839. return;
  22840. }
  22841. // Particles
  22842. var activeCamera = this._scene.activeCamera;
  22843. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  22844. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  22845. var particleSystem = this._particleSystems.data[particleIndex];
  22846. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  22847. continue;
  22848. }
  22849. var emitter = particleSystem.emitter;
  22850. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  22851. this._scene._activeParticles.addCount(particleSystem.render(), false);
  22852. }
  22853. }
  22854. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  22855. };
  22856. RenderingGroup.prototype._renderSprites = function () {
  22857. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  22858. return;
  22859. }
  22860. // Sprites
  22861. var activeCamera = this._scene.activeCamera;
  22862. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  22863. for (var id = 0; id < this._spriteManagers.length; id++) {
  22864. var spriteManager = this._spriteManagers.data[id];
  22865. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  22866. spriteManager.render();
  22867. }
  22868. }
  22869. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  22870. };
  22871. return RenderingGroup;
  22872. }());
  22873. BABYLON.RenderingGroup = RenderingGroup;
  22874. })(BABYLON || (BABYLON = {}));
  22875. //# sourceMappingURL=babylon.renderingGroup.js.map
  22876. "use strict";
  22877. var BABYLON;
  22878. (function (BABYLON) {
  22879. /** @ignore */
  22880. var ClickInfo = /** @class */ (function () {
  22881. function ClickInfo() {
  22882. this._singleClick = false;
  22883. this._doubleClick = false;
  22884. this._hasSwiped = false;
  22885. this._ignore = false;
  22886. }
  22887. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  22888. get: function () {
  22889. return this._singleClick;
  22890. },
  22891. set: function (b) {
  22892. this._singleClick = b;
  22893. },
  22894. enumerable: true,
  22895. configurable: true
  22896. });
  22897. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  22898. get: function () {
  22899. return this._doubleClick;
  22900. },
  22901. set: function (b) {
  22902. this._doubleClick = b;
  22903. },
  22904. enumerable: true,
  22905. configurable: true
  22906. });
  22907. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  22908. get: function () {
  22909. return this._hasSwiped;
  22910. },
  22911. set: function (b) {
  22912. this._hasSwiped = b;
  22913. },
  22914. enumerable: true,
  22915. configurable: true
  22916. });
  22917. Object.defineProperty(ClickInfo.prototype, "ignore", {
  22918. get: function () {
  22919. return this._ignore;
  22920. },
  22921. set: function (b) {
  22922. this._ignore = b;
  22923. },
  22924. enumerable: true,
  22925. configurable: true
  22926. });
  22927. return ClickInfo;
  22928. }());
  22929. /**
  22930. * This class is used by the onRenderingGroupObservable
  22931. */
  22932. var RenderingGroupInfo = /** @class */ (function () {
  22933. function RenderingGroupInfo() {
  22934. }
  22935. /**
  22936. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  22937. * This stage will be fired no matter what
  22938. */
  22939. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  22940. /**
  22941. * Called before opaque object are rendered.
  22942. * This stage will be fired only if there's 3D Opaque content to render
  22943. */
  22944. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  22945. /**
  22946. * Called after the opaque objects are rendered and before the transparent ones
  22947. * This stage will be fired only if there's 3D transparent content to render
  22948. */
  22949. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  22950. /**
  22951. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  22952. * This stage will be fired no matter what
  22953. */
  22954. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  22955. return RenderingGroupInfo;
  22956. }());
  22957. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  22958. /**
  22959. * Represents a scene to be rendered by the engine.
  22960. * @see http://doc.babylonjs.com/features/scene
  22961. */
  22962. var Scene = /** @class */ (function () {
  22963. /**
  22964. * Creates a new Scene
  22965. * @param engine defines the engine to use to render this scene
  22966. */
  22967. function Scene(engine) {
  22968. // Members
  22969. /**
  22970. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  22971. */
  22972. this.autoClear = true;
  22973. /**
  22974. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  22975. */
  22976. this.autoClearDepthAndStencil = true;
  22977. /**
  22978. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  22979. */
  22980. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  22981. /**
  22982. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  22983. */
  22984. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22985. this._forceWireframe = false;
  22986. this._forcePointsCloud = false;
  22987. /**
  22988. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  22989. */
  22990. this.forceShowBoundingBoxes = false;
  22991. /**
  22992. * Gets or sets a boolean indicating if animations are enabled
  22993. */
  22994. this.animationsEnabled = true;
  22995. /**
  22996. * Gets or sets a boolean indicating if a constant deltatime has to be used
  22997. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  22998. */
  22999. this.useConstantAnimationDeltaTime = false;
  23000. /**
  23001. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23002. * Please note that it requires to run a ray cast through the scene on every frame
  23003. */
  23004. this.constantlyUpdateMeshUnderPointer = false;
  23005. /**
  23006. * Defines the HTML cursor to use when hovering over interactive elements
  23007. */
  23008. this.hoverCursor = "pointer";
  23009. /**
  23010. * Defines the HTML default cursor to use (empty by default)
  23011. */
  23012. this.defaultCursor = "";
  23013. /**
  23014. * This is used to call preventDefault() on pointer down
  23015. * in order to block unwanted artifacts like system double clicks
  23016. */
  23017. this.preventDefaultOnPointerDown = true;
  23018. // Metadata
  23019. /**
  23020. * Gets or sets user defined metadata
  23021. */
  23022. this.metadata = null;
  23023. /**
  23024. * Use this array to add regular expressions used to disable offline support for specific urls
  23025. */
  23026. this.disableOfflineSupportExceptionRules = new Array();
  23027. /**
  23028. * An event triggered when the scene is disposed.
  23029. */
  23030. this.onDisposeObservable = new BABYLON.Observable();
  23031. this._onDisposeObserver = null;
  23032. /**
  23033. * An event triggered before rendering the scene (right after animations and physics)
  23034. */
  23035. this.onBeforeRenderObservable = new BABYLON.Observable();
  23036. this._onBeforeRenderObserver = null;
  23037. /**
  23038. * An event triggered after rendering the scene
  23039. */
  23040. this.onAfterRenderObservable = new BABYLON.Observable();
  23041. this._onAfterRenderObserver = null;
  23042. /**
  23043. * An event triggered before animating the scene
  23044. */
  23045. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23046. /**
  23047. * An event triggered after animations processing
  23048. */
  23049. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23050. /**
  23051. * An event triggered before draw calls are ready to be sent
  23052. */
  23053. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23054. /**
  23055. * An event triggered after draw calls have been sent
  23056. */
  23057. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23058. /**
  23059. * An event triggered when physic simulation is about to be run
  23060. */
  23061. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23062. /**
  23063. * An event triggered when physic simulation has been done
  23064. */
  23065. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23066. /**
  23067. * An event triggered when the scene is ready
  23068. */
  23069. this.onReadyObservable = new BABYLON.Observable();
  23070. /**
  23071. * An event triggered before rendering a camera
  23072. */
  23073. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23074. this._onBeforeCameraRenderObserver = null;
  23075. /**
  23076. * An event triggered after rendering a camera
  23077. */
  23078. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23079. this._onAfterCameraRenderObserver = null;
  23080. /**
  23081. * An event triggered when active meshes evaluation is about to start
  23082. */
  23083. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23084. /**
  23085. * An event triggered when active meshes evaluation is done
  23086. */
  23087. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23088. /**
  23089. * An event triggered when particles rendering is about to start
  23090. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23091. */
  23092. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23093. /**
  23094. * An event triggered when particles rendering is done
  23095. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23096. */
  23097. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23098. /**
  23099. * An event triggered when sprites rendering is about to start
  23100. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23101. */
  23102. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23103. /**
  23104. * An event triggered when sprites rendering is done
  23105. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23106. */
  23107. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23108. /**
  23109. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23110. */
  23111. this.onDataLoadedObservable = new BABYLON.Observable();
  23112. /**
  23113. * An event triggered when a camera is created
  23114. */
  23115. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23116. /**
  23117. * An event triggered when a camera is removed
  23118. */
  23119. this.onCameraRemovedObservable = new BABYLON.Observable();
  23120. /**
  23121. * An event triggered when a light is created
  23122. */
  23123. this.onNewLightAddedObservable = new BABYLON.Observable();
  23124. /**
  23125. * An event triggered when a light is removed
  23126. */
  23127. this.onLightRemovedObservable = new BABYLON.Observable();
  23128. /**
  23129. * An event triggered when a geometry is created
  23130. */
  23131. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23132. /**
  23133. * An event triggered when a geometry is removed
  23134. */
  23135. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23136. /**
  23137. * An event triggered when a transform node is created
  23138. */
  23139. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23140. /**
  23141. * An event triggered when a transform node is removed
  23142. */
  23143. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23144. /**
  23145. * An event triggered when a mesh is created
  23146. */
  23147. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23148. /**
  23149. * An event triggered when a mesh is removed
  23150. */
  23151. this.onMeshRemovedObservable = new BABYLON.Observable();
  23152. /**
  23153. * An event triggered when render targets are about to be rendered
  23154. * Can happen multiple times per frame.
  23155. */
  23156. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23157. /**
  23158. * An event triggered when render targets were rendered.
  23159. * Can happen multiple times per frame.
  23160. */
  23161. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23162. /**
  23163. * An event triggered before calculating deterministic simulation step
  23164. */
  23165. this.onBeforeStepObservable = new BABYLON.Observable();
  23166. /**
  23167. * An event triggered after calculating deterministic simulation step
  23168. */
  23169. this.onAfterStepObservable = new BABYLON.Observable();
  23170. /**
  23171. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23172. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23173. * 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)
  23174. */
  23175. this.onRenderingGroupObservable = new BABYLON.Observable();
  23176. // Animations
  23177. /**
  23178. * Gets a list of Animations associated with the scene
  23179. */
  23180. this.animations = [];
  23181. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23182. /**
  23183. * 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).
  23184. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23185. */
  23186. this.onPrePointerObservable = new BABYLON.Observable();
  23187. /**
  23188. * Observable event triggered each time an input event is received from the rendering canvas
  23189. */
  23190. this.onPointerObservable = new BABYLON.Observable();
  23191. this._meshPickProceed = false;
  23192. this._currentPickResult = null;
  23193. this._previousPickResult = null;
  23194. this._totalPointersPressed = 0;
  23195. this._doubleClickOccured = false;
  23196. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23197. this.cameraToUseForPointers = null;
  23198. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23199. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23200. this._startingPointerTime = 0;
  23201. this._previousStartingPointerTime = 0;
  23202. // Deterministic lockstep
  23203. this._timeAccumulator = 0;
  23204. this._currentStepId = 0;
  23205. this._currentInternalStep = 0;
  23206. // Keyboard
  23207. /**
  23208. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23209. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23210. */
  23211. this.onPreKeyboardObservable = new BABYLON.Observable();
  23212. /**
  23213. * Observable event triggered each time an keyboard event is received from the hosting window
  23214. */
  23215. this.onKeyboardObservable = new BABYLON.Observable();
  23216. // Coordinates system
  23217. this._useRightHandedSystem = false;
  23218. // Fog
  23219. this._fogEnabled = true;
  23220. this._fogMode = Scene.FOGMODE_NONE;
  23221. /**
  23222. * Gets or sets the fog color to use
  23223. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23224. */
  23225. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23226. /**
  23227. * Gets or sets the fog density to use
  23228. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23229. */
  23230. this.fogDensity = 0.1;
  23231. /**
  23232. * Gets or sets the fog start distance to use
  23233. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23234. */
  23235. this.fogStart = 0;
  23236. /**
  23237. * Gets or sets the fog end distance to use
  23238. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23239. */
  23240. this.fogEnd = 1000.0;
  23241. // Lights
  23242. this._shadowsEnabled = true;
  23243. this._lightsEnabled = true;
  23244. /**
  23245. * All of the lights added to this scene
  23246. * @see http://doc.babylonjs.com/babylon101/lights
  23247. */
  23248. this.lights = new Array();
  23249. // Cameras
  23250. /** All of the cameras added to this scene.
  23251. * @see http://doc.babylonjs.com/babylon101/cameras
  23252. */
  23253. this.cameras = new Array();
  23254. /** All of the active cameras added to this scene. */
  23255. this.activeCameras = new Array();
  23256. // Meshes
  23257. /**
  23258. * All of the tranform nodes added to this scene
  23259. * @see http://doc.babylonjs.com/how_to/transformnode
  23260. */
  23261. this.transformNodes = new Array();
  23262. /**
  23263. * All of the (abstract) meshes added to this scene
  23264. */
  23265. this.meshes = new Array();
  23266. /**
  23267. * All of the animation groups added to this scene
  23268. * @see http://doc.babylonjs.com/how_to/group
  23269. */
  23270. this.animationGroups = new Array();
  23271. // Geometries
  23272. this._geometries = new Array();
  23273. /**
  23274. * All of the materials added to this scene
  23275. * @see http://doc.babylonjs.com/babylon101/materials
  23276. */
  23277. this.materials = new Array();
  23278. /**
  23279. * All of the multi-materials added to this scene
  23280. * @see http://doc.babylonjs.com/how_to/multi_materials
  23281. */
  23282. this.multiMaterials = new Array();
  23283. // Textures
  23284. this._texturesEnabled = true;
  23285. /**
  23286. * All of the textures added to this scene
  23287. */
  23288. this.textures = new Array();
  23289. // Particles
  23290. /**
  23291. * Gets or sets a boolean indicating if particles are enabled on this scene
  23292. */
  23293. this.particlesEnabled = true;
  23294. /**
  23295. * All of the particle systems added to this scene
  23296. * @see http://doc.babylonjs.com/babylon101/particles
  23297. */
  23298. this.particleSystems = new Array();
  23299. // Sprites
  23300. /**
  23301. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23302. */
  23303. this.spritesEnabled = true;
  23304. /**
  23305. * All of the sprite managers added to this scene
  23306. * @see http://doc.babylonjs.com/babylon101/sprites
  23307. */
  23308. this.spriteManagers = new Array();
  23309. /**
  23310. * The list of layers (background and foreground) of the scene
  23311. */
  23312. this.layers = new Array();
  23313. /**
  23314. * The list of effect layers (highlights/glow) added to the scene
  23315. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23316. * @see http://doc.babylonjs.com/how_to/glow_layer
  23317. */
  23318. this.effectLayers = new Array();
  23319. // Skeletons
  23320. this._skeletonsEnabled = true;
  23321. /**
  23322. * The list of skeletons added to the scene
  23323. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23324. */
  23325. this.skeletons = new Array();
  23326. // Morph targets
  23327. /**
  23328. * The list of morph target managers added to the scene
  23329. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23330. */
  23331. this.morphTargetManagers = new Array();
  23332. // Lens flares
  23333. /**
  23334. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23335. */
  23336. this.lensFlaresEnabled = true;
  23337. /**
  23338. * The list of lens flare system added to the scene
  23339. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23340. */
  23341. this.lensFlareSystems = new Array();
  23342. // Collisions
  23343. /**
  23344. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23345. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23346. */
  23347. this.collisionsEnabled = true;
  23348. /**
  23349. * Defines the gravity applied to this scene (used only for collisions)
  23350. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23351. */
  23352. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23353. // Postprocesses
  23354. /**
  23355. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23356. */
  23357. this.postProcessesEnabled = true;
  23358. /**
  23359. * The list of postprocesses added to the scene
  23360. */
  23361. this.postProcesses = new Array();
  23362. // Customs render targets
  23363. /**
  23364. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23365. */
  23366. this.renderTargetsEnabled = true;
  23367. /**
  23368. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23369. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23370. */
  23371. this.dumpNextRenderTargets = false;
  23372. /**
  23373. * The list of user defined render targets added to the scene
  23374. */
  23375. this.customRenderTargets = new Array();
  23376. /**
  23377. * Gets the list of meshes imported to the scene through SceneLoader
  23378. */
  23379. this.importedMeshesFiles = new Array();
  23380. // Probes
  23381. /**
  23382. * Gets or sets a boolean indicating if probes are enabled on this scene
  23383. */
  23384. this.probesEnabled = true;
  23385. /**
  23386. * The list of reflection probes added to the scene
  23387. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23388. */
  23389. this.reflectionProbes = new Array();
  23390. /** @ignore */
  23391. this._actionManagers = new Array();
  23392. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23393. // Procedural textures
  23394. /**
  23395. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23396. */
  23397. this.proceduralTexturesEnabled = true;
  23398. /**
  23399. * The list of procedural textures added to the scene
  23400. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23401. */
  23402. this.proceduralTextures = new Array();
  23403. /**
  23404. * The list of sound tracks added to the scene
  23405. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23406. */
  23407. this.soundTracks = new Array();
  23408. this._audioEnabled = true;
  23409. this._headphone = false;
  23410. // Performance counters
  23411. this._totalVertices = new BABYLON.PerfCounter();
  23412. /** @ignore */
  23413. this._activeIndices = new BABYLON.PerfCounter();
  23414. /** @ignore */
  23415. this._activeParticles = new BABYLON.PerfCounter();
  23416. /** @ignore */
  23417. this._activeBones = new BABYLON.PerfCounter();
  23418. this._animationTime = 0;
  23419. /**
  23420. * Gets or sets a general scale for animation speed
  23421. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23422. */
  23423. this.animationTimeScale = 1;
  23424. this._renderId = 0;
  23425. this._executeWhenReadyTimeoutId = -1;
  23426. this._intermediateRendering = false;
  23427. this._viewUpdateFlag = -1;
  23428. this._projectionUpdateFlag = -1;
  23429. this._alternateViewUpdateFlag = -1;
  23430. this._alternateProjectionUpdateFlag = -1;
  23431. /** @ignore */
  23432. this._toBeDisposed = new BABYLON.SmartArray(256);
  23433. this._activeRequests = new Array();
  23434. this._pendingData = new Array();
  23435. this._isDisposed = false;
  23436. /**
  23437. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23438. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23439. */
  23440. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23441. this._activeMeshes = new BABYLON.SmartArray(256);
  23442. this._processedMaterials = new BABYLON.SmartArray(256);
  23443. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23444. /** @ignore */
  23445. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23446. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23447. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23448. /** @ignore */
  23449. this._activeAnimatables = new Array();
  23450. this._transformMatrix = BABYLON.Matrix.Zero();
  23451. this._useAlternateCameraConfiguration = false;
  23452. this._alternateRendering = false;
  23453. /**
  23454. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23455. * This is useful if there are more lights that the maximum simulteanous authorized
  23456. */
  23457. this.requireLightSorting = false;
  23458. this._depthRenderer = {};
  23459. this._activeMeshesFrozen = false;
  23460. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23461. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23462. this._engine.scenes.push(this);
  23463. this._uid = null;
  23464. this._renderingManager = new BABYLON.RenderingManager(this);
  23465. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23466. if (BABYLON.OutlineRenderer) {
  23467. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23468. }
  23469. if (BABYLON.Tools.IsWindowObjectExist()) {
  23470. this.attachControl();
  23471. }
  23472. //simplification queue
  23473. if (BABYLON.SimplificationQueue) {
  23474. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23475. }
  23476. //collision coordinator initialization. For now legacy per default.
  23477. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23478. // Uniform Buffer
  23479. this._createUbo();
  23480. // Default Image processing definition.
  23481. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23482. }
  23483. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23484. /** The fog is deactivated */
  23485. get: function () {
  23486. return Scene._FOGMODE_NONE;
  23487. },
  23488. enumerable: true,
  23489. configurable: true
  23490. });
  23491. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23492. /** The fog density is following an exponential function */
  23493. get: function () {
  23494. return Scene._FOGMODE_EXP;
  23495. },
  23496. enumerable: true,
  23497. configurable: true
  23498. });
  23499. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23500. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23501. get: function () {
  23502. return Scene._FOGMODE_EXP2;
  23503. },
  23504. enumerable: true,
  23505. configurable: true
  23506. });
  23507. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23508. /** The fog density is following a linear function. */
  23509. get: function () {
  23510. return Scene._FOGMODE_LINEAR;
  23511. },
  23512. enumerable: true,
  23513. configurable: true
  23514. });
  23515. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23516. /**
  23517. * Texture used in all pbr material as the reflection texture.
  23518. * As in the majority of the scene they are the same (exception for multi room and so on),
  23519. * this is easier to reference from here than from all the materials.
  23520. */
  23521. get: function () {
  23522. return this._environmentTexture;
  23523. },
  23524. /**
  23525. * Texture used in all pbr material as the reflection texture.
  23526. * As in the majority of the scene they are the same (exception for multi room and so on),
  23527. * this is easier to set here than in all the materials.
  23528. */
  23529. set: function (value) {
  23530. if (this._environmentTexture === value) {
  23531. return;
  23532. }
  23533. this._environmentTexture = value;
  23534. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23535. },
  23536. enumerable: true,
  23537. configurable: true
  23538. });
  23539. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23540. /**
  23541. * Default image processing configuration used either in the rendering
  23542. * Forward main pass or through the imageProcessingPostProcess if present.
  23543. * As in the majority of the scene they are the same (exception for multi camera),
  23544. * this is easier to reference from here than from all the materials and post process.
  23545. *
  23546. * No setter as we it is a shared configuration, you can set the values instead.
  23547. */
  23548. get: function () {
  23549. return this._imageProcessingConfiguration;
  23550. },
  23551. enumerable: true,
  23552. configurable: true
  23553. });
  23554. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23555. get: function () {
  23556. return this._forceWireframe;
  23557. },
  23558. /**
  23559. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23560. */
  23561. set: function (value) {
  23562. if (this._forceWireframe === value) {
  23563. return;
  23564. }
  23565. this._forceWireframe = value;
  23566. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23567. },
  23568. enumerable: true,
  23569. configurable: true
  23570. });
  23571. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23572. get: function () {
  23573. return this._forcePointsCloud;
  23574. },
  23575. /**
  23576. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23577. */
  23578. set: function (value) {
  23579. if (this._forcePointsCloud === value) {
  23580. return;
  23581. }
  23582. this._forcePointsCloud = value;
  23583. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23584. },
  23585. enumerable: true,
  23586. configurable: true
  23587. });
  23588. Object.defineProperty(Scene.prototype, "onDispose", {
  23589. /** Sets a function to be executed when this scene is disposed. */
  23590. set: function (callback) {
  23591. if (this._onDisposeObserver) {
  23592. this.onDisposeObservable.remove(this._onDisposeObserver);
  23593. }
  23594. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23595. },
  23596. enumerable: true,
  23597. configurable: true
  23598. });
  23599. Object.defineProperty(Scene.prototype, "beforeRender", {
  23600. /** Sets a function to be executed before rendering this scene */
  23601. set: function (callback) {
  23602. if (this._onBeforeRenderObserver) {
  23603. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23604. }
  23605. if (callback) {
  23606. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23607. }
  23608. },
  23609. enumerable: true,
  23610. configurable: true
  23611. });
  23612. Object.defineProperty(Scene.prototype, "afterRender", {
  23613. /** Sets a function to be executed after rendering this scene */
  23614. set: function (callback) {
  23615. if (this._onAfterRenderObserver) {
  23616. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23617. }
  23618. if (callback) {
  23619. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23620. }
  23621. },
  23622. enumerable: true,
  23623. configurable: true
  23624. });
  23625. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23626. /** Sets a function to be executed before rendering a camera*/
  23627. set: function (callback) {
  23628. if (this._onBeforeCameraRenderObserver) {
  23629. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23630. }
  23631. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23632. },
  23633. enumerable: true,
  23634. configurable: true
  23635. });
  23636. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23637. /** Sets a function to be executed after rendering a camera*/
  23638. set: function (callback) {
  23639. if (this._onAfterCameraRenderObserver) {
  23640. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23641. }
  23642. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23643. },
  23644. enumerable: true,
  23645. configurable: true
  23646. });
  23647. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23648. /**
  23649. * Gets the gamepad manager associated with the scene
  23650. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23651. */
  23652. get: function () {
  23653. if (!this._gamepadManager) {
  23654. this._gamepadManager = new BABYLON.GamepadManager(this);
  23655. }
  23656. return this._gamepadManager;
  23657. },
  23658. enumerable: true,
  23659. configurable: true
  23660. });
  23661. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23662. /**
  23663. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23664. */
  23665. get: function () {
  23666. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23667. },
  23668. enumerable: true,
  23669. configurable: true
  23670. });
  23671. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23672. get: function () {
  23673. return this._useRightHandedSystem;
  23674. },
  23675. /**
  23676. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23677. */
  23678. set: function (value) {
  23679. if (this._useRightHandedSystem === value) {
  23680. return;
  23681. }
  23682. this._useRightHandedSystem = value;
  23683. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23684. },
  23685. enumerable: true,
  23686. configurable: true
  23687. });
  23688. /**
  23689. * Sets the step Id used by deterministic lock step
  23690. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23691. * @param newStepId defines the step Id
  23692. */
  23693. Scene.prototype.setStepId = function (newStepId) {
  23694. this._currentStepId = newStepId;
  23695. };
  23696. ;
  23697. /**
  23698. * Gets the step Id used by deterministic lock step
  23699. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23700. * @returns the step Id
  23701. */
  23702. Scene.prototype.getStepId = function () {
  23703. return this._currentStepId;
  23704. };
  23705. ;
  23706. /**
  23707. * Gets the internal step used by deterministic lock step
  23708. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23709. * @returns the internal step
  23710. */
  23711. Scene.prototype.getInternalStep = function () {
  23712. return this._currentInternalStep;
  23713. };
  23714. ;
  23715. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23716. get: function () {
  23717. return this._fogEnabled;
  23718. },
  23719. /**
  23720. * Gets or sets a boolean indicating if fog is enabled on this scene
  23721. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23722. */
  23723. set: function (value) {
  23724. if (this._fogEnabled === value) {
  23725. return;
  23726. }
  23727. this._fogEnabled = value;
  23728. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23729. },
  23730. enumerable: true,
  23731. configurable: true
  23732. });
  23733. Object.defineProperty(Scene.prototype, "fogMode", {
  23734. get: function () {
  23735. return this._fogMode;
  23736. },
  23737. /**
  23738. * Gets or sets the fog mode to use
  23739. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23740. */
  23741. set: function (value) {
  23742. if (this._fogMode === value) {
  23743. return;
  23744. }
  23745. this._fogMode = value;
  23746. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23747. },
  23748. enumerable: true,
  23749. configurable: true
  23750. });
  23751. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  23752. get: function () {
  23753. return this._shadowsEnabled;
  23754. },
  23755. /**
  23756. * Gets or sets a boolean indicating if shadows are enabled on this scene
  23757. */
  23758. set: function (value) {
  23759. if (this._shadowsEnabled === value) {
  23760. return;
  23761. }
  23762. this._shadowsEnabled = value;
  23763. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23764. },
  23765. enumerable: true,
  23766. configurable: true
  23767. });
  23768. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  23769. get: function () {
  23770. return this._lightsEnabled;
  23771. },
  23772. /**
  23773. * Gets or sets a boolean indicating if lights are enabled on this scene
  23774. */
  23775. set: function (value) {
  23776. if (this._lightsEnabled === value) {
  23777. return;
  23778. }
  23779. this._lightsEnabled = value;
  23780. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  23781. },
  23782. enumerable: true,
  23783. configurable: true
  23784. });
  23785. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  23786. /** The default material used on meshes when no material is affected */
  23787. get: function () {
  23788. if (!this._defaultMaterial) {
  23789. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  23790. }
  23791. return this._defaultMaterial;
  23792. },
  23793. /** The default material used on meshes when no material is affected */
  23794. set: function (value) {
  23795. this._defaultMaterial = value;
  23796. },
  23797. enumerable: true,
  23798. configurable: true
  23799. });
  23800. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  23801. get: function () {
  23802. return this._texturesEnabled;
  23803. },
  23804. /**
  23805. * Gets or sets a boolean indicating if textures are enabled on this scene
  23806. */
  23807. set: function (value) {
  23808. if (this._texturesEnabled === value) {
  23809. return;
  23810. }
  23811. this._texturesEnabled = value;
  23812. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23813. },
  23814. enumerable: true,
  23815. configurable: true
  23816. });
  23817. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  23818. get: function () {
  23819. return this._skeletonsEnabled;
  23820. },
  23821. /**
  23822. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  23823. */
  23824. set: function (value) {
  23825. if (this._skeletonsEnabled === value) {
  23826. return;
  23827. }
  23828. this._skeletonsEnabled = value;
  23829. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  23830. },
  23831. enumerable: true,
  23832. configurable: true
  23833. });
  23834. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  23835. /**
  23836. * Gets the postprocess render pipeline manager
  23837. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  23838. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  23839. */
  23840. get: function () {
  23841. if (!this._postProcessRenderPipelineManager) {
  23842. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  23843. }
  23844. return this._postProcessRenderPipelineManager;
  23845. },
  23846. enumerable: true,
  23847. configurable: true
  23848. });
  23849. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  23850. /**
  23851. * Gets the main soundtrack associated with the scene
  23852. */
  23853. get: function () {
  23854. if (!this._mainSoundTrack) {
  23855. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  23856. }
  23857. return this._mainSoundTrack;
  23858. },
  23859. enumerable: true,
  23860. configurable: true
  23861. });
  23862. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  23863. /** @ignore */
  23864. get: function () {
  23865. return this._alternateRendering;
  23866. },
  23867. enumerable: true,
  23868. configurable: true
  23869. });
  23870. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  23871. /**
  23872. * Gets the list of frustum planes (built from the active camera)
  23873. */
  23874. get: function () {
  23875. return this._frustumPlanes;
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  23881. /**
  23882. * Gets the current geometry buffer associated to the scene.
  23883. */
  23884. get: function () {
  23885. return this._geometryBufferRenderer;
  23886. },
  23887. /**
  23888. * Sets the current geometry buffer for the scene.
  23889. */
  23890. set: function (geometryBufferRenderer) {
  23891. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  23892. this._geometryBufferRenderer = geometryBufferRenderer;
  23893. }
  23894. },
  23895. enumerable: true,
  23896. configurable: true
  23897. });
  23898. Object.defineProperty(Scene.prototype, "debugLayer", {
  23899. /**
  23900. * Gets the debug layer associated with the scene
  23901. * @see http://doc.babylonjs.com/features/playground_debuglayer
  23902. */
  23903. get: function () {
  23904. if (!this._debugLayer) {
  23905. this._debugLayer = new BABYLON.DebugLayer(this);
  23906. }
  23907. return this._debugLayer;
  23908. },
  23909. enumerable: true,
  23910. configurable: true
  23911. });
  23912. Object.defineProperty(Scene.prototype, "workerCollisions", {
  23913. /**
  23914. * Gets a boolean indicating if collisions are processed on a web worker
  23915. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  23916. */
  23917. get: function () {
  23918. return this._workerCollisions;
  23919. },
  23920. set: function (enabled) {
  23921. if (!BABYLON.CollisionCoordinatorLegacy) {
  23922. return;
  23923. }
  23924. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  23925. this._workerCollisions = enabled;
  23926. if (this.collisionCoordinator) {
  23927. this.collisionCoordinator.destroy();
  23928. }
  23929. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  23930. this.collisionCoordinator.init(this);
  23931. },
  23932. enumerable: true,
  23933. configurable: true
  23934. });
  23935. Object.defineProperty(Scene.prototype, "selectionOctree", {
  23936. /**
  23937. * Gets the octree used to boost mesh selection (picking)
  23938. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  23939. */
  23940. get: function () {
  23941. return this._selectionOctree;
  23942. },
  23943. enumerable: true,
  23944. configurable: true
  23945. });
  23946. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  23947. /**
  23948. * Gets the mesh that is currently under the pointer
  23949. */
  23950. get: function () {
  23951. return this._pointerOverMesh;
  23952. },
  23953. enumerable: true,
  23954. configurable: true
  23955. });
  23956. Object.defineProperty(Scene.prototype, "pointerX", {
  23957. /**
  23958. * Gets the current on-screen X position of the pointer
  23959. */
  23960. get: function () {
  23961. return this._pointerX;
  23962. },
  23963. enumerable: true,
  23964. configurable: true
  23965. });
  23966. Object.defineProperty(Scene.prototype, "pointerY", {
  23967. /**
  23968. * Gets the current on-screen Y position of the pointer
  23969. */
  23970. get: function () {
  23971. return this._pointerY;
  23972. },
  23973. enumerable: true,
  23974. configurable: true
  23975. });
  23976. /**
  23977. * Gets the cached material (ie. the latest rendered one)
  23978. * @returns the cached material
  23979. */
  23980. Scene.prototype.getCachedMaterial = function () {
  23981. return this._cachedMaterial;
  23982. };
  23983. /**
  23984. * Gets the cached effect (ie. the latest rendered one)
  23985. * @returns the cached effect
  23986. */
  23987. Scene.prototype.getCachedEffect = function () {
  23988. return this._cachedEffect;
  23989. };
  23990. /**
  23991. * Gets the cached visibility state (ie. the latest rendered one)
  23992. * @returns the cached visibility state
  23993. */
  23994. Scene.prototype.getCachedVisibility = function () {
  23995. return this._cachedVisibility;
  23996. };
  23997. /**
  23998. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  23999. * @param material defines the current material
  24000. * @param effect defines the current effect
  24001. * @param visibility defines the current visibility state
  24002. * @returns true if one parameter is not cached
  24003. */
  24004. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24005. if (visibility === void 0) { visibility = 1; }
  24006. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24007. };
  24008. /**
  24009. * Gets the bounding box renderer associated with the scene
  24010. * @returns a BoundingBoxRenderer
  24011. */
  24012. Scene.prototype.getBoundingBoxRenderer = function () {
  24013. if (!this._boundingBoxRenderer) {
  24014. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24015. }
  24016. return this._boundingBoxRenderer;
  24017. };
  24018. /**
  24019. * Gets the outline renderer associated with the scene
  24020. * @returns a OutlineRenderer
  24021. */
  24022. Scene.prototype.getOutlineRenderer = function () {
  24023. return this._outlineRenderer;
  24024. };
  24025. /**
  24026. * Gets the engine associated with the scene
  24027. * @returns an Engine
  24028. */
  24029. Scene.prototype.getEngine = function () {
  24030. return this._engine;
  24031. };
  24032. /**
  24033. * Gets the total number of vertices rendered per frame
  24034. * @returns the total number of vertices rendered per frame
  24035. */
  24036. Scene.prototype.getTotalVertices = function () {
  24037. return this._totalVertices.current;
  24038. };
  24039. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24040. /**
  24041. * Gets the performance counter for total vertices
  24042. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24043. */
  24044. get: function () {
  24045. return this._totalVertices;
  24046. },
  24047. enumerable: true,
  24048. configurable: true
  24049. });
  24050. /**
  24051. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24052. * @returns the total number of active indices rendered per frame
  24053. */
  24054. Scene.prototype.getActiveIndices = function () {
  24055. return this._activeIndices.current;
  24056. };
  24057. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24058. /**
  24059. * Gets the performance counter for active indices
  24060. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24061. */
  24062. get: function () {
  24063. return this._activeIndices;
  24064. },
  24065. enumerable: true,
  24066. configurable: true
  24067. });
  24068. /**
  24069. * Gets the total number of active particles rendered per frame
  24070. * @returns the total number of active particles rendered per frame
  24071. */
  24072. Scene.prototype.getActiveParticles = function () {
  24073. return this._activeParticles.current;
  24074. };
  24075. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24076. /**
  24077. * Gets the performance counter for active particles
  24078. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24079. */
  24080. get: function () {
  24081. return this._activeParticles;
  24082. },
  24083. enumerable: true,
  24084. configurable: true
  24085. });
  24086. /**
  24087. * Gets the total number of active bones rendered per frame
  24088. * @returns the total number of active bones rendered per frame
  24089. */
  24090. Scene.prototype.getActiveBones = function () {
  24091. return this._activeBones.current;
  24092. };
  24093. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24094. /**
  24095. * Gets the performance counter for active bones
  24096. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24097. */
  24098. get: function () {
  24099. return this._activeBones;
  24100. },
  24101. enumerable: true,
  24102. configurable: true
  24103. });
  24104. /** @ignore */
  24105. Scene.prototype.getInterFramePerfCounter = function () {
  24106. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24107. return 0;
  24108. };
  24109. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24110. /** @ignore */
  24111. get: function () {
  24112. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24113. return null;
  24114. },
  24115. enumerable: true,
  24116. configurable: true
  24117. });
  24118. /** @ignore */
  24119. Scene.prototype.getLastFrameDuration = function () {
  24120. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24121. return 0;
  24122. };
  24123. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24124. /** @ignore */
  24125. get: function () {
  24126. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24127. return null;
  24128. },
  24129. enumerable: true,
  24130. configurable: true
  24131. });
  24132. /** @ignore */
  24133. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24134. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24135. return 0;
  24136. };
  24137. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24138. /** @ignore */
  24139. get: function () {
  24140. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24141. return null;
  24142. },
  24143. enumerable: true,
  24144. configurable: true
  24145. });
  24146. /**
  24147. * Gets the array of active meshes
  24148. * @returns an array of AbstractMesh
  24149. */
  24150. Scene.prototype.getActiveMeshes = function () {
  24151. return this._activeMeshes;
  24152. };
  24153. /** @ignore */
  24154. Scene.prototype.getRenderTargetsDuration = function () {
  24155. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24156. return 0;
  24157. };
  24158. /** @ignore */
  24159. Scene.prototype.getRenderDuration = function () {
  24160. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24161. return 0;
  24162. };
  24163. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24164. /** @ignore */
  24165. get: function () {
  24166. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24167. return null;
  24168. },
  24169. enumerable: true,
  24170. configurable: true
  24171. });
  24172. /** @ignore */
  24173. Scene.prototype.getParticlesDuration = function () {
  24174. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24175. return 0;
  24176. };
  24177. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24178. /** @ignore */
  24179. get: function () {
  24180. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24181. return null;
  24182. },
  24183. enumerable: true,
  24184. configurable: true
  24185. });
  24186. /** @ignore */
  24187. Scene.prototype.getSpritesDuration = function () {
  24188. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24189. return 0;
  24190. };
  24191. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24192. /** @ignore */
  24193. get: function () {
  24194. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24195. return null;
  24196. },
  24197. enumerable: true,
  24198. configurable: true
  24199. });
  24200. /**
  24201. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24202. * @returns a number
  24203. */
  24204. Scene.prototype.getAnimationRatio = function () {
  24205. return this._animationRatio;
  24206. };
  24207. /**
  24208. * Gets an unique Id for the current frame
  24209. * @returns a number
  24210. */
  24211. Scene.prototype.getRenderId = function () {
  24212. return this._renderId;
  24213. };
  24214. /** Call this function if you want to manually increment the render Id*/
  24215. Scene.prototype.incrementRenderId = function () {
  24216. this._renderId++;
  24217. };
  24218. Scene.prototype._updatePointerPosition = function (evt) {
  24219. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24220. if (!canvasRect) {
  24221. return;
  24222. }
  24223. this._pointerX = evt.clientX - canvasRect.left;
  24224. this._pointerY = evt.clientY - canvasRect.top;
  24225. this._unTranslatedPointerX = this._pointerX;
  24226. this._unTranslatedPointerY = this._pointerY;
  24227. };
  24228. Scene.prototype._createUbo = function () {
  24229. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24230. this._sceneUbo.addUniform("viewProjection", 16);
  24231. this._sceneUbo.addUniform("view", 16);
  24232. };
  24233. Scene.prototype._createAlternateUbo = function () {
  24234. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24235. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24236. this._alternateSceneUbo.addUniform("view", 16);
  24237. };
  24238. // Pointers handling
  24239. /**
  24240. * Use this method to simulate a pointer move on a mesh
  24241. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24242. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24243. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24244. * @returns the current scene
  24245. */
  24246. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24247. var evt = new PointerEvent("pointermove", pointerEventInit);
  24248. return this._processPointerMove(pickResult, evt);
  24249. };
  24250. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24251. var canvas = this._engine.getRenderingCanvas();
  24252. if (!canvas) {
  24253. return this;
  24254. }
  24255. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24256. this.setPointerOverSprite(null);
  24257. this.setPointerOverMesh(pickResult.pickedMesh);
  24258. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24259. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24260. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24261. }
  24262. else {
  24263. canvas.style.cursor = this.hoverCursor;
  24264. }
  24265. }
  24266. else {
  24267. canvas.style.cursor = this.defaultCursor;
  24268. }
  24269. }
  24270. else {
  24271. this.setPointerOverMesh(null);
  24272. // Sprites
  24273. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24274. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24275. this.setPointerOverSprite(pickResult.pickedSprite);
  24276. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24277. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24278. }
  24279. else {
  24280. canvas.style.cursor = this.hoverCursor;
  24281. }
  24282. }
  24283. else {
  24284. this.setPointerOverSprite(null);
  24285. // Restore pointer
  24286. canvas.style.cursor = this.defaultCursor;
  24287. }
  24288. }
  24289. if (pickResult) {
  24290. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24291. if (this.onPointerMove) {
  24292. this.onPointerMove(evt, pickResult, type);
  24293. }
  24294. if (this.onPointerObservable.hasObservers()) {
  24295. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24296. this.onPointerObservable.notifyObservers(pi, type);
  24297. }
  24298. }
  24299. return this;
  24300. };
  24301. /**
  24302. * Use this method to simulate a pointer down on a mesh
  24303. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24304. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24305. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24306. * @returns the current scene
  24307. */
  24308. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24309. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24310. return this._processPointerDown(pickResult, evt);
  24311. };
  24312. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24313. var _this = this;
  24314. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24315. this._pickedDownMesh = pickResult.pickedMesh;
  24316. var actionManager = pickResult.pickedMesh.actionManager;
  24317. if (actionManager) {
  24318. if (actionManager.hasPickTriggers) {
  24319. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24320. switch (evt.button) {
  24321. case 0:
  24322. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24323. break;
  24324. case 1:
  24325. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24326. break;
  24327. case 2:
  24328. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24329. break;
  24330. }
  24331. }
  24332. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24333. window.setTimeout(function () {
  24334. 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);
  24335. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24336. if (_this._totalPointersPressed !== 0 &&
  24337. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24338. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24339. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24340. _this._startingPointerTime = 0;
  24341. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24342. }
  24343. }
  24344. }, Scene.LongPressDelay);
  24345. }
  24346. }
  24347. }
  24348. if (pickResult) {
  24349. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24350. if (this.onPointerDown) {
  24351. this.onPointerDown(evt, pickResult, type);
  24352. }
  24353. if (this.onPointerObservable.hasObservers()) {
  24354. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24355. this.onPointerObservable.notifyObservers(pi, type);
  24356. }
  24357. }
  24358. return this;
  24359. };
  24360. /**
  24361. * Use this method to simulate a pointer up on a mesh
  24362. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24363. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24364. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24365. * @returns the current scene
  24366. */
  24367. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24368. var evt = new PointerEvent("pointerup", pointerEventInit);
  24369. var clickInfo = new ClickInfo();
  24370. clickInfo.singleClick = true;
  24371. clickInfo.ignore = true;
  24372. return this._processPointerUp(pickResult, evt, clickInfo);
  24373. };
  24374. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24375. if (pickResult && pickResult && pickResult.pickedMesh) {
  24376. this._pickedUpMesh = pickResult.pickedMesh;
  24377. if (this._pickedDownMesh === this._pickedUpMesh) {
  24378. if (this.onPointerPick) {
  24379. this.onPointerPick(evt, pickResult);
  24380. }
  24381. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24382. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24383. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24384. this.onPointerObservable.notifyObservers(pi, type_1);
  24385. }
  24386. }
  24387. if (pickResult.pickedMesh.actionManager) {
  24388. if (clickInfo.ignore) {
  24389. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24390. }
  24391. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24392. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24393. }
  24394. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24395. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24396. }
  24397. }
  24398. }
  24399. if (this._pickedDownMesh &&
  24400. this._pickedDownMesh.actionManager &&
  24401. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24402. this._pickedDownMesh !== this._pickedUpMesh) {
  24403. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24404. }
  24405. var type = BABYLON.PointerEventTypes.POINTERUP;
  24406. if (this.onPointerObservable.hasObservers()) {
  24407. if (!clickInfo.ignore) {
  24408. if (!clickInfo.hasSwiped) {
  24409. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24410. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24411. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24412. this.onPointerObservable.notifyObservers(pi, type_2);
  24413. }
  24414. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24415. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24416. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24417. this.onPointerObservable.notifyObservers(pi, type_3);
  24418. }
  24419. }
  24420. }
  24421. else {
  24422. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24423. this.onPointerObservable.notifyObservers(pi, type);
  24424. }
  24425. }
  24426. if (this.onPointerUp) {
  24427. this.onPointerUp(evt, pickResult, type);
  24428. }
  24429. return this;
  24430. };
  24431. /**
  24432. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24433. * @param attachUp defines if you want to attach events to pointerup
  24434. * @param attachDown defines if you want to attach events to pointerdown
  24435. * @param attachMove defines if you want to attach events to pointermove
  24436. */
  24437. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24438. var _this = this;
  24439. if (attachUp === void 0) { attachUp = true; }
  24440. if (attachDown === void 0) { attachDown = true; }
  24441. if (attachMove === void 0) { attachMove = true; }
  24442. this._initActionManager = function (act, clickInfo) {
  24443. if (!_this._meshPickProceed) {
  24444. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24445. _this._currentPickResult = pickResult;
  24446. if (pickResult) {
  24447. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24448. }
  24449. _this._meshPickProceed = true;
  24450. }
  24451. return act;
  24452. };
  24453. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24454. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24455. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24456. btn !== _this._previousButtonPressed) {
  24457. _this._doubleClickOccured = false;
  24458. clickInfo.singleClick = true;
  24459. clickInfo.ignore = false;
  24460. cb(clickInfo, _this._currentPickResult);
  24461. }
  24462. };
  24463. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24464. var clickInfo = new ClickInfo();
  24465. _this._currentPickResult = null;
  24466. var act = null;
  24467. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24468. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24469. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24470. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24471. act = _this._initActionManager(act, clickInfo);
  24472. if (act)
  24473. checkPicking = act.hasPickTriggers;
  24474. }
  24475. if (checkPicking) {
  24476. var btn = evt.button;
  24477. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24478. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24479. if (!clickInfo.hasSwiped) {
  24480. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24481. if (!checkSingleClickImmediately) {
  24482. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24483. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24484. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24485. act = _this._initActionManager(act, clickInfo);
  24486. if (act)
  24487. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24488. }
  24489. }
  24490. if (checkSingleClickImmediately) {
  24491. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24492. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24493. btn !== _this._previousButtonPressed) {
  24494. clickInfo.singleClick = true;
  24495. cb(clickInfo, _this._currentPickResult);
  24496. }
  24497. }
  24498. else {
  24499. // wait that no double click has been raised during the double click delay
  24500. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24501. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24502. }
  24503. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24504. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24505. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24506. act = _this._initActionManager(act, clickInfo);
  24507. if (act)
  24508. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24509. }
  24510. if (checkDoubleClick) {
  24511. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24512. if (btn === _this._previousButtonPressed &&
  24513. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24514. !_this._doubleClickOccured) {
  24515. // pointer has not moved for 2 clicks, it's a double click
  24516. if (!clickInfo.hasSwiped &&
  24517. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24518. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24519. _this._previousStartingPointerTime = 0;
  24520. _this._doubleClickOccured = true;
  24521. clickInfo.doubleClick = true;
  24522. clickInfo.ignore = false;
  24523. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24524. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24525. }
  24526. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24527. cb(clickInfo, _this._currentPickResult);
  24528. }
  24529. else {
  24530. _this._doubleClickOccured = false;
  24531. _this._previousStartingPointerTime = _this._startingPointerTime;
  24532. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24533. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24534. _this._previousButtonPressed = btn;
  24535. if (Scene.ExclusiveDoubleClickMode) {
  24536. if (_this._previousDelayedSimpleClickTimeout) {
  24537. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24538. }
  24539. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24540. cb(clickInfo, _this._previousPickResult);
  24541. }
  24542. else {
  24543. cb(clickInfo, _this._currentPickResult);
  24544. }
  24545. }
  24546. }
  24547. else {
  24548. _this._doubleClickOccured = false;
  24549. _this._previousStartingPointerTime = _this._startingPointerTime;
  24550. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24551. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24552. _this._previousButtonPressed = btn;
  24553. }
  24554. }
  24555. }
  24556. }
  24557. clickInfo.ignore = true;
  24558. cb(clickInfo, _this._currentPickResult);
  24559. };
  24560. this._spritePredicate = function (sprite) {
  24561. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24562. };
  24563. this._onPointerMove = function (evt) {
  24564. _this._updatePointerPosition(evt);
  24565. // PreObservable support
  24566. if (_this.onPrePointerObservable.hasObservers()) {
  24567. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24568. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24569. _this.onPrePointerObservable.notifyObservers(pi, type);
  24570. if (pi.skipOnPointerObservable) {
  24571. return;
  24572. }
  24573. }
  24574. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24575. return;
  24576. }
  24577. if (!_this.pointerMovePredicate) {
  24578. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24579. }
  24580. // Meshes
  24581. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24582. _this._processPointerMove(pickResult, evt);
  24583. };
  24584. this._onPointerDown = function (evt) {
  24585. _this._totalPointersPressed++;
  24586. _this._pickedDownMesh = null;
  24587. _this._meshPickProceed = false;
  24588. _this._updatePointerPosition(evt);
  24589. if (_this.preventDefaultOnPointerDown && canvas) {
  24590. evt.preventDefault();
  24591. canvas.focus();
  24592. }
  24593. // PreObservable support
  24594. if (_this.onPrePointerObservable.hasObservers()) {
  24595. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24596. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24597. _this.onPrePointerObservable.notifyObservers(pi, type);
  24598. if (pi.skipOnPointerObservable) {
  24599. return;
  24600. }
  24601. }
  24602. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24603. return;
  24604. }
  24605. _this._startingPointerPosition.x = _this._pointerX;
  24606. _this._startingPointerPosition.y = _this._pointerY;
  24607. _this._startingPointerTime = new Date().getTime();
  24608. if (!_this.pointerDownPredicate) {
  24609. _this.pointerDownPredicate = function (mesh) {
  24610. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24611. };
  24612. }
  24613. // Meshes
  24614. _this._pickedDownMesh = null;
  24615. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24616. _this._processPointerDown(pickResult, evt);
  24617. // Sprites
  24618. _this._pickedDownSprite = null;
  24619. if (_this.spriteManagers.length > 0) {
  24620. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24621. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24622. if (pickResult.pickedSprite.actionManager) {
  24623. _this._pickedDownSprite = pickResult.pickedSprite;
  24624. switch (evt.button) {
  24625. case 0:
  24626. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24627. break;
  24628. case 1:
  24629. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24630. break;
  24631. case 2:
  24632. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24633. break;
  24634. }
  24635. if (pickResult.pickedSprite.actionManager) {
  24636. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24637. }
  24638. }
  24639. }
  24640. }
  24641. };
  24642. this._onPointerUp = function (evt) {
  24643. if (_this._totalPointersPressed === 0) {
  24644. return; // So we need to test it the pointer down was pressed before.
  24645. }
  24646. _this._totalPointersPressed--;
  24647. _this._pickedUpMesh = null;
  24648. _this._meshPickProceed = false;
  24649. _this._updatePointerPosition(evt);
  24650. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24651. // PreObservable support
  24652. if (_this.onPrePointerObservable.hasObservers()) {
  24653. if (!clickInfo.ignore) {
  24654. if (!clickInfo.hasSwiped) {
  24655. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24656. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24657. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24658. _this.onPrePointerObservable.notifyObservers(pi, type);
  24659. if (pi.skipOnPointerObservable) {
  24660. return;
  24661. }
  24662. }
  24663. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24664. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24665. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24666. _this.onPrePointerObservable.notifyObservers(pi, type);
  24667. if (pi.skipOnPointerObservable) {
  24668. return;
  24669. }
  24670. }
  24671. }
  24672. }
  24673. else {
  24674. var type = BABYLON.PointerEventTypes.POINTERUP;
  24675. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24676. _this.onPrePointerObservable.notifyObservers(pi, type);
  24677. if (pi.skipOnPointerObservable) {
  24678. return;
  24679. }
  24680. }
  24681. }
  24682. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24683. return;
  24684. }
  24685. if (!_this.pointerUpPredicate) {
  24686. _this.pointerUpPredicate = function (mesh) {
  24687. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24688. };
  24689. }
  24690. // Meshes
  24691. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24692. _this._initActionManager(null, clickInfo);
  24693. }
  24694. if (!pickResult) {
  24695. pickResult = _this._currentPickResult;
  24696. }
  24697. _this._processPointerUp(pickResult, evt, clickInfo);
  24698. // Sprites
  24699. if (_this.spriteManagers.length > 0) {
  24700. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24701. if (spritePickResult) {
  24702. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24703. if (spritePickResult.pickedSprite.actionManager) {
  24704. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24705. if (spritePickResult.pickedSprite.actionManager) {
  24706. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24707. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24708. }
  24709. }
  24710. }
  24711. }
  24712. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24713. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24714. }
  24715. }
  24716. }
  24717. _this._previousPickResult = _this._currentPickResult;
  24718. });
  24719. };
  24720. this._onKeyDown = function (evt) {
  24721. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24722. if (_this.onPreKeyboardObservable.hasObservers()) {
  24723. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24724. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24725. if (pi.skipOnPointerObservable) {
  24726. return;
  24727. }
  24728. }
  24729. if (_this.onKeyboardObservable.hasObservers()) {
  24730. var pi = new BABYLON.KeyboardInfo(type, evt);
  24731. _this.onKeyboardObservable.notifyObservers(pi, type);
  24732. }
  24733. if (_this.actionManager) {
  24734. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24735. }
  24736. };
  24737. this._onKeyUp = function (evt) {
  24738. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24739. if (_this.onPreKeyboardObservable.hasObservers()) {
  24740. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24741. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24742. if (pi.skipOnPointerObservable) {
  24743. return;
  24744. }
  24745. }
  24746. if (_this.onKeyboardObservable.hasObservers()) {
  24747. var pi = new BABYLON.KeyboardInfo(type, evt);
  24748. _this.onKeyboardObservable.notifyObservers(pi, type);
  24749. }
  24750. if (_this.actionManager) {
  24751. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24752. }
  24753. };
  24754. var engine = this.getEngine();
  24755. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  24756. if (!canvas) {
  24757. return;
  24758. }
  24759. canvas.addEventListener("keydown", _this._onKeyDown, false);
  24760. canvas.addEventListener("keyup", _this._onKeyUp, false);
  24761. });
  24762. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  24763. if (!canvas) {
  24764. return;
  24765. }
  24766. canvas.removeEventListener("keydown", _this._onKeyDown);
  24767. canvas.removeEventListener("keyup", _this._onKeyUp);
  24768. });
  24769. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24770. var canvas = this._engine.getRenderingCanvas();
  24771. if (!canvas) {
  24772. return;
  24773. }
  24774. if (attachMove) {
  24775. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  24776. // Wheel
  24777. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  24778. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  24779. }
  24780. if (attachDown) {
  24781. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  24782. }
  24783. if (attachUp) {
  24784. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  24785. }
  24786. canvas.tabIndex = 1;
  24787. };
  24788. /** Detaches all event handlers*/
  24789. Scene.prototype.detachControl = function () {
  24790. var engine = this.getEngine();
  24791. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  24792. var canvas = engine.getRenderingCanvas();
  24793. if (!canvas) {
  24794. return;
  24795. }
  24796. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  24797. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  24798. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  24799. if (this._onCanvasBlurObserver) {
  24800. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  24801. }
  24802. if (this._onCanvasFocusObserver) {
  24803. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  24804. }
  24805. // Wheel
  24806. canvas.removeEventListener('mousewheel', this._onPointerMove);
  24807. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  24808. // Keyboard
  24809. canvas.removeEventListener("keydown", this._onKeyDown);
  24810. canvas.removeEventListener("keyup", this._onKeyUp);
  24811. // Observables
  24812. this.onKeyboardObservable.clear();
  24813. this.onPreKeyboardObservable.clear();
  24814. this.onPointerObservable.clear();
  24815. this.onPrePointerObservable.clear();
  24816. };
  24817. /**
  24818. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  24819. * Delay loaded resources are not taking in account
  24820. * @return true if all required resources are ready
  24821. */
  24822. Scene.prototype.isReady = function () {
  24823. if (this._isDisposed) {
  24824. return false;
  24825. }
  24826. if (this._pendingData.length > 0) {
  24827. return false;
  24828. }
  24829. var index;
  24830. var engine = this.getEngine();
  24831. // Geometries
  24832. for (index = 0; index < this._geometries.length; index++) {
  24833. var geometry = this._geometries[index];
  24834. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24835. return false;
  24836. }
  24837. }
  24838. // Meshes
  24839. for (index = 0; index < this.meshes.length; index++) {
  24840. var mesh = this.meshes[index];
  24841. if (!mesh.isEnabled()) {
  24842. continue;
  24843. }
  24844. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24845. continue;
  24846. }
  24847. if (!mesh.isReady(true)) {
  24848. return false;
  24849. }
  24850. // Effect layers
  24851. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  24852. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  24853. var layer = _a[_i];
  24854. if (!layer.hasMesh(mesh)) {
  24855. continue;
  24856. }
  24857. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24858. var subMesh = _c[_b];
  24859. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  24860. return false;
  24861. }
  24862. }
  24863. }
  24864. }
  24865. // Post-processes
  24866. if (this.activeCameras && this.activeCameras.length > 0) {
  24867. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  24868. var camera = _e[_d];
  24869. if (!camera.isReady(true)) {
  24870. return false;
  24871. }
  24872. }
  24873. }
  24874. else if (this.activeCamera) {
  24875. if (!this.activeCamera.isReady(true)) {
  24876. return false;
  24877. }
  24878. }
  24879. // Particles
  24880. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  24881. var particleSystem = _g[_f];
  24882. if (!particleSystem.isReady()) {
  24883. return false;
  24884. }
  24885. }
  24886. return true;
  24887. };
  24888. /** Resets all cached information relative to material (including effect and visibility) */
  24889. Scene.prototype.resetCachedMaterial = function () {
  24890. this._cachedMaterial = null;
  24891. this._cachedEffect = null;
  24892. this._cachedVisibility = null;
  24893. };
  24894. /**
  24895. * Registers a function to be called before every frame render
  24896. * @param func defines the function to register
  24897. */
  24898. Scene.prototype.registerBeforeRender = function (func) {
  24899. this.onBeforeRenderObservable.add(func);
  24900. };
  24901. /**
  24902. * Unregisters a function called before every frame render
  24903. * @param func defines the function to unregister
  24904. */
  24905. Scene.prototype.unregisterBeforeRender = function (func) {
  24906. this.onBeforeRenderObservable.removeCallback(func);
  24907. };
  24908. /**
  24909. * Registers a function to be called after every frame render
  24910. * @param func defines the function to register
  24911. */
  24912. Scene.prototype.registerAfterRender = function (func) {
  24913. this.onAfterRenderObservable.add(func);
  24914. };
  24915. /**
  24916. * Unregisters a function called after every frame render
  24917. * @param func defines the function to unregister
  24918. */
  24919. Scene.prototype.unregisterAfterRender = function (func) {
  24920. this.onAfterRenderObservable.removeCallback(func);
  24921. };
  24922. Scene.prototype._executeOnceBeforeRender = function (func) {
  24923. var _this = this;
  24924. var execFunc = function () {
  24925. func();
  24926. setTimeout(function () {
  24927. _this.unregisterBeforeRender(execFunc);
  24928. });
  24929. };
  24930. this.registerBeforeRender(execFunc);
  24931. };
  24932. /**
  24933. * The provided function will run before render once and will be disposed afterwards.
  24934. * A timeout delay can be provided so that the function will be executed in N ms.
  24935. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  24936. * @param func The function to be executed.
  24937. * @param timeout optional delay in ms
  24938. */
  24939. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  24940. var _this = this;
  24941. if (timeout !== undefined) {
  24942. setTimeout(function () {
  24943. _this._executeOnceBeforeRender(func);
  24944. }, timeout);
  24945. }
  24946. else {
  24947. this._executeOnceBeforeRender(func);
  24948. }
  24949. };
  24950. /** @ignore */
  24951. Scene.prototype._addPendingData = function (data) {
  24952. this._pendingData.push(data);
  24953. };
  24954. /** @ignore */
  24955. Scene.prototype._removePendingData = function (data) {
  24956. var wasLoading = this.isLoading;
  24957. var index = this._pendingData.indexOf(data);
  24958. if (index !== -1) {
  24959. this._pendingData.splice(index, 1);
  24960. }
  24961. if (wasLoading && !this.isLoading) {
  24962. this.onDataLoadedObservable.notifyObservers(this);
  24963. }
  24964. };
  24965. /**
  24966. * Returns the number of items waiting to be loaded
  24967. * @returns the number of items waiting to be loaded
  24968. */
  24969. Scene.prototype.getWaitingItemsCount = function () {
  24970. return this._pendingData.length;
  24971. };
  24972. Object.defineProperty(Scene.prototype, "isLoading", {
  24973. /**
  24974. * Returns a boolean indicating if the scene is still loading data
  24975. */
  24976. get: function () {
  24977. return this._pendingData.length > 0;
  24978. },
  24979. enumerable: true,
  24980. configurable: true
  24981. });
  24982. /**
  24983. * Registers a function to be executed when the scene is ready
  24984. * @param {Function} func - the function to be executed
  24985. */
  24986. Scene.prototype.executeWhenReady = function (func) {
  24987. var _this = this;
  24988. this.onReadyObservable.add(func);
  24989. if (this._executeWhenReadyTimeoutId !== -1) {
  24990. return;
  24991. }
  24992. this._executeWhenReadyTimeoutId = setTimeout(function () {
  24993. _this._checkIsReady();
  24994. }, 150);
  24995. };
  24996. /**
  24997. * Returns a promise that resolves when the scene is ready
  24998. * @returns A promise that resolves when the scene is ready
  24999. */
  25000. Scene.prototype.whenReadyAsync = function () {
  25001. var _this = this;
  25002. return new Promise(function (resolve) {
  25003. _this.executeWhenReady(function () {
  25004. resolve();
  25005. });
  25006. });
  25007. };
  25008. /** @ignore */
  25009. Scene.prototype._checkIsReady = function () {
  25010. var _this = this;
  25011. if (this.isReady()) {
  25012. this.onReadyObservable.notifyObservers(this);
  25013. this.onReadyObservable.clear();
  25014. this._executeWhenReadyTimeoutId = -1;
  25015. return;
  25016. }
  25017. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25018. _this._checkIsReady();
  25019. }, 150);
  25020. };
  25021. // Animations
  25022. /**
  25023. * Will start the animation sequence of a given target
  25024. * @param target defines the target
  25025. * @param from defines from which frame should animation start
  25026. * @param to defines until which frame should animation run.
  25027. * @param weight defines the weight to apply to the animation (1.0 by default)
  25028. * @param loop defines if the animation loops
  25029. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25030. * @param onAnimationEnd defines the function to be executed when the animation ends
  25031. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25032. * @returns the animatable object created for this animation
  25033. */
  25034. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25035. if (weight === void 0) { weight = 1.0; }
  25036. if (speedRatio === void 0) { speedRatio = 1.0; }
  25037. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25038. returnedAnimatable.weight = weight;
  25039. return returnedAnimatable;
  25040. };
  25041. /**
  25042. * Will start the animation sequence of a given target
  25043. * @param target defines the target
  25044. * @param from defines from which frame should animation start
  25045. * @param to defines until which frame should animation run.
  25046. * @param loop defines if the animation loops
  25047. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25048. * @param onAnimationEnd defines the function to be executed when the animation ends
  25049. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25050. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25051. * @returns the animatable object created for this animation
  25052. */
  25053. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25054. if (speedRatio === void 0) { speedRatio = 1.0; }
  25055. if (stopCurrent === void 0) { stopCurrent = true; }
  25056. if (from > to && speedRatio > 0) {
  25057. speedRatio *= -1;
  25058. }
  25059. if (stopCurrent) {
  25060. this.stopAnimation(target);
  25061. }
  25062. if (!animatable) {
  25063. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25064. }
  25065. // Local animations
  25066. if (target.animations) {
  25067. animatable.appendAnimations(target, target.animations);
  25068. }
  25069. // Children animations
  25070. if (target.getAnimatables) {
  25071. var animatables = target.getAnimatables();
  25072. for (var index = 0; index < animatables.length; index++) {
  25073. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25074. }
  25075. }
  25076. animatable.reset();
  25077. return animatable;
  25078. };
  25079. /**
  25080. * Begin a new animation on a given node
  25081. * @param target defines the target where the animation will take place
  25082. * @param animations defines the list of animations to start
  25083. * @param from defines the initial value
  25084. * @param to defines the final value
  25085. * @param loop defines if you want animation to loop (off by default)
  25086. * @param speedRatio defines the speed ratio to apply to all animations
  25087. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25088. * @returns the list of created animatables
  25089. */
  25090. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25091. if (speedRatio === undefined) {
  25092. speedRatio = 1.0;
  25093. }
  25094. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25095. return animatable;
  25096. };
  25097. /**
  25098. * Begin a new animation on a given node and its hierarchy
  25099. * @param target defines the root node where the animation will take place
  25100. * @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.
  25101. * @param animations defines the list of animations to start
  25102. * @param from defines the initial value
  25103. * @param to defines the final value
  25104. * @param loop defines if you want animation to loop (off by default)
  25105. * @param speedRatio defines the speed ratio to apply to all animations
  25106. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25107. * @returns the list of animatables created for all nodes
  25108. */
  25109. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25110. var children = target.getDescendants(directDescendantsOnly);
  25111. var result = [];
  25112. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25113. var child = children_1[_i];
  25114. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25115. }
  25116. return result;
  25117. };
  25118. /**
  25119. * Gets the animatable associated with a specific target
  25120. * @param target defines the target of the animatable
  25121. * @returns the required animatable if found
  25122. */
  25123. Scene.prototype.getAnimatableByTarget = function (target) {
  25124. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25125. if (this._activeAnimatables[index].target === target) {
  25126. return this._activeAnimatables[index];
  25127. }
  25128. }
  25129. return null;
  25130. };
  25131. /**
  25132. * Gets all animatables associated with a given target
  25133. * @param target defines the target to look animatables for
  25134. * @returns an array of Animatables
  25135. */
  25136. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25137. var result = [];
  25138. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25139. if (this._activeAnimatables[index].target === target) {
  25140. result.push(this._activeAnimatables[index]);
  25141. }
  25142. }
  25143. return result;
  25144. };
  25145. Object.defineProperty(Scene.prototype, "animatables", {
  25146. /**
  25147. * Gets all animatable attached to the scene
  25148. */
  25149. get: function () {
  25150. return this._activeAnimatables;
  25151. },
  25152. enumerable: true,
  25153. configurable: true
  25154. });
  25155. /**
  25156. * Will stop the animation of the given target
  25157. * @param target - the target
  25158. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25159. */
  25160. Scene.prototype.stopAnimation = function (target, animationName) {
  25161. var animatables = this.getAllAnimatablesByTarget(target);
  25162. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25163. var animatable = animatables_1[_i];
  25164. animatable.stop(animationName);
  25165. }
  25166. };
  25167. /**
  25168. * Stops and removes all animations that have been applied to the scene
  25169. */
  25170. Scene.prototype.stopAllAnimations = function () {
  25171. if (this._activeAnimatables) {
  25172. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25173. this._activeAnimatables[i].stop();
  25174. }
  25175. this._activeAnimatables = [];
  25176. }
  25177. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25178. var group = _a[_i];
  25179. group.stop();
  25180. }
  25181. };
  25182. Scene.prototype._animate = function () {
  25183. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25184. return;
  25185. }
  25186. // Getting time
  25187. var now = BABYLON.Tools.Now;
  25188. if (!this._animationTimeLast) {
  25189. if (this._pendingData.length > 0) {
  25190. return;
  25191. }
  25192. this._animationTimeLast = now;
  25193. }
  25194. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25195. this._animationTime += deltaTime;
  25196. this._animationTimeLast = now;
  25197. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25198. this._activeAnimatables[index]._animate(this._animationTime);
  25199. }
  25200. // Late animation bindings
  25201. this._processLateAnimationBindings();
  25202. };
  25203. /** @ignore */
  25204. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25205. var target = runtimeAnimation.target;
  25206. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25207. if (!target._lateAnimationHolders) {
  25208. target._lateAnimationHolders = {};
  25209. }
  25210. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25211. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25212. totalWeight: 0,
  25213. animations: []
  25214. };
  25215. }
  25216. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25217. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25218. };
  25219. Scene.prototype._processLateAnimationBindings = function () {
  25220. if (!this._registeredForLateAnimationBindings.length) {
  25221. return;
  25222. }
  25223. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25224. var target = this._registeredForLateAnimationBindings.data[index];
  25225. for (var path in target._lateAnimationHolders) {
  25226. var holder = target._lateAnimationHolders[path];
  25227. var originalValue = holder.animations[0].originalValue;
  25228. // Sanity check
  25229. if (!originalValue.scaleAndAddToRef) {
  25230. continue;
  25231. }
  25232. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25233. var normalizer = 1.0;
  25234. var finalValue = void 0;
  25235. if (holder.totalWeight < 1.0) {
  25236. // We need to mix the original value in
  25237. if (matrixDecomposeMode) {
  25238. finalValue = originalValue.clone();
  25239. }
  25240. else {
  25241. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25242. }
  25243. }
  25244. else {
  25245. // We need to normalize the weights
  25246. normalizer = holder.totalWeight;
  25247. }
  25248. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25249. var runtimeAnimation = holder.animations[animIndex];
  25250. var scale = runtimeAnimation.weight / normalizer;
  25251. if (finalValue) {
  25252. if (matrixDecomposeMode) {
  25253. BABYLON.Matrix.DecomposeLerpToRef(finalValue, runtimeAnimation.currentValue, scale, finalValue);
  25254. }
  25255. else {
  25256. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25257. }
  25258. }
  25259. else {
  25260. if (scale !== 1) {
  25261. if (matrixDecomposeMode) {
  25262. finalValue = runtimeAnimation.currentValue.clone();
  25263. }
  25264. else {
  25265. finalValue = runtimeAnimation.currentValue.scale(scale);
  25266. }
  25267. }
  25268. else {
  25269. finalValue = runtimeAnimation.currentValue;
  25270. }
  25271. }
  25272. }
  25273. runtimeAnimation.target[path] = finalValue;
  25274. }
  25275. target._lateAnimationHolders = {};
  25276. }
  25277. this._registeredForLateAnimationBindings.reset();
  25278. };
  25279. // Matrix
  25280. /** @ignore */
  25281. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25282. this._useAlternateCameraConfiguration = active;
  25283. };
  25284. /**
  25285. * Gets the current view matrix
  25286. * @returns a Matrix
  25287. */
  25288. Scene.prototype.getViewMatrix = function () {
  25289. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25290. };
  25291. /**
  25292. * Gets the current projection matrix
  25293. * @returns a Matrix
  25294. */
  25295. Scene.prototype.getProjectionMatrix = function () {
  25296. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25297. };
  25298. /**
  25299. * Gets the current transform matrix
  25300. * @returns a Matrix made of View * Projection
  25301. */
  25302. Scene.prototype.getTransformMatrix = function () {
  25303. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25304. };
  25305. /**
  25306. * Sets the current transform matrix
  25307. * @param view defines the View matrix to use
  25308. * @param projection defines the Projection matrix to use
  25309. */
  25310. Scene.prototype.setTransformMatrix = function (view, projection) {
  25311. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25312. return;
  25313. }
  25314. this._viewUpdateFlag = view.updateFlag;
  25315. this._projectionUpdateFlag = projection.updateFlag;
  25316. this._viewMatrix = view;
  25317. this._projectionMatrix = projection;
  25318. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25319. // Update frustum
  25320. if (!this._frustumPlanes) {
  25321. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25322. }
  25323. else {
  25324. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25325. }
  25326. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25327. var otherCamera = this.activeCamera._alternateCamera;
  25328. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25329. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25330. }
  25331. if (this._sceneUbo.useUbo) {
  25332. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25333. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25334. this._sceneUbo.update();
  25335. }
  25336. };
  25337. /** @ignore */
  25338. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25339. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25340. return;
  25341. }
  25342. this._alternateViewUpdateFlag = view.updateFlag;
  25343. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25344. this._alternateViewMatrix = view;
  25345. this._alternateProjectionMatrix = projection;
  25346. if (!this._alternateTransformMatrix) {
  25347. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25348. }
  25349. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25350. if (!this._alternateSceneUbo) {
  25351. this._createAlternateUbo();
  25352. }
  25353. if (this._alternateSceneUbo.useUbo) {
  25354. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25355. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25356. this._alternateSceneUbo.update();
  25357. }
  25358. };
  25359. /**
  25360. * Gets the uniform buffer used to store scene data
  25361. * @returns a UniformBuffer
  25362. */
  25363. Scene.prototype.getSceneUniformBuffer = function () {
  25364. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25365. };
  25366. /**
  25367. * Gets an unique (relatively to the current scene) Id
  25368. * @returns an unique number for the scene
  25369. */
  25370. Scene.prototype.getUniqueId = function () {
  25371. var result = Scene._uniqueIdCounter;
  25372. Scene._uniqueIdCounter++;
  25373. return result;
  25374. };
  25375. /**
  25376. * Add a mesh to the list of scene's meshes
  25377. * @param newMesh defines the mesh to add
  25378. */
  25379. Scene.prototype.addMesh = function (newMesh) {
  25380. this.meshes.push(newMesh);
  25381. //notify the collision coordinator
  25382. if (this.collisionCoordinator) {
  25383. this.collisionCoordinator.onMeshAdded(newMesh);
  25384. }
  25385. newMesh._resyncLightSources();
  25386. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25387. };
  25388. /**
  25389. * Remove a mesh for the list of scene's meshes
  25390. * @param toRemove defines the mesh to remove
  25391. * @returns the index where the mesh was in the mesh list
  25392. */
  25393. Scene.prototype.removeMesh = function (toRemove) {
  25394. var index = this.meshes.indexOf(toRemove);
  25395. if (index !== -1) {
  25396. // Remove from the scene if mesh found
  25397. this.meshes.splice(index, 1);
  25398. }
  25399. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25400. return index;
  25401. };
  25402. /**
  25403. * Add a transform node to the list of scene's transform nodes
  25404. * @param newTransformNode defines the transform node to add
  25405. */
  25406. Scene.prototype.addTransformNode = function (newTransformNode) {
  25407. this.transformNodes.push(newTransformNode);
  25408. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25409. };
  25410. /**
  25411. * Remove a transform node for the list of scene's transform nodes
  25412. * @param toRemove defines the transform node to remove
  25413. * @returns the index where the transform node was in the transform node list
  25414. */
  25415. Scene.prototype.removeTransformNode = function (toRemove) {
  25416. var index = this.transformNodes.indexOf(toRemove);
  25417. if (index !== -1) {
  25418. // Remove from the scene if found
  25419. this.transformNodes.splice(index, 1);
  25420. }
  25421. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25422. return index;
  25423. };
  25424. /**
  25425. * Remove a skeleton for the list of scene's skeletons
  25426. * @param toRemove defines the skeleton to remove
  25427. * @returns the index where the skeleton was in the skeleton list
  25428. */
  25429. Scene.prototype.removeSkeleton = function (toRemove) {
  25430. var index = this.skeletons.indexOf(toRemove);
  25431. if (index !== -1) {
  25432. // Remove from the scene if found
  25433. this.skeletons.splice(index, 1);
  25434. }
  25435. return index;
  25436. };
  25437. /**
  25438. * Remove a morph target for the list of scene's morph targets
  25439. * @param toRemove defines the morph target to remove
  25440. * @returns the index where the morph target was in the morph target list
  25441. */
  25442. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25443. var index = this.morphTargetManagers.indexOf(toRemove);
  25444. if (index !== -1) {
  25445. // Remove from the scene if found
  25446. this.morphTargetManagers.splice(index, 1);
  25447. }
  25448. return index;
  25449. };
  25450. /**
  25451. * Remove a light for the list of scene's lights
  25452. * @param toRemove defines the light to remove
  25453. * @returns the index where the light was in the light list
  25454. */
  25455. Scene.prototype.removeLight = function (toRemove) {
  25456. var index = this.lights.indexOf(toRemove);
  25457. if (index !== -1) {
  25458. // Remove from meshes
  25459. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25460. var mesh = _a[_i];
  25461. mesh._removeLightSource(toRemove);
  25462. }
  25463. // Remove from the scene if mesh found
  25464. this.lights.splice(index, 1);
  25465. this.sortLightsByPriority();
  25466. }
  25467. this.onLightRemovedObservable.notifyObservers(toRemove);
  25468. return index;
  25469. };
  25470. /**
  25471. * Remove a camera for the list of scene's cameras
  25472. * @param toRemove defines the camera to remove
  25473. * @returns the index where the camera was in the camera list
  25474. */
  25475. Scene.prototype.removeCamera = function (toRemove) {
  25476. var index = this.cameras.indexOf(toRemove);
  25477. if (index !== -1) {
  25478. // Remove from the scene if mesh found
  25479. this.cameras.splice(index, 1);
  25480. }
  25481. // Remove from activeCameras
  25482. var index2 = this.activeCameras.indexOf(toRemove);
  25483. if (index2 !== -1) {
  25484. // Remove from the scene if mesh found
  25485. this.activeCameras.splice(index2, 1);
  25486. }
  25487. // Reset the activeCamera
  25488. if (this.activeCamera === toRemove) {
  25489. if (this.cameras.length > 0) {
  25490. this.activeCamera = this.cameras[0];
  25491. }
  25492. else {
  25493. this.activeCamera = null;
  25494. }
  25495. }
  25496. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25497. return index;
  25498. };
  25499. /**
  25500. * Remove a particle system for the list of scene's particle systems
  25501. * @param toRemove defines the particle system to remove
  25502. * @returns the index where the particle system was in the particle system list
  25503. */
  25504. Scene.prototype.removeParticleSystem = function (toRemove) {
  25505. var index = this.particleSystems.indexOf(toRemove);
  25506. if (index !== -1) {
  25507. this.particleSystems.splice(index, 1);
  25508. }
  25509. return index;
  25510. };
  25511. /**
  25512. * Remove a animation for the list of scene's animations
  25513. * @param toRemove defines the animation to remove
  25514. * @returns the index where the animation was in the animation list
  25515. */
  25516. Scene.prototype.removeAnimation = function (toRemove) {
  25517. var index = this.animations.indexOf(toRemove);
  25518. if (index !== -1) {
  25519. this.animations.splice(index, 1);
  25520. }
  25521. return index;
  25522. };
  25523. /**
  25524. * Removes the given animation group from this scene.
  25525. * @param toRemove The animation group to remove
  25526. * @returns The index of the removed animation group
  25527. */
  25528. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25529. var index = this.animationGroups.indexOf(toRemove);
  25530. if (index !== -1) {
  25531. this.animationGroups.splice(index, 1);
  25532. }
  25533. return index;
  25534. };
  25535. /**
  25536. * Removes the given multi-material from this scene.
  25537. * @param toRemove The multi-material to remove
  25538. * @returns The index of the removed multi-material
  25539. */
  25540. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25541. var index = this.multiMaterials.indexOf(toRemove);
  25542. if (index !== -1) {
  25543. this.multiMaterials.splice(index, 1);
  25544. }
  25545. return index;
  25546. };
  25547. /**
  25548. * Removes the given material from this scene.
  25549. * @param toRemove The material to remove
  25550. * @returns The index of the removed material
  25551. */
  25552. Scene.prototype.removeMaterial = function (toRemove) {
  25553. var index = this.materials.indexOf(toRemove);
  25554. if (index !== -1) {
  25555. this.materials.splice(index, 1);
  25556. }
  25557. return index;
  25558. };
  25559. /**
  25560. * Removes the given lens flare system from this scene.
  25561. * @param toRemove The lens flare system to remove
  25562. * @returns The index of the removed lens flare system
  25563. */
  25564. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25565. var index = this.lensFlareSystems.indexOf(toRemove);
  25566. if (index !== -1) {
  25567. this.lensFlareSystems.splice(index, 1);
  25568. }
  25569. return index;
  25570. };
  25571. /**
  25572. * Removes the given action manager from this scene.
  25573. * @param toRemove The action manager to remove
  25574. * @returns The index of the removed action manager
  25575. */
  25576. Scene.prototype.removeActionManager = function (toRemove) {
  25577. var index = this._actionManagers.indexOf(toRemove);
  25578. if (index !== -1) {
  25579. this._actionManagers.splice(index, 1);
  25580. }
  25581. return index;
  25582. };
  25583. /**
  25584. * Removes the given effect layer from this scene.
  25585. * @param toRemove defines the effect layer to remove
  25586. * @returns the index of the removed effect layer
  25587. */
  25588. Scene.prototype.removeEffectLayer = function (toRemove) {
  25589. var index = this.effectLayers.indexOf(toRemove);
  25590. if (index !== -1) {
  25591. this.effectLayers.splice(index, 1);
  25592. }
  25593. return index;
  25594. };
  25595. /**
  25596. * Removes the given texture from this scene.
  25597. * @param toRemove The texture to remove
  25598. * @returns The index of the removed texture
  25599. */
  25600. Scene.prototype.removeTexture = function (toRemove) {
  25601. var index = this.textures.indexOf(toRemove);
  25602. if (index !== -1) {
  25603. this.textures.splice(index, 1);
  25604. }
  25605. return index;
  25606. };
  25607. /**
  25608. * Adds the given light to this scene
  25609. * @param newLight The light to add
  25610. */
  25611. Scene.prototype.addLight = function (newLight) {
  25612. this.lights.push(newLight);
  25613. this.sortLightsByPriority();
  25614. // Add light to all meshes (To support if the light is removed and then readded)
  25615. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25616. var mesh = _a[_i];
  25617. if (mesh._lightSources.indexOf(newLight) === -1) {
  25618. mesh._lightSources.push(newLight);
  25619. mesh._resyncLightSources();
  25620. }
  25621. }
  25622. this.onNewLightAddedObservable.notifyObservers(newLight);
  25623. };
  25624. /**
  25625. * Sorts the list list based on light priorities
  25626. */
  25627. Scene.prototype.sortLightsByPriority = function () {
  25628. if (this.requireLightSorting) {
  25629. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25630. }
  25631. };
  25632. /**
  25633. * Adds the given camera to this scene
  25634. * @param newCamera The camera to add
  25635. */
  25636. Scene.prototype.addCamera = function (newCamera) {
  25637. this.cameras.push(newCamera);
  25638. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25639. };
  25640. /**
  25641. * Adds the given skeleton to this scene
  25642. * @param newSkeleton The skeleton to add
  25643. */
  25644. Scene.prototype.addSkeleton = function (newSkeleton) {
  25645. this.skeletons.push(newSkeleton);
  25646. };
  25647. /**
  25648. * Adds the given particle system to this scene
  25649. * @param newParticleSystem The particle system to add
  25650. */
  25651. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25652. this.particleSystems.push(newParticleSystem);
  25653. };
  25654. /**
  25655. * Adds the given animation to this scene
  25656. * @param newAnimation The animation to add
  25657. */
  25658. Scene.prototype.addAnimation = function (newAnimation) {
  25659. this.animations.push(newAnimation);
  25660. };
  25661. /**
  25662. * Adds the given animation group to this scene.
  25663. * @param newAnimationGroup The animation group to add
  25664. */
  25665. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25666. this.animationGroups.push(newAnimationGroup);
  25667. };
  25668. /**
  25669. * Adds the given multi-material to this scene
  25670. * @param newMultiMaterial The multi-material to add
  25671. */
  25672. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25673. this.multiMaterials.push(newMultiMaterial);
  25674. };
  25675. /**
  25676. * Adds the given material to this scene
  25677. * @param newMaterial The material to add
  25678. */
  25679. Scene.prototype.addMaterial = function (newMaterial) {
  25680. this.materials.push(newMaterial);
  25681. };
  25682. /**
  25683. * Adds the given morph target to this scene
  25684. * @param newMorphTargetManager The morph target to add
  25685. */
  25686. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25687. this.morphTargetManagers.push(newMorphTargetManager);
  25688. };
  25689. /**
  25690. * Adds the given geometry to this scene
  25691. * @param newGeometry The geometry to add
  25692. */
  25693. Scene.prototype.addGeometry = function (newGeometry) {
  25694. this._geometries.push(newGeometry);
  25695. };
  25696. /**
  25697. * Adds the given lens flare system to this scene
  25698. * @param newLensFlareSystem The lens flare system to add
  25699. */
  25700. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  25701. this.lensFlareSystems.push(newLensFlareSystem);
  25702. };
  25703. /**
  25704. * Adds the given effect layer to this scene
  25705. * @param newEffectLayer defines the effect layer to add
  25706. */
  25707. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  25708. this.effectLayers.push(newEffectLayer);
  25709. };
  25710. /**
  25711. * Adds the given action manager to this scene
  25712. * @param newActionManager The action manager to add
  25713. */
  25714. Scene.prototype.addActionManager = function (newActionManager) {
  25715. this._actionManagers.push(newActionManager);
  25716. };
  25717. /**
  25718. * Adds the given texture to this scene.
  25719. * @param newTexture The texture to add
  25720. */
  25721. Scene.prototype.addTexture = function (newTexture) {
  25722. this.textures.push(newTexture);
  25723. };
  25724. /**
  25725. * Switch active camera
  25726. * @param newCamera defines the new active camera
  25727. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  25728. */
  25729. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  25730. if (attachControl === void 0) { attachControl = true; }
  25731. var canvas = this._engine.getRenderingCanvas();
  25732. if (!canvas) {
  25733. return;
  25734. }
  25735. if (this.activeCamera) {
  25736. this.activeCamera.detachControl(canvas);
  25737. }
  25738. this.activeCamera = newCamera;
  25739. if (attachControl) {
  25740. newCamera.attachControl(canvas);
  25741. }
  25742. };
  25743. /**
  25744. * sets the active camera of the scene using its ID
  25745. * @param id defines the camera's ID
  25746. * @return the new active camera or null if none found.
  25747. */
  25748. Scene.prototype.setActiveCameraByID = function (id) {
  25749. var camera = this.getCameraByID(id);
  25750. if (camera) {
  25751. this.activeCamera = camera;
  25752. return camera;
  25753. }
  25754. return null;
  25755. };
  25756. /**
  25757. * sets the active camera of the scene using its name
  25758. * @param name defines the camera's name
  25759. * @returns the new active camera or null if none found.
  25760. */
  25761. Scene.prototype.setActiveCameraByName = function (name) {
  25762. var camera = this.getCameraByName(name);
  25763. if (camera) {
  25764. this.activeCamera = camera;
  25765. return camera;
  25766. }
  25767. return null;
  25768. };
  25769. /**
  25770. * get an animation group using its name
  25771. * @param name defines the material's name
  25772. * @return the animation group or null if none found.
  25773. */
  25774. Scene.prototype.getAnimationGroupByName = function (name) {
  25775. for (var index = 0; index < this.animationGroups.length; index++) {
  25776. if (this.animationGroups[index].name === name) {
  25777. return this.animationGroups[index];
  25778. }
  25779. }
  25780. return null;
  25781. };
  25782. /**
  25783. * get a material using its id
  25784. * @param id defines the material's ID
  25785. * @return the material or null if none found.
  25786. */
  25787. Scene.prototype.getMaterialByID = function (id) {
  25788. for (var index = 0; index < this.materials.length; index++) {
  25789. if (this.materials[index].id === id) {
  25790. return this.materials[index];
  25791. }
  25792. }
  25793. return null;
  25794. };
  25795. /**
  25796. * Gets a material using its name
  25797. * @param name defines the material's name
  25798. * @return the material or null if none found.
  25799. */
  25800. Scene.prototype.getMaterialByName = function (name) {
  25801. for (var index = 0; index < this.materials.length; index++) {
  25802. if (this.materials[index].name === name) {
  25803. return this.materials[index];
  25804. }
  25805. }
  25806. return null;
  25807. };
  25808. /**
  25809. * Gets a lens flare system using its name
  25810. * @param name defines the name to look for
  25811. * @returns the lens flare system or null if not found
  25812. */
  25813. Scene.prototype.getLensFlareSystemByName = function (name) {
  25814. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25815. if (this.lensFlareSystems[index].name === name) {
  25816. return this.lensFlareSystems[index];
  25817. }
  25818. }
  25819. return null;
  25820. };
  25821. /**
  25822. * Gets a lens flare system using its id
  25823. * @param id defines the id to look for
  25824. * @returns the lens flare system or null if not found
  25825. */
  25826. Scene.prototype.getLensFlareSystemByID = function (id) {
  25827. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  25828. if (this.lensFlareSystems[index].id === id) {
  25829. return this.lensFlareSystems[index];
  25830. }
  25831. }
  25832. return null;
  25833. };
  25834. /**
  25835. * Gets a camera using its id
  25836. * @param id defines the id to look for
  25837. * @returns the camera or null if not found
  25838. */
  25839. Scene.prototype.getCameraByID = function (id) {
  25840. for (var index = 0; index < this.cameras.length; index++) {
  25841. if (this.cameras[index].id === id) {
  25842. return this.cameras[index];
  25843. }
  25844. }
  25845. return null;
  25846. };
  25847. /**
  25848. * Gets a camera using its unique id
  25849. * @param uniqueId defines the unique id to look for
  25850. * @returns the camera or null if not found
  25851. */
  25852. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  25853. for (var index = 0; index < this.cameras.length; index++) {
  25854. if (this.cameras[index].uniqueId === uniqueId) {
  25855. return this.cameras[index];
  25856. }
  25857. }
  25858. return null;
  25859. };
  25860. /**
  25861. * Gets a camera using its name
  25862. * @param name defines the camera's name
  25863. * @return the camera or null if none found.
  25864. */
  25865. Scene.prototype.getCameraByName = function (name) {
  25866. for (var index = 0; index < this.cameras.length; index++) {
  25867. if (this.cameras[index].name === name) {
  25868. return this.cameras[index];
  25869. }
  25870. }
  25871. return null;
  25872. };
  25873. /**
  25874. * Gets a bone using its id
  25875. * @param id defines the bone's id
  25876. * @return the bone or null if not found
  25877. */
  25878. Scene.prototype.getBoneByID = function (id) {
  25879. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25880. var skeleton = this.skeletons[skeletonIndex];
  25881. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25882. if (skeleton.bones[boneIndex].id === id) {
  25883. return skeleton.bones[boneIndex];
  25884. }
  25885. }
  25886. }
  25887. return null;
  25888. };
  25889. /**
  25890. * Gets a bone using its id
  25891. * @param name defines the bone's name
  25892. * @return the bone or null if not found
  25893. */
  25894. Scene.prototype.getBoneByName = function (name) {
  25895. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  25896. var skeleton = this.skeletons[skeletonIndex];
  25897. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  25898. if (skeleton.bones[boneIndex].name === name) {
  25899. return skeleton.bones[boneIndex];
  25900. }
  25901. }
  25902. }
  25903. return null;
  25904. };
  25905. /**
  25906. * Gets a light node using its name
  25907. * @param name defines the the light's name
  25908. * @return the light or null if none found.
  25909. */
  25910. Scene.prototype.getLightByName = function (name) {
  25911. for (var index = 0; index < this.lights.length; index++) {
  25912. if (this.lights[index].name === name) {
  25913. return this.lights[index];
  25914. }
  25915. }
  25916. return null;
  25917. };
  25918. /**
  25919. * Gets a light node using its id
  25920. * @param id defines the light's id
  25921. * @return the light or null if none found.
  25922. */
  25923. Scene.prototype.getLightByID = function (id) {
  25924. for (var index = 0; index < this.lights.length; index++) {
  25925. if (this.lights[index].id === id) {
  25926. return this.lights[index];
  25927. }
  25928. }
  25929. return null;
  25930. };
  25931. /**
  25932. * Gets a light node using its scene-generated unique ID
  25933. * @param uniqueId defines the light's unique id
  25934. * @return the light or null if none found.
  25935. */
  25936. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  25937. for (var index = 0; index < this.lights.length; index++) {
  25938. if (this.lights[index].uniqueId === uniqueId) {
  25939. return this.lights[index];
  25940. }
  25941. }
  25942. return null;
  25943. };
  25944. /**
  25945. * Gets a particle system by id
  25946. * @param id defines the particle system id
  25947. * @return the corresponding system or null if none found
  25948. */
  25949. Scene.prototype.getParticleSystemByID = function (id) {
  25950. for (var index = 0; index < this.particleSystems.length; index++) {
  25951. if (this.particleSystems[index].id === id) {
  25952. return this.particleSystems[index];
  25953. }
  25954. }
  25955. return null;
  25956. };
  25957. /**
  25958. * Gets a geometry using its ID
  25959. * @param id defines the geometry's id
  25960. * @return the geometry or null if none found.
  25961. */
  25962. Scene.prototype.getGeometryByID = function (id) {
  25963. for (var index = 0; index < this._geometries.length; index++) {
  25964. if (this._geometries[index].id === id) {
  25965. return this._geometries[index];
  25966. }
  25967. }
  25968. return null;
  25969. };
  25970. /**
  25971. * Add a new geometry to this scene
  25972. * @param geometry defines the geometry to be added to the scene.
  25973. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  25974. * @return a boolean defining if the geometry was added or not
  25975. */
  25976. Scene.prototype.pushGeometry = function (geometry, force) {
  25977. if (!force && this.getGeometryByID(geometry.id)) {
  25978. return false;
  25979. }
  25980. this._geometries.push(geometry);
  25981. //notify the collision coordinator
  25982. if (this.collisionCoordinator) {
  25983. this.collisionCoordinator.onGeometryAdded(geometry);
  25984. }
  25985. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  25986. return true;
  25987. };
  25988. /**
  25989. * Removes an existing geometry
  25990. * @param geometry defines the geometry to be removed from the scene
  25991. * @return a boolean defining if the geometry was removed or not
  25992. */
  25993. Scene.prototype.removeGeometry = function (geometry) {
  25994. var index = this._geometries.indexOf(geometry);
  25995. if (index > -1) {
  25996. this._geometries.splice(index, 1);
  25997. //notify the collision coordinator
  25998. if (this.collisionCoordinator) {
  25999. this.collisionCoordinator.onGeometryDeleted(geometry);
  26000. }
  26001. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26002. return true;
  26003. }
  26004. return false;
  26005. };
  26006. /**
  26007. * Gets the list of geometries attached to the scene
  26008. * @returns an array of Geometry
  26009. */
  26010. Scene.prototype.getGeometries = function () {
  26011. return this._geometries;
  26012. };
  26013. /**
  26014. * Gets the first added mesh found of a given ID
  26015. * @param id defines the id to search for
  26016. * @return the mesh found or null if not found at all
  26017. */
  26018. Scene.prototype.getMeshByID = function (id) {
  26019. for (var index = 0; index < this.meshes.length; index++) {
  26020. if (this.meshes[index].id === id) {
  26021. return this.meshes[index];
  26022. }
  26023. }
  26024. return null;
  26025. };
  26026. /**
  26027. * Gets a list of meshes using their id
  26028. * @param id defines the id to search for
  26029. * @returns a list of meshes
  26030. */
  26031. Scene.prototype.getMeshesByID = function (id) {
  26032. return this.meshes.filter(function (m) {
  26033. return m.id === id;
  26034. });
  26035. };
  26036. /**
  26037. * Gets the first added transform node found of a given ID
  26038. * @param id defines the id to search for
  26039. * @return the found transform node or null if not found at all.
  26040. */
  26041. Scene.prototype.getTransformNodeByID = function (id) {
  26042. for (var index = 0; index < this.transformNodes.length; index++) {
  26043. if (this.transformNodes[index].id === id) {
  26044. return this.transformNodes[index];
  26045. }
  26046. }
  26047. return null;
  26048. };
  26049. /**
  26050. * Gets a list of transform nodes using their id
  26051. * @param id defines the id to search for
  26052. * @returns a list of transform nodes
  26053. */
  26054. Scene.prototype.getTransformNodesByID = function (id) {
  26055. return this.transformNodes.filter(function (m) {
  26056. return m.id === id;
  26057. });
  26058. };
  26059. /**
  26060. * Gets a mesh with its auto-generated unique id
  26061. * @param uniqueId defines the unique id to search for
  26062. * @return the found mesh or null if not found at all.
  26063. */
  26064. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26065. for (var index = 0; index < this.meshes.length; index++) {
  26066. if (this.meshes[index].uniqueId === uniqueId) {
  26067. return this.meshes[index];
  26068. }
  26069. }
  26070. return null;
  26071. };
  26072. /**
  26073. * Gets a the last added mesh using a given id
  26074. * @param id defines the id to search for
  26075. * @return the found mesh or null if not found at all.
  26076. */
  26077. Scene.prototype.getLastMeshByID = function (id) {
  26078. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26079. if (this.meshes[index].id === id) {
  26080. return this.meshes[index];
  26081. }
  26082. }
  26083. return null;
  26084. };
  26085. /**
  26086. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26087. * @param id defines the id to search for
  26088. * @return the found node or null if not found at all
  26089. */
  26090. Scene.prototype.getLastEntryByID = function (id) {
  26091. var index;
  26092. for (index = this.meshes.length - 1; index >= 0; index--) {
  26093. if (this.meshes[index].id === id) {
  26094. return this.meshes[index];
  26095. }
  26096. }
  26097. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26098. if (this.transformNodes[index].id === id) {
  26099. return this.transformNodes[index];
  26100. }
  26101. }
  26102. for (index = this.cameras.length - 1; index >= 0; index--) {
  26103. if (this.cameras[index].id === id) {
  26104. return this.cameras[index];
  26105. }
  26106. }
  26107. for (index = this.lights.length - 1; index >= 0; index--) {
  26108. if (this.lights[index].id === id) {
  26109. return this.lights[index];
  26110. }
  26111. }
  26112. return null;
  26113. };
  26114. /**
  26115. * Gets a node (Mesh, Camera, Light) using a given id
  26116. * @param id defines the id to search for
  26117. * @return the found node or null if not found at all
  26118. */
  26119. Scene.prototype.getNodeByID = function (id) {
  26120. var mesh = this.getMeshByID(id);
  26121. if (mesh) {
  26122. return mesh;
  26123. }
  26124. var light = this.getLightByID(id);
  26125. if (light) {
  26126. return light;
  26127. }
  26128. var camera = this.getCameraByID(id);
  26129. if (camera) {
  26130. return camera;
  26131. }
  26132. var bone = this.getBoneByID(id);
  26133. return bone;
  26134. };
  26135. /**
  26136. * Gets a node (Mesh, Camera, Light) using a given name
  26137. * @param name defines the name to search for
  26138. * @return the found node or null if not found at all.
  26139. */
  26140. Scene.prototype.getNodeByName = function (name) {
  26141. var mesh = this.getMeshByName(name);
  26142. if (mesh) {
  26143. return mesh;
  26144. }
  26145. var light = this.getLightByName(name);
  26146. if (light) {
  26147. return light;
  26148. }
  26149. var camera = this.getCameraByName(name);
  26150. if (camera) {
  26151. return camera;
  26152. }
  26153. var bone = this.getBoneByName(name);
  26154. return bone;
  26155. };
  26156. /**
  26157. * Gets a mesh using a given name
  26158. * @param name defines the name to search for
  26159. * @return the found mesh or null if not found at all.
  26160. */
  26161. Scene.prototype.getMeshByName = function (name) {
  26162. for (var index = 0; index < this.meshes.length; index++) {
  26163. if (this.meshes[index].name === name) {
  26164. return this.meshes[index];
  26165. }
  26166. }
  26167. return null;
  26168. };
  26169. /**
  26170. * Gets a transform node using a given name
  26171. * @param name defines the name to search for
  26172. * @return the found transform node or null if not found at all.
  26173. */
  26174. Scene.prototype.getTransformNodeByName = function (name) {
  26175. for (var index = 0; index < this.transformNodes.length; index++) {
  26176. if (this.transformNodes[index].name === name) {
  26177. return this.transformNodes[index];
  26178. }
  26179. }
  26180. return null;
  26181. };
  26182. /**
  26183. * Gets a sound using a given name
  26184. * @param name defines the name to search for
  26185. * @return the found sound or null if not found at all.
  26186. */
  26187. Scene.prototype.getSoundByName = function (name) {
  26188. var index;
  26189. if (BABYLON.AudioEngine) {
  26190. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26191. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26192. return this.mainSoundTrack.soundCollection[index];
  26193. }
  26194. }
  26195. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26196. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26197. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26198. return this.soundTracks[sdIndex].soundCollection[index];
  26199. }
  26200. }
  26201. }
  26202. }
  26203. return null;
  26204. };
  26205. /**
  26206. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26207. * @param id defines the id to search for
  26208. * @return the found skeleton or null if not found at all.
  26209. */
  26210. Scene.prototype.getLastSkeletonByID = function (id) {
  26211. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26212. if (this.skeletons[index].id === id) {
  26213. return this.skeletons[index];
  26214. }
  26215. }
  26216. return null;
  26217. };
  26218. /**
  26219. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26220. * @param id defines the id to search for
  26221. * @return the found skeleton or null if not found at all.
  26222. */
  26223. Scene.prototype.getSkeletonById = function (id) {
  26224. for (var index = 0; index < this.skeletons.length; index++) {
  26225. if (this.skeletons[index].id === id) {
  26226. return this.skeletons[index];
  26227. }
  26228. }
  26229. return null;
  26230. };
  26231. /**
  26232. * Gets a skeleton using a given name
  26233. * @param name defines the name to search for
  26234. * @return the found skeleton or null if not found at all.
  26235. */
  26236. Scene.prototype.getSkeletonByName = function (name) {
  26237. for (var index = 0; index < this.skeletons.length; index++) {
  26238. if (this.skeletons[index].name === name) {
  26239. return this.skeletons[index];
  26240. }
  26241. }
  26242. return null;
  26243. };
  26244. /**
  26245. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26246. * @param id defines the id to search for
  26247. * @return the found morph target manager or null if not found at all.
  26248. */
  26249. Scene.prototype.getMorphTargetManagerById = function (id) {
  26250. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26251. if (this.morphTargetManagers[index].uniqueId === id) {
  26252. return this.morphTargetManagers[index];
  26253. }
  26254. }
  26255. return null;
  26256. };
  26257. /**
  26258. * Gets a boolean indicating if the given mesh is active
  26259. * @param mesh defines the mesh to look for
  26260. * @returns true if the mesh is in the active list
  26261. */
  26262. Scene.prototype.isActiveMesh = function (mesh) {
  26263. return (this._activeMeshes.indexOf(mesh) !== -1);
  26264. };
  26265. /**
  26266. * Return a the first highlight layer of the scene with a given name.
  26267. * @param name The name of the highlight layer to look for.
  26268. * @return The highlight layer if found otherwise null.
  26269. */
  26270. Scene.prototype.getHighlightLayerByName = function (name) {
  26271. for (var index = 0; index < this.effectLayers.length; index++) {
  26272. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26273. return this.effectLayers[index];
  26274. }
  26275. }
  26276. return null;
  26277. };
  26278. /**
  26279. * Return a the first highlight layer of the scene with a given name.
  26280. * @param name The name of the highlight layer to look for.
  26281. * @return The highlight layer if found otherwise null.
  26282. */
  26283. Scene.prototype.getGlowLayerByName = function (name) {
  26284. for (var index = 0; index < this.effectLayers.length; index++) {
  26285. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26286. return this.effectLayers[index];
  26287. }
  26288. }
  26289. return null;
  26290. };
  26291. Object.defineProperty(Scene.prototype, "uid", {
  26292. /**
  26293. * Return a unique id as a string which can serve as an identifier for the scene
  26294. */
  26295. get: function () {
  26296. if (!this._uid) {
  26297. this._uid = BABYLON.Tools.RandomId();
  26298. }
  26299. return this._uid;
  26300. },
  26301. enumerable: true,
  26302. configurable: true
  26303. });
  26304. /**
  26305. * Add an externaly attached data from its key.
  26306. * This method call will fail and return false, if such key already exists.
  26307. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26308. * @param key the unique key that identifies the data
  26309. * @param data the data object to associate to the key for this Engine instance
  26310. * @return true if no such key were already present and the data was added successfully, false otherwise
  26311. */
  26312. Scene.prototype.addExternalData = function (key, data) {
  26313. if (!this._externalData) {
  26314. this._externalData = new BABYLON.StringDictionary();
  26315. }
  26316. return this._externalData.add(key, data);
  26317. };
  26318. /**
  26319. * Get an externaly attached data from its key
  26320. * @param key the unique key that identifies the data
  26321. * @return the associated data, if present (can be null), or undefined if not present
  26322. */
  26323. Scene.prototype.getExternalData = function (key) {
  26324. if (!this._externalData) {
  26325. return null;
  26326. }
  26327. return this._externalData.get(key);
  26328. };
  26329. /**
  26330. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26331. * @param key the unique key that identifies the data
  26332. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26333. * @return the associated data, can be null if the factory returned null.
  26334. */
  26335. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26336. if (!this._externalData) {
  26337. this._externalData = new BABYLON.StringDictionary();
  26338. }
  26339. return this._externalData.getOrAddWithFactory(key, factory);
  26340. };
  26341. /**
  26342. * Remove an externaly attached data from the Engine instance
  26343. * @param key the unique key that identifies the data
  26344. * @return true if the data was successfully removed, false if it doesn't exist
  26345. */
  26346. Scene.prototype.removeExternalData = function (key) {
  26347. return this._externalData.remove(key);
  26348. };
  26349. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26350. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26351. if (mesh.showSubMeshesBoundingBox) {
  26352. var boundingInfo = subMesh.getBoundingInfo();
  26353. if (boundingInfo !== null && boundingInfo !== undefined) {
  26354. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26355. }
  26356. }
  26357. var material = subMesh.getMaterial();
  26358. if (material !== null && material !== undefined) {
  26359. // Render targets
  26360. if (material.getRenderTargetTextures !== undefined) {
  26361. if (this._processedMaterials.indexOf(material) === -1) {
  26362. this._processedMaterials.push(material);
  26363. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26364. }
  26365. }
  26366. // Dispatch
  26367. this._activeIndices.addCount(subMesh.indexCount, false);
  26368. this._renderingManager.dispatch(subMesh, mesh, material);
  26369. }
  26370. }
  26371. };
  26372. /**
  26373. * Clear the processed materials smart array preventing retention point in material dispose.
  26374. */
  26375. Scene.prototype.freeProcessedMaterials = function () {
  26376. this._processedMaterials.dispose();
  26377. };
  26378. /**
  26379. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26380. */
  26381. Scene.prototype.freeActiveMeshes = function () {
  26382. this._activeMeshes.dispose();
  26383. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26384. this.activeCamera._activeMeshes.dispose();
  26385. }
  26386. if (this.activeCameras) {
  26387. for (var i = 0; i < this.activeCameras.length; i++) {
  26388. var activeCamera = this.activeCameras[i];
  26389. if (activeCamera && activeCamera._activeMeshes) {
  26390. activeCamera._activeMeshes.dispose();
  26391. }
  26392. }
  26393. }
  26394. };
  26395. /**
  26396. * Clear the info related to rendering groups preventing retention points during dispose.
  26397. */
  26398. Scene.prototype.freeRenderingGroups = function () {
  26399. if (this._renderingManager) {
  26400. this._renderingManager.freeRenderingGroups();
  26401. }
  26402. if (this.textures) {
  26403. for (var i = 0; i < this.textures.length; i++) {
  26404. var texture = this.textures[i];
  26405. if (texture && texture.renderList) {
  26406. texture.freeRenderingGroups();
  26407. }
  26408. }
  26409. }
  26410. };
  26411. /** @ignore */
  26412. Scene.prototype._isInIntermediateRendering = function () {
  26413. return this._intermediateRendering;
  26414. };
  26415. /**
  26416. * Defines the current active mesh candidate provider
  26417. * @param provider defines the provider to use
  26418. */
  26419. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26420. this._activeMeshCandidateProvider = provider;
  26421. };
  26422. /**
  26423. * Gets the current active mesh candidate provider
  26424. * @returns the current active mesh candidate provider
  26425. */
  26426. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26427. return this._activeMeshCandidateProvider;
  26428. };
  26429. /**
  26430. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26431. * @returns the current scene
  26432. */
  26433. Scene.prototype.freezeActiveMeshes = function () {
  26434. if (!this.activeCamera) {
  26435. return this;
  26436. }
  26437. if (!this._frustumPlanes) {
  26438. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26439. }
  26440. this._evaluateActiveMeshes();
  26441. this._activeMeshesFrozen = true;
  26442. return this;
  26443. };
  26444. /**
  26445. * Use this function to restart evaluating active meshes on every frame
  26446. * @returns the current scene
  26447. */
  26448. Scene.prototype.unfreezeActiveMeshes = function () {
  26449. this._activeMeshesFrozen = false;
  26450. return this;
  26451. };
  26452. Scene.prototype._evaluateActiveMeshes = function () {
  26453. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26454. return;
  26455. }
  26456. if (!this.activeCamera) {
  26457. return;
  26458. }
  26459. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26460. this.activeCamera._activeMeshes.reset();
  26461. this._activeMeshes.reset();
  26462. this._renderingManager.reset();
  26463. this._processedMaterials.reset();
  26464. this._activeParticleSystems.reset();
  26465. this._activeSkeletons.reset();
  26466. this._softwareSkinnedMeshes.reset();
  26467. if (this._boundingBoxRenderer) {
  26468. this._boundingBoxRenderer.reset();
  26469. }
  26470. // Meshes
  26471. var meshes;
  26472. var len;
  26473. var checkIsEnabled = true;
  26474. // Determine mesh candidates
  26475. if (this._activeMeshCandidateProvider !== undefined) {
  26476. // Use _activeMeshCandidateProvider
  26477. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26478. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26479. if (meshes !== undefined) {
  26480. len = meshes.length;
  26481. }
  26482. else {
  26483. len = 0;
  26484. }
  26485. }
  26486. else if (this._selectionOctree !== undefined) {
  26487. // Octree
  26488. var selection = this._selectionOctree.select(this._frustumPlanes);
  26489. meshes = selection.data;
  26490. len = selection.length;
  26491. }
  26492. else {
  26493. // Full scene traversal
  26494. len = this.meshes.length;
  26495. meshes = this.meshes;
  26496. }
  26497. // Check each mesh
  26498. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26499. mesh = meshes[meshIndex];
  26500. if (mesh.isBlocked) {
  26501. continue;
  26502. }
  26503. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26504. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26505. continue;
  26506. }
  26507. mesh.computeWorldMatrix();
  26508. // Intersections
  26509. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26510. this._meshesForIntersections.pushNoDuplicate(mesh);
  26511. }
  26512. // Switch to current LOD
  26513. meshLOD = mesh.getLOD(this.activeCamera);
  26514. if (meshLOD === undefined || meshLOD === null) {
  26515. continue;
  26516. }
  26517. mesh._preActivate();
  26518. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26519. this._activeMeshes.push(mesh);
  26520. this.activeCamera._activeMeshes.push(mesh);
  26521. mesh._activate(this._renderId);
  26522. if (meshLOD !== mesh) {
  26523. meshLOD._activate(this._renderId);
  26524. }
  26525. this._activeMesh(mesh, meshLOD);
  26526. }
  26527. }
  26528. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26529. // Particle systems
  26530. if (this.particlesEnabled) {
  26531. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26532. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26533. var particleSystem = this.particleSystems[particleIndex];
  26534. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26535. continue;
  26536. }
  26537. var emitter = particleSystem.emitter;
  26538. if (!emitter.position || emitter.isEnabled()) {
  26539. this._activeParticleSystems.push(particleSystem);
  26540. particleSystem.animate();
  26541. this._renderingManager.dispatchParticles(particleSystem);
  26542. }
  26543. }
  26544. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26545. }
  26546. };
  26547. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26548. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26549. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26550. mesh.skeleton.prepare();
  26551. }
  26552. if (!mesh.computeBonesUsingShaders) {
  26553. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26554. }
  26555. }
  26556. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26557. var boundingInfo = sourceMesh.getBoundingInfo();
  26558. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26559. }
  26560. if (mesh !== undefined && mesh !== null
  26561. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26562. // Submeshes Octrees
  26563. var len;
  26564. var subMeshes;
  26565. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26566. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26567. len = intersections.length;
  26568. subMeshes = intersections.data;
  26569. }
  26570. else {
  26571. subMeshes = mesh.subMeshes;
  26572. len = subMeshes.length;
  26573. }
  26574. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26575. subMesh = subMeshes[subIndex];
  26576. this._evaluateSubMesh(subMesh, mesh);
  26577. }
  26578. }
  26579. };
  26580. /**
  26581. * Update the transform matrix to update from the current active camera
  26582. * @param force defines a boolean used to force the update even if cache is up to date
  26583. */
  26584. Scene.prototype.updateTransformMatrix = function (force) {
  26585. if (!this.activeCamera) {
  26586. return;
  26587. }
  26588. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26589. };
  26590. /**
  26591. * 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)
  26592. * @param alternateCamera defines the camera to use
  26593. */
  26594. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26595. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26596. };
  26597. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26598. if (camera && camera._skipRendering) {
  26599. return;
  26600. }
  26601. var engine = this._engine;
  26602. this.activeCamera = camera;
  26603. if (!this.activeCamera)
  26604. throw new Error("Active camera not set");
  26605. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26606. // Viewport
  26607. engine.setViewport(this.activeCamera.viewport);
  26608. // Camera
  26609. this.resetCachedMaterial();
  26610. this._renderId++;
  26611. this.updateTransformMatrix();
  26612. if (camera._alternateCamera) {
  26613. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26614. this._alternateRendering = true;
  26615. }
  26616. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26617. // Meshes
  26618. this._evaluateActiveMeshes();
  26619. // Software skinning
  26620. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26621. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26622. mesh.applySkeleton(mesh.skeleton);
  26623. }
  26624. // Render targets
  26625. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26626. var needsRestoreFrameBuffer = false;
  26627. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26628. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26629. }
  26630. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26631. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26632. }
  26633. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26634. this._intermediateRendering = true;
  26635. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26636. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26637. var renderTarget = this._renderTargets.data[renderIndex];
  26638. if (renderTarget._shouldRender()) {
  26639. this._renderId++;
  26640. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26641. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26642. }
  26643. }
  26644. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26645. this._intermediateRendering = false;
  26646. this._renderId++;
  26647. needsRestoreFrameBuffer = true; // Restore back buffer
  26648. }
  26649. // Render EffecttLayer Texture
  26650. var stencilState = this._engine.getStencilBuffer();
  26651. var renderEffects = false;
  26652. var needStencil = false;
  26653. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26654. this._intermediateRendering = true;
  26655. for (var i = 0; i < this.effectLayers.length; i++) {
  26656. var effectLayer = this.effectLayers[i];
  26657. if (effectLayer.shouldRender() &&
  26658. (!effectLayer.camera ||
  26659. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26660. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26661. renderEffects = true;
  26662. needStencil = needStencil || effectLayer.needStencil();
  26663. var renderTarget = effectLayer._mainTexture;
  26664. if (renderTarget._shouldRender()) {
  26665. this._renderId++;
  26666. renderTarget.render(false, false);
  26667. needsRestoreFrameBuffer = true;
  26668. }
  26669. }
  26670. }
  26671. this._intermediateRendering = false;
  26672. this._renderId++;
  26673. }
  26674. if (needsRestoreFrameBuffer) {
  26675. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26676. }
  26677. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26678. // Prepare Frame
  26679. this.postProcessManager._prepareFrame();
  26680. // Backgrounds
  26681. var layerIndex;
  26682. var layer;
  26683. if (this.layers.length) {
  26684. engine.setDepthBuffer(false);
  26685. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26686. layer = this.layers[layerIndex];
  26687. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26688. layer.render();
  26689. }
  26690. }
  26691. engine.setDepthBuffer(true);
  26692. }
  26693. // Activate effect Layer stencil
  26694. if (needStencil) {
  26695. this._engine.setStencilBuffer(true);
  26696. }
  26697. // Render
  26698. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26699. this._renderingManager.render(null, null, true, true);
  26700. this.onAfterDrawPhaseObservable.notifyObservers(this);
  26701. // Restore effect Layer stencil
  26702. if (needStencil) {
  26703. this._engine.setStencilBuffer(stencilState);
  26704. }
  26705. // Bounding boxes
  26706. if (this._boundingBoxRenderer) {
  26707. this._boundingBoxRenderer.render();
  26708. }
  26709. // Lens flares
  26710. if (this.lensFlaresEnabled) {
  26711. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26712. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  26713. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  26714. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  26715. lensFlareSystem.render();
  26716. }
  26717. }
  26718. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  26719. }
  26720. // Effect Layer
  26721. if (renderEffects) {
  26722. engine.setDepthBuffer(false);
  26723. for (var i = 0; i < this.effectLayers.length; i++) {
  26724. if (this.effectLayers[i].shouldRender()) {
  26725. this.effectLayers[i].render();
  26726. }
  26727. }
  26728. engine.setDepthBuffer(true);
  26729. }
  26730. // Foregrounds
  26731. if (this.layers.length) {
  26732. engine.setDepthBuffer(false);
  26733. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26734. layer = this.layers[layerIndex];
  26735. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26736. layer.render();
  26737. }
  26738. }
  26739. engine.setDepthBuffer(true);
  26740. }
  26741. // Finalize frame
  26742. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  26743. // Reset some special arrays
  26744. this._renderTargets.reset();
  26745. this._alternateRendering = false;
  26746. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  26747. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26748. };
  26749. Scene.prototype._processSubCameras = function (camera) {
  26750. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  26751. this._renderForCamera(camera);
  26752. return;
  26753. }
  26754. // rig cameras
  26755. for (var index = 0; index < camera._rigCameras.length; index++) {
  26756. this._renderForCamera(camera._rigCameras[index], camera);
  26757. }
  26758. this.activeCamera = camera;
  26759. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26760. };
  26761. Scene.prototype._checkIntersections = function () {
  26762. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  26763. var sourceMesh = this._meshesForIntersections.data[index];
  26764. if (!sourceMesh.actionManager) {
  26765. continue;
  26766. }
  26767. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  26768. var action = sourceMesh.actionManager.actions[actionIndex];
  26769. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26770. var parameters = action.getTriggerParameter();
  26771. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  26772. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  26773. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  26774. if (areIntersecting && currentIntersectionInProgress === -1) {
  26775. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  26776. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26777. sourceMesh._intersectionsInProgress.push(otherMesh);
  26778. }
  26779. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26780. sourceMesh._intersectionsInProgress.push(otherMesh);
  26781. }
  26782. }
  26783. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  26784. //They intersected, and now they don't.
  26785. //is this trigger an exit trigger? execute an event.
  26786. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26787. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  26788. }
  26789. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  26790. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  26791. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  26792. return otherMesh === parameterMesh;
  26793. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  26794. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  26795. }
  26796. }
  26797. }
  26798. }
  26799. }
  26800. };
  26801. /**
  26802. * Render the scene
  26803. */
  26804. Scene.prototype.render = function () {
  26805. if (this.isDisposed) {
  26806. return;
  26807. }
  26808. this._activeParticles.fetchNewFrame();
  26809. this._totalVertices.fetchNewFrame();
  26810. this._activeIndices.fetchNewFrame();
  26811. this._activeBones.fetchNewFrame();
  26812. this._meshesForIntersections.reset();
  26813. this.resetCachedMaterial();
  26814. this.onBeforeAnimationsObservable.notifyObservers(this);
  26815. // Actions
  26816. if (this.actionManager) {
  26817. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  26818. }
  26819. //Simplification Queue
  26820. if (this.simplificationQueue && !this.simplificationQueue.running) {
  26821. this.simplificationQueue.executeNext();
  26822. }
  26823. if (this._engine.isDeterministicLockStep()) {
  26824. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  26825. var defaultFPS = (60.0 / 1000.0);
  26826. var defaultFrameTime = 1000 / 60; // frame time in MS
  26827. if (this._physicsEngine) {
  26828. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  26829. }
  26830. var stepsTaken = 0;
  26831. var maxSubSteps = this._engine.getLockstepMaxSteps();
  26832. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  26833. internalSteps = Math.min(internalSteps, maxSubSteps);
  26834. do {
  26835. this.onBeforeStepObservable.notifyObservers(this);
  26836. // Animations
  26837. this._animationRatio = defaultFrameTime * defaultFPS;
  26838. this._animate();
  26839. this.onAfterAnimationsObservable.notifyObservers(this);
  26840. // Physics
  26841. if (this._physicsEngine) {
  26842. this.onBeforePhysicsObservable.notifyObservers(this);
  26843. this._physicsEngine._step(defaultFrameTime / 1000);
  26844. this.onAfterPhysicsObservable.notifyObservers(this);
  26845. }
  26846. this.onAfterStepObservable.notifyObservers(this);
  26847. this._currentStepId++;
  26848. stepsTaken++;
  26849. deltaTime -= defaultFrameTime;
  26850. } while (deltaTime > 0 && stepsTaken < internalSteps);
  26851. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  26852. }
  26853. else {
  26854. // Animations
  26855. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  26856. this._animationRatio = deltaTime * (60.0 / 1000.0);
  26857. this._animate();
  26858. this.onAfterAnimationsObservable.notifyObservers(this);
  26859. // Physics
  26860. if (this._physicsEngine) {
  26861. this.onBeforePhysicsObservable.notifyObservers(this);
  26862. this._physicsEngine._step(deltaTime / 1000.0);
  26863. this.onAfterPhysicsObservable.notifyObservers(this);
  26864. }
  26865. }
  26866. // update gamepad manager
  26867. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  26868. this._gamepadManager._checkGamepadsStatus();
  26869. }
  26870. // Update Cameras
  26871. if (this.activeCameras.length > 0) {
  26872. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26873. var camera = this.activeCameras[cameraIndex];
  26874. camera.update();
  26875. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26876. // rig cameras
  26877. for (var index = 0; index < camera._rigCameras.length; index++) {
  26878. camera._rigCameras[index].update();
  26879. }
  26880. }
  26881. }
  26882. }
  26883. else if (this.activeCamera) {
  26884. this.activeCamera.update();
  26885. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  26886. // rig cameras
  26887. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  26888. this.activeCamera._rigCameras[index].update();
  26889. }
  26890. }
  26891. }
  26892. // Before render
  26893. this.onBeforeRenderObservable.notifyObservers(this);
  26894. // Customs render targets
  26895. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26896. var engine = this.getEngine();
  26897. var currentActiveCamera = this.activeCamera;
  26898. if (this.renderTargetsEnabled) {
  26899. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26900. this._intermediateRendering = true;
  26901. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  26902. var renderTarget = this.customRenderTargets[customIndex];
  26903. if (renderTarget._shouldRender()) {
  26904. this._renderId++;
  26905. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  26906. if (!this.activeCamera)
  26907. throw new Error("Active camera not set");
  26908. // Viewport
  26909. engine.setViewport(this.activeCamera.viewport);
  26910. // Camera
  26911. this.updateTransformMatrix();
  26912. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  26913. }
  26914. }
  26915. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  26916. this._intermediateRendering = false;
  26917. this._renderId++;
  26918. }
  26919. // Restore back buffer
  26920. if (this.customRenderTargets.length > 0) {
  26921. engine.restoreDefaultFramebuffer();
  26922. }
  26923. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26924. this.activeCamera = currentActiveCamera;
  26925. // Procedural textures
  26926. if (this.proceduralTexturesEnabled) {
  26927. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26928. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  26929. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  26930. if (proceduralTexture._shouldRender()) {
  26931. proceduralTexture.render();
  26932. }
  26933. }
  26934. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  26935. }
  26936. // Clear
  26937. if (this.autoClearDepthAndStencil || this.autoClear) {
  26938. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  26939. }
  26940. // Shadows
  26941. if (this.shadowsEnabled) {
  26942. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  26943. var light = this.lights[lightIndex];
  26944. var shadowGenerator = light.getShadowGenerator();
  26945. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  26946. var shadowMap = (shadowGenerator.getShadowMap());
  26947. if (this.textures.indexOf(shadowMap) !== -1) {
  26948. this._renderTargets.push(shadowMap);
  26949. }
  26950. }
  26951. }
  26952. }
  26953. // Depth renderer
  26954. for (var key in this._depthRenderer) {
  26955. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  26956. }
  26957. // Geometry renderer
  26958. if (this._geometryBufferRenderer) {
  26959. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  26960. }
  26961. // RenderPipeline
  26962. if (this._postProcessRenderPipelineManager) {
  26963. this._postProcessRenderPipelineManager.update();
  26964. }
  26965. // Multi-cameras?
  26966. if (this.activeCameras.length > 0) {
  26967. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  26968. if (cameraIndex > 0) {
  26969. this._engine.clear(null, false, true, true);
  26970. }
  26971. this._processSubCameras(this.activeCameras[cameraIndex]);
  26972. }
  26973. }
  26974. else {
  26975. if (!this.activeCamera) {
  26976. throw new Error("No camera defined");
  26977. }
  26978. this._processSubCameras(this.activeCamera);
  26979. }
  26980. // Intersection checks
  26981. this._checkIntersections();
  26982. // Update the audio listener attached to the camera
  26983. if (BABYLON.AudioEngine) {
  26984. this._updateAudioParameters();
  26985. }
  26986. // After render
  26987. if (this.afterRender) {
  26988. this.afterRender();
  26989. }
  26990. this.onAfterRenderObservable.notifyObservers(this);
  26991. // Cleaning
  26992. for (var index = 0; index < this._toBeDisposed.length; index++) {
  26993. var data = this._toBeDisposed.data[index];
  26994. if (data) {
  26995. data.dispose();
  26996. }
  26997. this._toBeDisposed[index] = null;
  26998. }
  26999. this._toBeDisposed.reset();
  27000. if (this.dumpNextRenderTargets) {
  27001. this.dumpNextRenderTargets = false;
  27002. }
  27003. this._activeBones.addCount(0, true);
  27004. this._activeIndices.addCount(0, true);
  27005. this._activeParticles.addCount(0, true);
  27006. };
  27007. Scene.prototype._updateAudioParameters = function () {
  27008. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27009. return;
  27010. }
  27011. var listeningCamera;
  27012. var audioEngine = BABYLON.Engine.audioEngine;
  27013. if (this.activeCameras.length > 0) {
  27014. listeningCamera = this.activeCameras[0];
  27015. }
  27016. else {
  27017. listeningCamera = this.activeCamera;
  27018. }
  27019. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27020. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27021. // for VR cameras
  27022. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27023. listeningCamera = listeningCamera.rigCameras[0];
  27024. }
  27025. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27026. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27027. cameraDirection.normalize();
  27028. // To avoid some errors on GearVR
  27029. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27030. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27031. }
  27032. var i;
  27033. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27034. var sound = this.mainSoundTrack.soundCollection[i];
  27035. if (sound.useCustomAttenuation) {
  27036. sound.updateDistanceFromListener();
  27037. }
  27038. }
  27039. for (i = 0; i < this.soundTracks.length; i++) {
  27040. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27041. sound = this.soundTracks[i].soundCollection[j];
  27042. if (sound.useCustomAttenuation) {
  27043. sound.updateDistanceFromListener();
  27044. }
  27045. }
  27046. }
  27047. }
  27048. };
  27049. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27050. // Audio
  27051. /**
  27052. * Gets or sets if audio support is enabled
  27053. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27054. */
  27055. get: function () {
  27056. return this._audioEnabled;
  27057. },
  27058. set: function (value) {
  27059. this._audioEnabled = value;
  27060. if (BABYLON.AudioEngine) {
  27061. if (this._audioEnabled) {
  27062. this._enableAudio();
  27063. }
  27064. else {
  27065. this._disableAudio();
  27066. }
  27067. }
  27068. },
  27069. enumerable: true,
  27070. configurable: true
  27071. });
  27072. Scene.prototype._disableAudio = function () {
  27073. var i;
  27074. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27075. this.mainSoundTrack.soundCollection[i].pause();
  27076. }
  27077. for (i = 0; i < this.soundTracks.length; i++) {
  27078. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27079. this.soundTracks[i].soundCollection[j].pause();
  27080. }
  27081. }
  27082. };
  27083. Scene.prototype._enableAudio = function () {
  27084. var i;
  27085. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27086. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27087. this.mainSoundTrack.soundCollection[i].play();
  27088. }
  27089. }
  27090. for (i = 0; i < this.soundTracks.length; i++) {
  27091. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27092. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27093. this.soundTracks[i].soundCollection[j].play();
  27094. }
  27095. }
  27096. }
  27097. };
  27098. Object.defineProperty(Scene.prototype, "headphone", {
  27099. /**
  27100. * Gets or sets if audio will be output to headphones
  27101. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27102. */
  27103. get: function () {
  27104. return this._headphone;
  27105. },
  27106. set: function (value) {
  27107. this._headphone = value;
  27108. if (BABYLON.AudioEngine) {
  27109. if (this._headphone) {
  27110. this._switchAudioModeForHeadphones();
  27111. }
  27112. else {
  27113. this._switchAudioModeForNormalSpeakers();
  27114. }
  27115. }
  27116. },
  27117. enumerable: true,
  27118. configurable: true
  27119. });
  27120. Scene.prototype._switchAudioModeForHeadphones = function () {
  27121. this.mainSoundTrack.switchPanningModelToHRTF();
  27122. for (var i = 0; i < this.soundTracks.length; i++) {
  27123. this.soundTracks[i].switchPanningModelToHRTF();
  27124. }
  27125. };
  27126. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27127. this.mainSoundTrack.switchPanningModelToEqualPower();
  27128. for (var i = 0; i < this.soundTracks.length; i++) {
  27129. this.soundTracks[i].switchPanningModelToEqualPower();
  27130. }
  27131. };
  27132. /**
  27133. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27134. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27135. * @returns the created depth renderer
  27136. */
  27137. Scene.prototype.enableDepthRenderer = function (camera) {
  27138. camera = camera || this.activeCamera;
  27139. if (!camera) {
  27140. throw "No camera available to enable depth renderer";
  27141. }
  27142. if (!this._depthRenderer[camera.id]) {
  27143. var textureType = 0;
  27144. if (this._engine.getCaps().textureHalfFloatRender) {
  27145. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27146. }
  27147. else if (this._engine.getCaps().textureFloatRender) {
  27148. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27149. }
  27150. else {
  27151. throw "Depth renderer does not support int texture type";
  27152. }
  27153. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27154. }
  27155. return this._depthRenderer[camera.id];
  27156. };
  27157. /**
  27158. * Disables a depth renderer for a given camera
  27159. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27160. */
  27161. Scene.prototype.disableDepthRenderer = function (camera) {
  27162. camera = camera || this.activeCamera;
  27163. if (!camera || !this._depthRenderer[camera.id]) {
  27164. return;
  27165. }
  27166. this._depthRenderer[camera.id].dispose();
  27167. delete this._depthRenderer[camera.id];
  27168. };
  27169. /**
  27170. * Enables a GeometryBufferRender and associates it with the scene
  27171. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27172. * @returns the GeometryBufferRenderer
  27173. */
  27174. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27175. if (ratio === void 0) { ratio = 1; }
  27176. if (this._geometryBufferRenderer) {
  27177. return this._geometryBufferRenderer;
  27178. }
  27179. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27180. if (!this._geometryBufferRenderer.isSupported) {
  27181. this._geometryBufferRenderer = null;
  27182. }
  27183. return this._geometryBufferRenderer;
  27184. };
  27185. /**
  27186. * Disables the GeometryBufferRender associated with the scene
  27187. */
  27188. Scene.prototype.disableGeometryBufferRenderer = function () {
  27189. if (!this._geometryBufferRenderer) {
  27190. return;
  27191. }
  27192. this._geometryBufferRenderer.dispose();
  27193. this._geometryBufferRenderer = null;
  27194. };
  27195. /**
  27196. * Freeze all materials
  27197. * A frozen material will not be updatable but should be faster to render
  27198. */
  27199. Scene.prototype.freezeMaterials = function () {
  27200. for (var i = 0; i < this.materials.length; i++) {
  27201. this.materials[i].freeze();
  27202. }
  27203. };
  27204. /**
  27205. * Unfreeze all materials
  27206. * A frozen material will not be updatable but should be faster to render
  27207. */
  27208. Scene.prototype.unfreezeMaterials = function () {
  27209. for (var i = 0; i < this.materials.length; i++) {
  27210. this.materials[i].unfreeze();
  27211. }
  27212. };
  27213. /**
  27214. * Releases all held ressources
  27215. */
  27216. Scene.prototype.dispose = function () {
  27217. this.beforeRender = null;
  27218. this.afterRender = null;
  27219. this.skeletons = [];
  27220. this.morphTargetManagers = [];
  27221. this.importedMeshesFiles = new Array();
  27222. this.stopAllAnimations();
  27223. this.resetCachedMaterial();
  27224. for (var key in this._depthRenderer) {
  27225. this._depthRenderer[key].dispose();
  27226. }
  27227. if (this._gamepadManager) {
  27228. this._gamepadManager.dispose();
  27229. this._gamepadManager = null;
  27230. }
  27231. // Smart arrays
  27232. if (this.activeCamera) {
  27233. this.activeCamera._activeMeshes.dispose();
  27234. this.activeCamera = null;
  27235. }
  27236. this._activeMeshes.dispose();
  27237. this._renderingManager.dispose();
  27238. this._processedMaterials.dispose();
  27239. this._activeParticleSystems.dispose();
  27240. this._activeSkeletons.dispose();
  27241. this._softwareSkinnedMeshes.dispose();
  27242. this._renderTargets.dispose();
  27243. this._registeredForLateAnimationBindings.dispose();
  27244. if (this._boundingBoxRenderer) {
  27245. this._boundingBoxRenderer.dispose();
  27246. }
  27247. this._meshesForIntersections.dispose();
  27248. this._toBeDisposed.dispose();
  27249. // Abort active requests
  27250. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27251. var request = _a[_i];
  27252. request.abort();
  27253. }
  27254. // Debug layer
  27255. if (this._debugLayer) {
  27256. this._debugLayer.hide();
  27257. }
  27258. // Events
  27259. this.onDisposeObservable.notifyObservers(this);
  27260. this.onDisposeObservable.clear();
  27261. this.onBeforeRenderObservable.clear();
  27262. this.onAfterRenderObservable.clear();
  27263. this.onBeforeRenderTargetsRenderObservable.clear();
  27264. this.onAfterRenderTargetsRenderObservable.clear();
  27265. this.onAfterStepObservable.clear();
  27266. this.onBeforeStepObservable.clear();
  27267. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27268. this.onAfterActiveMeshesEvaluationObservable.clear();
  27269. this.onBeforeParticlesRenderingObservable.clear();
  27270. this.onAfterParticlesRenderingObservable.clear();
  27271. this.onBeforeSpritesRenderingObservable.clear();
  27272. this.onAfterSpritesRenderingObservable.clear();
  27273. this.onBeforeDrawPhaseObservable.clear();
  27274. this.onAfterDrawPhaseObservable.clear();
  27275. this.onBeforePhysicsObservable.clear();
  27276. this.onAfterPhysicsObservable.clear();
  27277. this.onBeforeAnimationsObservable.clear();
  27278. this.onAfterAnimationsObservable.clear();
  27279. this.onDataLoadedObservable.clear();
  27280. this.detachControl();
  27281. // Release sounds & sounds tracks
  27282. if (BABYLON.AudioEngine) {
  27283. this.disposeSounds();
  27284. }
  27285. // VR Helper
  27286. if (this.VRHelper) {
  27287. this.VRHelper.dispose();
  27288. }
  27289. // Detach cameras
  27290. var canvas = this._engine.getRenderingCanvas();
  27291. if (canvas) {
  27292. var index;
  27293. for (index = 0; index < this.cameras.length; index++) {
  27294. this.cameras[index].detachControl(canvas);
  27295. }
  27296. }
  27297. // Release animation groups
  27298. while (this.animationGroups.length) {
  27299. this.animationGroups[0].dispose();
  27300. }
  27301. // Release lights
  27302. while (this.lights.length) {
  27303. this.lights[0].dispose();
  27304. }
  27305. // Release meshes
  27306. while (this.meshes.length) {
  27307. this.meshes[0].dispose(true);
  27308. }
  27309. while (this.transformNodes.length) {
  27310. this.removeTransformNode(this.transformNodes[0]);
  27311. }
  27312. // Release cameras
  27313. while (this.cameras.length) {
  27314. this.cameras[0].dispose();
  27315. }
  27316. // Release materials
  27317. if (this.defaultMaterial) {
  27318. this.defaultMaterial.dispose();
  27319. }
  27320. while (this.multiMaterials.length) {
  27321. this.multiMaterials[0].dispose();
  27322. }
  27323. while (this.materials.length) {
  27324. this.materials[0].dispose();
  27325. }
  27326. // Release particles
  27327. while (this.particleSystems.length) {
  27328. this.particleSystems[0].dispose();
  27329. }
  27330. // Release sprites
  27331. while (this.spriteManagers.length) {
  27332. this.spriteManagers[0].dispose();
  27333. }
  27334. // Release postProcesses
  27335. while (this.postProcesses.length) {
  27336. this.postProcesses[0].dispose();
  27337. }
  27338. // Release layers
  27339. while (this.layers.length) {
  27340. this.layers[0].dispose();
  27341. }
  27342. while (this.effectLayers.length) {
  27343. this.effectLayers[0].dispose();
  27344. }
  27345. // Release textures
  27346. while (this.textures.length) {
  27347. this.textures[0].dispose();
  27348. }
  27349. // Release UBO
  27350. this._sceneUbo.dispose();
  27351. if (this._alternateSceneUbo) {
  27352. this._alternateSceneUbo.dispose();
  27353. }
  27354. // Post-processes
  27355. this.postProcessManager.dispose();
  27356. if (this._postProcessRenderPipelineManager) {
  27357. this._postProcessRenderPipelineManager.dispose();
  27358. }
  27359. // Physics
  27360. if (this._physicsEngine) {
  27361. this.disablePhysicsEngine();
  27362. }
  27363. // Remove from engine
  27364. index = this._engine.scenes.indexOf(this);
  27365. if (index > -1) {
  27366. this._engine.scenes.splice(index, 1);
  27367. }
  27368. this._engine.wipeCaches(true);
  27369. this._isDisposed = true;
  27370. };
  27371. Object.defineProperty(Scene.prototype, "isDisposed", {
  27372. /**
  27373. * Gets if the scene is already disposed
  27374. */
  27375. get: function () {
  27376. return this._isDisposed;
  27377. },
  27378. enumerable: true,
  27379. configurable: true
  27380. });
  27381. /**
  27382. * Releases sounds & soundtracks
  27383. */
  27384. Scene.prototype.disposeSounds = function () {
  27385. if (!this._mainSoundTrack) {
  27386. return;
  27387. }
  27388. this.mainSoundTrack.dispose();
  27389. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27390. this.soundTracks[scIndex].dispose();
  27391. }
  27392. };
  27393. // Octrees
  27394. /**
  27395. * Get the world extend vectors with an optional filter
  27396. *
  27397. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27398. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27399. */
  27400. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27401. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27402. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27403. filterPredicate = filterPredicate || (function () { return true; });
  27404. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27405. mesh.computeWorldMatrix(true);
  27406. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27407. return;
  27408. }
  27409. var boundingInfo = mesh.getBoundingInfo();
  27410. var minBox = boundingInfo.boundingBox.minimumWorld;
  27411. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27412. BABYLON.Tools.CheckExtends(minBox, min, max);
  27413. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27414. });
  27415. return {
  27416. min: min,
  27417. max: max
  27418. };
  27419. };
  27420. /**
  27421. * Creates or updates the octree used to boost selection (picking)
  27422. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27423. * @param maxCapacity defines the maximum capacity per leaf
  27424. * @param maxDepth defines the maximum depth of the octree
  27425. * @returns an octree of AbstractMesh
  27426. */
  27427. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27428. if (maxCapacity === void 0) { maxCapacity = 64; }
  27429. if (maxDepth === void 0) { maxDepth = 2; }
  27430. if (!this._selectionOctree) {
  27431. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27432. }
  27433. var worldExtends = this.getWorldExtends();
  27434. // Update octree
  27435. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27436. return this._selectionOctree;
  27437. };
  27438. // Picking
  27439. /**
  27440. * Creates a ray that can be used to pick in the scene
  27441. * @param x defines the x coordinate of the origin (on-screen)
  27442. * @param y defines the y coordinate of the origin (on-screen)
  27443. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27444. * @param camera defines the camera to use for the picking
  27445. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27446. * @returns a Ray
  27447. */
  27448. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27449. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27450. var result = BABYLON.Ray.Zero();
  27451. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27452. return result;
  27453. };
  27454. /**
  27455. * Creates a ray that can be used to pick in the scene
  27456. * @param x defines the x coordinate of the origin (on-screen)
  27457. * @param y defines the y coordinate of the origin (on-screen)
  27458. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27459. * @param result defines the ray where to store the picking ray
  27460. * @param camera defines the camera to use for the picking
  27461. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27462. * @returns the current scene
  27463. */
  27464. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27465. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27466. var engine = this._engine;
  27467. if (!camera) {
  27468. if (!this.activeCamera)
  27469. throw new Error("Active camera not set");
  27470. camera = this.activeCamera;
  27471. }
  27472. var cameraViewport = camera.viewport;
  27473. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27474. // Moving coordinates to local viewport world
  27475. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27476. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27477. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27478. return this;
  27479. };
  27480. /**
  27481. * Creates a ray that can be used to pick in the scene
  27482. * @param x defines the x coordinate of the origin (on-screen)
  27483. * @param y defines the y coordinate of the origin (on-screen)
  27484. * @param camera defines the camera to use for the picking
  27485. * @returns a Ray
  27486. */
  27487. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27488. var result = BABYLON.Ray.Zero();
  27489. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27490. return result;
  27491. };
  27492. /**
  27493. * Creates a ray that can be used to pick in the scene
  27494. * @param x defines the x coordinate of the origin (on-screen)
  27495. * @param y defines the y coordinate of the origin (on-screen)
  27496. * @param result defines the ray where to store the picking ray
  27497. * @param camera defines the camera to use for the picking
  27498. * @returns the current scene
  27499. */
  27500. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27501. if (!BABYLON.PickingInfo) {
  27502. return this;
  27503. }
  27504. var engine = this._engine;
  27505. if (!camera) {
  27506. if (!this.activeCamera)
  27507. throw new Error("Active camera not set");
  27508. camera = this.activeCamera;
  27509. }
  27510. var cameraViewport = camera.viewport;
  27511. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27512. var identity = BABYLON.Matrix.Identity();
  27513. // Moving coordinates to local viewport world
  27514. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27515. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27516. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27517. return this;
  27518. };
  27519. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27520. if (!BABYLON.PickingInfo) {
  27521. return null;
  27522. }
  27523. var pickingInfo = null;
  27524. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27525. var mesh = this.meshes[meshIndex];
  27526. if (predicate) {
  27527. if (!predicate(mesh)) {
  27528. continue;
  27529. }
  27530. }
  27531. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27532. continue;
  27533. }
  27534. var world = mesh.getWorldMatrix();
  27535. var ray = rayFunction(world);
  27536. var result = mesh.intersects(ray, fastCheck);
  27537. if (!result || !result.hit)
  27538. continue;
  27539. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27540. continue;
  27541. pickingInfo = result;
  27542. if (fastCheck) {
  27543. break;
  27544. }
  27545. }
  27546. return pickingInfo || new BABYLON.PickingInfo();
  27547. };
  27548. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27549. if (!BABYLON.PickingInfo) {
  27550. return null;
  27551. }
  27552. var pickingInfos = new Array();
  27553. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27554. var mesh = this.meshes[meshIndex];
  27555. if (predicate) {
  27556. if (!predicate(mesh)) {
  27557. continue;
  27558. }
  27559. }
  27560. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27561. continue;
  27562. }
  27563. var world = mesh.getWorldMatrix();
  27564. var ray = rayFunction(world);
  27565. var result = mesh.intersects(ray, false);
  27566. if (!result || !result.hit)
  27567. continue;
  27568. pickingInfos.push(result);
  27569. }
  27570. return pickingInfos;
  27571. };
  27572. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27573. if (!BABYLON.PickingInfo) {
  27574. return null;
  27575. }
  27576. var pickingInfo = null;
  27577. if (!camera) {
  27578. if (!this.activeCamera) {
  27579. return null;
  27580. }
  27581. camera = this.activeCamera;
  27582. }
  27583. if (this.spriteManagers.length > 0) {
  27584. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27585. var spriteManager = this.spriteManagers[spriteIndex];
  27586. if (!spriteManager.isPickable) {
  27587. continue;
  27588. }
  27589. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27590. if (!result || !result.hit)
  27591. continue;
  27592. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27593. continue;
  27594. pickingInfo = result;
  27595. if (fastCheck) {
  27596. break;
  27597. }
  27598. }
  27599. }
  27600. return pickingInfo || new BABYLON.PickingInfo();
  27601. };
  27602. /** Launch a ray to try to pick a mesh in the scene
  27603. * @param x position on screen
  27604. * @param y position on screen
  27605. * @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
  27606. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27607. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27608. * @returns a PickingInfo
  27609. */
  27610. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27611. var _this = this;
  27612. if (!BABYLON.PickingInfo) {
  27613. return null;
  27614. }
  27615. return this._internalPick(function (world) {
  27616. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27617. return _this._tempPickingRay;
  27618. }, predicate, fastCheck);
  27619. };
  27620. /** Launch a ray to try to pick a sprite in the scene
  27621. * @param x position on screen
  27622. * @param y position on screen
  27623. * @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
  27624. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27625. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27626. * @returns a PickingInfo
  27627. */
  27628. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27629. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27630. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27631. };
  27632. /** Use the given ray to pick a mesh in the scene
  27633. * @param ray The ray to use to pick meshes
  27634. * @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
  27635. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27636. * @returns a PickingInfo
  27637. */
  27638. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27639. var _this = this;
  27640. return this._internalPick(function (world) {
  27641. if (!_this._pickWithRayInverseMatrix) {
  27642. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27643. }
  27644. world.invertToRef(_this._pickWithRayInverseMatrix);
  27645. if (!_this._cachedRayForTransform) {
  27646. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27647. }
  27648. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27649. return _this._cachedRayForTransform;
  27650. }, predicate, fastCheck);
  27651. };
  27652. /**
  27653. * Launch a ray to try to pick a mesh in the scene
  27654. * @param x X position on screen
  27655. * @param y Y position on screen
  27656. * @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
  27657. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27658. * @returns an array of PickingInfo
  27659. */
  27660. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27661. var _this = this;
  27662. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27663. };
  27664. /**
  27665. * Launch a ray to try to pick a mesh in the scene
  27666. * @param ray Ray to use
  27667. * @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
  27668. * @returns an array of PickingInfo
  27669. */
  27670. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27671. var _this = this;
  27672. return this._internalMultiPick(function (world) {
  27673. if (!_this._pickWithRayInverseMatrix) {
  27674. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27675. }
  27676. world.invertToRef(_this._pickWithRayInverseMatrix);
  27677. if (!_this._cachedRayForTransform) {
  27678. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27679. }
  27680. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27681. return _this._cachedRayForTransform;
  27682. }, predicate);
  27683. };
  27684. /**
  27685. * Force the value of meshUnderPointer
  27686. * @param mesh defines the mesh to use
  27687. */
  27688. Scene.prototype.setPointerOverMesh = function (mesh) {
  27689. if (this._pointerOverMesh === mesh) {
  27690. return;
  27691. }
  27692. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27693. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27694. }
  27695. this._pointerOverMesh = mesh;
  27696. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27697. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27698. }
  27699. };
  27700. /**
  27701. * Gets the mesh under the pointer
  27702. * @returns a Mesh or null if no mesh is under the pointer
  27703. */
  27704. Scene.prototype.getPointerOverMesh = function () {
  27705. return this._pointerOverMesh;
  27706. };
  27707. /**
  27708. * Force the sprite under the pointer
  27709. * @param sprite defines the sprite to use
  27710. */
  27711. Scene.prototype.setPointerOverSprite = function (sprite) {
  27712. if (this._pointerOverSprite === sprite) {
  27713. return;
  27714. }
  27715. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27716. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27717. }
  27718. this._pointerOverSprite = sprite;
  27719. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  27720. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  27721. }
  27722. };
  27723. /**
  27724. * Gets the sprite under the pointer
  27725. * @returns a Sprite or null if no sprite is under the pointer
  27726. */
  27727. Scene.prototype.getPointerOverSprite = function () {
  27728. return this._pointerOverSprite;
  27729. };
  27730. // Physics
  27731. /**
  27732. * Gets the current physics engine
  27733. * @returns a PhysicsEngine or null if none attached
  27734. */
  27735. Scene.prototype.getPhysicsEngine = function () {
  27736. return this._physicsEngine;
  27737. };
  27738. /**
  27739. * Enables physics to the current scene
  27740. * @param gravity defines the scene's gravity for the physics engine
  27741. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  27742. * @return a boolean indicating if the physics engine was initialized
  27743. */
  27744. Scene.prototype.enablePhysics = function (gravity, plugin) {
  27745. if (gravity === void 0) { gravity = null; }
  27746. if (this._physicsEngine) {
  27747. return true;
  27748. }
  27749. try {
  27750. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  27751. return true;
  27752. }
  27753. catch (e) {
  27754. BABYLON.Tools.Error(e.message);
  27755. return false;
  27756. }
  27757. };
  27758. /**
  27759. * Disables and disposes the physics engine associated with the scene
  27760. */
  27761. Scene.prototype.disablePhysicsEngine = function () {
  27762. if (!this._physicsEngine) {
  27763. return;
  27764. }
  27765. this._physicsEngine.dispose();
  27766. this._physicsEngine = null;
  27767. };
  27768. /**
  27769. * Gets a boolean indicating if there is an active physics engine
  27770. * @returns a boolean indicating if there is an active physics engine
  27771. */
  27772. Scene.prototype.isPhysicsEnabled = function () {
  27773. return this._physicsEngine !== undefined;
  27774. };
  27775. /**
  27776. * Deletes a physics compound impostor
  27777. * @param compound defines the compound to delete
  27778. */
  27779. Scene.prototype.deleteCompoundImpostor = function (compound) {
  27780. var mesh = compound.parts[0].mesh;
  27781. if (mesh.physicsImpostor) {
  27782. mesh.physicsImpostor.dispose();
  27783. mesh.physicsImpostor = null;
  27784. }
  27785. };
  27786. // Misc.
  27787. /** @ignore */
  27788. Scene.prototype._rebuildGeometries = function () {
  27789. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  27790. var geometry = _a[_i];
  27791. geometry._rebuild();
  27792. }
  27793. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  27794. var mesh = _c[_b];
  27795. mesh._rebuild();
  27796. }
  27797. if (this.postProcessManager) {
  27798. this.postProcessManager._rebuild();
  27799. }
  27800. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  27801. var layer = _e[_d];
  27802. layer._rebuild();
  27803. }
  27804. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  27805. var effectLayer = _g[_f];
  27806. effectLayer._rebuild();
  27807. }
  27808. if (this._boundingBoxRenderer) {
  27809. this._boundingBoxRenderer._rebuild();
  27810. }
  27811. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  27812. var system = _j[_h];
  27813. system.rebuild();
  27814. }
  27815. if (this._postProcessRenderPipelineManager) {
  27816. this._postProcessRenderPipelineManager._rebuild();
  27817. }
  27818. };
  27819. /** @ignore */
  27820. Scene.prototype._rebuildTextures = function () {
  27821. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  27822. var texture = _a[_i];
  27823. texture._rebuild();
  27824. }
  27825. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27826. };
  27827. /**
  27828. * Creates a default light for the scene.
  27829. * @param replace Whether to replace the existing lights in the scene.
  27830. */
  27831. Scene.prototype.createDefaultLight = function (replace) {
  27832. if (replace === void 0) { replace = false; }
  27833. // Dispose existing light in replace mode.
  27834. if (replace) {
  27835. if (this.lights) {
  27836. for (var i = 0; i < this.lights.length; i++) {
  27837. this.lights[i].dispose();
  27838. }
  27839. }
  27840. }
  27841. // Light
  27842. if (this.lights.length === 0) {
  27843. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  27844. }
  27845. };
  27846. /**
  27847. * Creates a default camera for the scene.
  27848. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  27849. * @param replace Whether to replace the existing active camera in the scene.
  27850. * @param attachCameraControls Whether to attach camera controls to the canvas.
  27851. */
  27852. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  27853. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27854. if (replace === void 0) { replace = false; }
  27855. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27856. // Dispose existing camera in replace mode.
  27857. if (replace) {
  27858. if (this.activeCamera) {
  27859. this.activeCamera.dispose();
  27860. this.activeCamera = null;
  27861. }
  27862. }
  27863. // Camera
  27864. if (!this.activeCamera) {
  27865. var worldExtends = this.getWorldExtends();
  27866. var worldSize = worldExtends.max.subtract(worldExtends.min);
  27867. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  27868. var camera;
  27869. var radius = worldSize.length() * 1.5;
  27870. // empty scene scenario!
  27871. if (!isFinite(radius)) {
  27872. radius = 1;
  27873. worldCenter.copyFromFloats(0, 0, 0);
  27874. }
  27875. if (createArcRotateCamera) {
  27876. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  27877. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  27878. arcRotateCamera.wheelPrecision = 100 / radius;
  27879. camera = arcRotateCamera;
  27880. }
  27881. else {
  27882. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  27883. freeCamera.setTarget(worldCenter);
  27884. camera = freeCamera;
  27885. }
  27886. camera.minZ = radius * 0.01;
  27887. camera.maxZ = radius * 1000;
  27888. camera.speed = radius * 0.2;
  27889. this.activeCamera = camera;
  27890. var canvas = this.getEngine().getRenderingCanvas();
  27891. if (attachCameraControls && canvas) {
  27892. camera.attachControl(canvas);
  27893. }
  27894. }
  27895. };
  27896. /**
  27897. * Creates a default camera and a default light
  27898. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  27899. * @param replace defines if the camera and/or light will replace the existing ones
  27900. * @param attachCameraControls defines if attachControl will be called on the new camera
  27901. */
  27902. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  27903. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  27904. if (replace === void 0) { replace = false; }
  27905. if (attachCameraControls === void 0) { attachCameraControls = false; }
  27906. this.createDefaultLight(replace);
  27907. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  27908. };
  27909. /**
  27910. * Creates a new sky box
  27911. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27912. * @param environmentTexture defines the texture to use as environment texture
  27913. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  27914. * @param scale defines the overall scale of the skybox
  27915. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  27916. * @returns a new mesh holding the sky box
  27917. */
  27918. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  27919. if (pbr === void 0) { pbr = false; }
  27920. if (scale === void 0) { scale = 1000; }
  27921. if (blur === void 0) { blur = 0; }
  27922. if (environmentTexture) {
  27923. this.environmentTexture = environmentTexture;
  27924. }
  27925. if (!this.environmentTexture) {
  27926. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  27927. return null;
  27928. }
  27929. // Skybox
  27930. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  27931. if (pbr) {
  27932. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  27933. hdrSkyboxMaterial.backFaceCulling = false;
  27934. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27935. if (hdrSkyboxMaterial.reflectionTexture) {
  27936. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27937. }
  27938. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  27939. hdrSkyboxMaterial.disableLighting = true;
  27940. hdrSkyboxMaterial.twoSidedLighting = true;
  27941. hdrSkybox.infiniteDistance = true;
  27942. hdrSkybox.material = hdrSkyboxMaterial;
  27943. }
  27944. else {
  27945. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  27946. skyboxMaterial.backFaceCulling = false;
  27947. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  27948. if (skyboxMaterial.reflectionTexture) {
  27949. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  27950. }
  27951. skyboxMaterial.disableLighting = true;
  27952. hdrSkybox.infiniteDistance = true;
  27953. hdrSkybox.material = skyboxMaterial;
  27954. }
  27955. return hdrSkybox;
  27956. };
  27957. /**
  27958. * Creates a new environment
  27959. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  27960. * @param options defines the options you can use to configure the environment
  27961. * @returns the new EnvironmentHelper
  27962. */
  27963. Scene.prototype.createDefaultEnvironment = function (options) {
  27964. if (BABYLON.EnvironmentHelper) {
  27965. return new BABYLON.EnvironmentHelper(options, this);
  27966. }
  27967. return null;
  27968. };
  27969. /**
  27970. * Creates a new VREXperienceHelper
  27971. * @see http://doc.babylonjs.com/how_to/webvr_helper
  27972. * @param webVROptions defines the options used to create the new VREXperienceHelper
  27973. * @returns a new VREXperienceHelper
  27974. */
  27975. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  27976. if (webVROptions === void 0) { webVROptions = {}; }
  27977. return new BABYLON.VRExperienceHelper(this, webVROptions);
  27978. };
  27979. // Tags
  27980. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  27981. if (tagsQuery === undefined) {
  27982. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  27983. return list;
  27984. }
  27985. var listByTags = [];
  27986. forEach = forEach || (function (item) { return; });
  27987. for (var i in list) {
  27988. var item = list[i];
  27989. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  27990. listByTags.push(item);
  27991. forEach(item);
  27992. }
  27993. }
  27994. return listByTags;
  27995. };
  27996. /**
  27997. * Get a list of meshes by tags
  27998. * @param tagsQuery defines the tags query to use
  27999. * @param forEach defines a predicate used to filter results
  28000. * @returns an array of Mesh
  28001. */
  28002. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28003. return this._getByTags(this.meshes, tagsQuery, forEach);
  28004. };
  28005. /**
  28006. * Get a list of cameras by tags
  28007. * @param tagsQuery defines the tags query to use
  28008. * @param forEach defines a predicate used to filter results
  28009. * @returns an array of Camera
  28010. */
  28011. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28012. return this._getByTags(this.cameras, tagsQuery, forEach);
  28013. };
  28014. /**
  28015. * Get a list of lights by tags
  28016. * @param tagsQuery defines the tags query to use
  28017. * @param forEach defines a predicate used to filter results
  28018. * @returns an array of Light
  28019. */
  28020. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28021. return this._getByTags(this.lights, tagsQuery, forEach);
  28022. };
  28023. /**
  28024. * Get a list of materials by tags
  28025. * @param tagsQuery defines the tags query to use
  28026. * @param forEach defines a predicate used to filter results
  28027. * @returns an array of Material
  28028. */
  28029. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28030. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28031. };
  28032. /**
  28033. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28034. * This allowed control for front to back rendering or reversly depending of the special needs.
  28035. *
  28036. * @param renderingGroupId The rendering group id corresponding to its index
  28037. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28038. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28039. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28040. */
  28041. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28042. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28043. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28044. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28045. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28046. };
  28047. /**
  28048. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28049. *
  28050. * @param renderingGroupId The rendering group id corresponding to its index
  28051. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28052. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28053. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28054. */
  28055. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28056. if (depth === void 0) { depth = true; }
  28057. if (stencil === void 0) { stencil = true; }
  28058. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28059. };
  28060. /**
  28061. * Will flag all materials as dirty to trigger new shader compilation
  28062. * @param flag defines the flag used to specify which material part must be marked as dirty
  28063. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28064. */
  28065. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28066. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28067. var material = _a[_i];
  28068. if (predicate && !predicate(material)) {
  28069. continue;
  28070. }
  28071. material.markAsDirty(flag);
  28072. }
  28073. };
  28074. /** @ignore */
  28075. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28076. var _this = this;
  28077. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28078. this._activeRequests.push(request);
  28079. request.onCompleteObservable.add(function (request) {
  28080. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28081. });
  28082. return request;
  28083. };
  28084. /** @ignore */
  28085. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28086. var _this = this;
  28087. return new Promise(function (resolve, reject) {
  28088. _this._loadFile(url, function (data) {
  28089. resolve(data);
  28090. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28091. reject(exception);
  28092. });
  28093. });
  28094. };
  28095. // Statics
  28096. Scene._FOGMODE_NONE = 0;
  28097. Scene._FOGMODE_EXP = 1;
  28098. Scene._FOGMODE_EXP2 = 2;
  28099. Scene._FOGMODE_LINEAR = 3;
  28100. Scene._uniqueIdCounter = 0;
  28101. /**
  28102. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28103. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28104. */
  28105. Scene.MinDeltaTime = 1.0;
  28106. /**
  28107. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28108. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28109. */
  28110. Scene.MaxDeltaTime = 1000.0;
  28111. /** The distance in pixel that you have to move to prevent some events */
  28112. Scene.DragMovementThreshold = 10; // in pixels
  28113. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28114. Scene.LongPressDelay = 500; // in milliseconds
  28115. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28116. Scene.DoubleClickDelay = 300; // in milliseconds
  28117. /** If you need to check double click without raising a single click at first click, enable this flag */
  28118. Scene.ExclusiveDoubleClickMode = false;
  28119. return Scene;
  28120. }());
  28121. BABYLON.Scene = Scene;
  28122. })(BABYLON || (BABYLON = {}));
  28123. //# sourceMappingURL=babylon.scene.js.map
  28124. "use strict";
  28125. var BABYLON;
  28126. (function (BABYLON) {
  28127. /**
  28128. * Set of assets to keep when moving a scene into an asset container.
  28129. */
  28130. var KeepAssets = /** @class */ (function () {
  28131. function KeepAssets() {
  28132. /**
  28133. * Cameras to keep.
  28134. */
  28135. this.cameras = new Array();
  28136. /**
  28137. * Lights to keep.
  28138. */
  28139. this.lights = new Array();
  28140. /**
  28141. * Meshes to keep.
  28142. */
  28143. this.meshes = new Array();
  28144. /**
  28145. * Skeletons to keep.
  28146. */
  28147. this.skeletons = new Array();
  28148. /**
  28149. * ParticleSystems to keep.
  28150. */
  28151. this.particleSystems = new Array();
  28152. /**
  28153. * Animations to keep.
  28154. */
  28155. this.animations = new Array();
  28156. /**
  28157. * AnimationGroups to keep.
  28158. */
  28159. this.animationGroups = new Array();
  28160. /**
  28161. * MultiMaterials to keep.
  28162. */
  28163. this.multiMaterials = new Array();
  28164. /**
  28165. * Materials to keep.
  28166. */
  28167. this.materials = new Array();
  28168. /**
  28169. * MorphTargetManagers to keep.
  28170. */
  28171. this.morphTargetManagers = new Array();
  28172. /**
  28173. * Geometries to keep.
  28174. */
  28175. this.geometries = new Array();
  28176. /**
  28177. * TransformNodes to keep.
  28178. */
  28179. this.transformNodes = new Array();
  28180. /**
  28181. * LensFlareSystems to keep.
  28182. */
  28183. this.lensFlareSystems = new Array();
  28184. /**
  28185. * ShadowGenerators to keep.
  28186. */
  28187. this.shadowGenerators = new Array();
  28188. /**
  28189. * ActionManagers to keep.
  28190. */
  28191. this.actionManagers = new Array();
  28192. /**
  28193. * Sounds to keep.
  28194. */
  28195. this.sounds = new Array();
  28196. /**
  28197. * Textures to keep.
  28198. */
  28199. this.textures = new Array();
  28200. /**
  28201. * Effect layers to keep.
  28202. */
  28203. this.effectLayers = new Array();
  28204. }
  28205. return KeepAssets;
  28206. }());
  28207. BABYLON.KeepAssets = KeepAssets;
  28208. /**
  28209. * Container with a set of assets that can be added or removed from a scene.
  28210. */
  28211. var AssetContainer = /** @class */ (function () {
  28212. /**
  28213. * Instantiates an AssetContainer.
  28214. * @param scene The scene the AssetContainer belongs to.
  28215. */
  28216. function AssetContainer(scene) {
  28217. // Objects
  28218. /**
  28219. * Cameras populated in the container.
  28220. */
  28221. this.cameras = new Array();
  28222. /**
  28223. * Lights populated in the container.
  28224. */
  28225. this.lights = new Array();
  28226. /**
  28227. * Meshes populated in the container.
  28228. */
  28229. this.meshes = new Array();
  28230. /**
  28231. * Skeletons populated in the container.
  28232. */
  28233. this.skeletons = new Array();
  28234. /**
  28235. * ParticleSystems populated in the container.
  28236. */
  28237. this.particleSystems = new Array();
  28238. /**
  28239. * Animations populated in the container.
  28240. */
  28241. this.animations = new Array();
  28242. /**
  28243. * AnimationGroups populated in the container.
  28244. */
  28245. this.animationGroups = new Array();
  28246. /**
  28247. * MultiMaterials populated in the container.
  28248. */
  28249. this.multiMaterials = new Array();
  28250. /**
  28251. * Materials populated in the container.
  28252. */
  28253. this.materials = new Array();
  28254. /**
  28255. * MorphTargetManagers populated in the container.
  28256. */
  28257. this.morphTargetManagers = new Array();
  28258. /**
  28259. * Geometries populated in the container.
  28260. */
  28261. this.geometries = new Array();
  28262. /**
  28263. * TransformNodes populated in the container.
  28264. */
  28265. this.transformNodes = new Array();
  28266. /**
  28267. * LensFlareSystems populated in the container.
  28268. */
  28269. this.lensFlareSystems = new Array();
  28270. /**
  28271. * ShadowGenerators populated in the container.
  28272. */
  28273. this.shadowGenerators = new Array();
  28274. /**
  28275. * ActionManagers populated in the container.
  28276. */
  28277. this.actionManagers = new Array();
  28278. /**
  28279. * Sounds populated in the container.
  28280. */
  28281. this.sounds = new Array();
  28282. /**
  28283. * Textures populated in the container.
  28284. */
  28285. this.textures = new Array();
  28286. /**
  28287. * Effect layers populated in the container.
  28288. */
  28289. this.effectLayers = new Array();
  28290. this.scene = scene;
  28291. }
  28292. /**
  28293. * Adds all the assets from the container to the scene.
  28294. */
  28295. AssetContainer.prototype.addAllToScene = function () {
  28296. var _this = this;
  28297. this.cameras.forEach(function (o) {
  28298. _this.scene.addCamera(o);
  28299. });
  28300. this.lights.forEach(function (o) {
  28301. _this.scene.addLight(o);
  28302. });
  28303. this.meshes.forEach(function (o) {
  28304. _this.scene.addMesh(o);
  28305. });
  28306. this.skeletons.forEach(function (o) {
  28307. _this.scene.addSkeleton(o);
  28308. });
  28309. this.particleSystems.forEach(function (o) {
  28310. _this.scene.addParticleSystem(o);
  28311. });
  28312. this.animations.forEach(function (o) {
  28313. _this.scene.addAnimation(o);
  28314. });
  28315. this.animationGroups.forEach(function (o) {
  28316. _this.scene.addAnimationGroup(o);
  28317. });
  28318. this.multiMaterials.forEach(function (o) {
  28319. _this.scene.addMultiMaterial(o);
  28320. });
  28321. this.materials.forEach(function (o) {
  28322. _this.scene.addMaterial(o);
  28323. });
  28324. this.morphTargetManagers.forEach(function (o) {
  28325. _this.scene.addMorphTargetManager(o);
  28326. });
  28327. this.geometries.forEach(function (o) {
  28328. _this.scene.addGeometry(o);
  28329. });
  28330. this.transformNodes.forEach(function (o) {
  28331. _this.scene.addTransformNode(o);
  28332. });
  28333. this.lensFlareSystems.forEach(function (o) {
  28334. _this.scene.addLensFlareSystem(o);
  28335. });
  28336. this.actionManagers.forEach(function (o) {
  28337. _this.scene.addActionManager(o);
  28338. });
  28339. this.sounds.forEach(function (o) {
  28340. o.play();
  28341. o.autoplay = true;
  28342. _this.scene.mainSoundTrack.AddSound(o);
  28343. });
  28344. this.textures.forEach(function (o) {
  28345. _this.scene.addTexture(o);
  28346. });
  28347. this.effectLayers.forEach(function (o) {
  28348. _this.scene.addEffectLayer(o);
  28349. });
  28350. };
  28351. /**
  28352. * Removes all the assets in the container from the scene
  28353. */
  28354. AssetContainer.prototype.removeAllFromScene = function () {
  28355. var _this = this;
  28356. this.cameras.forEach(function (o) {
  28357. _this.scene.removeCamera(o);
  28358. });
  28359. this.lights.forEach(function (o) {
  28360. _this.scene.removeLight(o);
  28361. });
  28362. this.meshes.forEach(function (o) {
  28363. _this.scene.removeMesh(o);
  28364. });
  28365. this.skeletons.forEach(function (o) {
  28366. _this.scene.removeSkeleton(o);
  28367. });
  28368. this.particleSystems.forEach(function (o) {
  28369. _this.scene.removeParticleSystem(o);
  28370. });
  28371. this.animations.forEach(function (o) {
  28372. _this.scene.removeAnimation(o);
  28373. });
  28374. this.animationGroups.forEach(function (o) {
  28375. _this.scene.removeAnimationGroup(o);
  28376. });
  28377. this.multiMaterials.forEach(function (o) {
  28378. _this.scene.removeMultiMaterial(o);
  28379. });
  28380. this.materials.forEach(function (o) {
  28381. _this.scene.removeMaterial(o);
  28382. });
  28383. this.morphTargetManagers.forEach(function (o) {
  28384. _this.scene.removeMorphTargetManager(o);
  28385. });
  28386. this.geometries.forEach(function (o) {
  28387. _this.scene.removeGeometry(o);
  28388. });
  28389. this.transformNodes.forEach(function (o) {
  28390. _this.scene.removeTransformNode(o);
  28391. });
  28392. this.lensFlareSystems.forEach(function (o) {
  28393. _this.scene.removeLensFlareSystem(o);
  28394. });
  28395. this.actionManagers.forEach(function (o) {
  28396. _this.scene.removeActionManager(o);
  28397. });
  28398. this.sounds.forEach(function (o) {
  28399. o.stop();
  28400. o.autoplay = false;
  28401. _this.scene.mainSoundTrack.RemoveSound(o);
  28402. });
  28403. this.textures.forEach(function (o) {
  28404. _this.scene.removeTexture(o);
  28405. });
  28406. this.effectLayers.forEach(function (o) {
  28407. _this.scene.removeEffectLayer(o);
  28408. });
  28409. };
  28410. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28411. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28412. var asset = sourceAssets_1[_i];
  28413. var move = true;
  28414. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28415. var keepAsset = keepAssets_1[_a];
  28416. if (asset === keepAsset) {
  28417. move = false;
  28418. break;
  28419. }
  28420. }
  28421. if (move) {
  28422. targetAssets.push(asset);
  28423. }
  28424. }
  28425. };
  28426. /**
  28427. * Removes all the assets contained in the scene and adds them to the container.
  28428. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28429. */
  28430. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28431. if (keepAssets === undefined) {
  28432. keepAssets = new KeepAssets();
  28433. }
  28434. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28435. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28436. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28437. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28438. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28439. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28440. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28441. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28442. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28443. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28444. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28445. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28446. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28447. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28448. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28449. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28450. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28451. this.removeAllFromScene();
  28452. };
  28453. return AssetContainer;
  28454. }());
  28455. BABYLON.AssetContainer = AssetContainer;
  28456. })(BABYLON || (BABYLON = {}));
  28457. //# sourceMappingURL=babylon.assetContainer.js.map
  28458. "use strict";
  28459. var BABYLON;
  28460. (function (BABYLON) {
  28461. var Buffer = /** @class */ (function () {
  28462. /**
  28463. * Constructor
  28464. * @param engine the engine
  28465. * @param data the data to use for this buffer
  28466. * @param updatable whether the data is updatable
  28467. * @param stride the stride (optional)
  28468. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28469. * @param instanced whether the buffer is instanced (optional)
  28470. * @param useBytes set to true if the stride in in bytes (optional)
  28471. */
  28472. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28473. if (stride === void 0) { stride = 0; }
  28474. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28475. if (instanced === void 0) { instanced = false; }
  28476. if (useBytes === void 0) { useBytes = false; }
  28477. if (engine instanceof BABYLON.Mesh) {
  28478. this._engine = engine.getScene().getEngine();
  28479. }
  28480. else {
  28481. this._engine = engine;
  28482. }
  28483. this._updatable = updatable;
  28484. this._instanced = instanced;
  28485. this._data = data;
  28486. this.byteStride = useBytes ? stride : stride * 4;
  28487. if (!postponeInternalCreation) {
  28488. this.create();
  28489. }
  28490. }
  28491. /**
  28492. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28493. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28494. * @param offset defines offset in the buffer (0 by default)
  28495. * @param size defines the size in floats of attributes (position is 3 for instance)
  28496. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28497. * @param instanced defines if the vertex buffer contains indexed data
  28498. * @param useBytes defines if the offset and stride are in bytes
  28499. * @returns the new vertex buffer
  28500. */
  28501. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28502. if (useBytes === void 0) { useBytes = false; }
  28503. var byteOffset = useBytes ? offset : offset * 4;
  28504. var byteStride = stride ? (useBytes ? stride : stride * 4) : this.byteStride;
  28505. // a lot of these parameters are ignored as they are overriden by the buffer
  28506. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28507. };
  28508. // Properties
  28509. Buffer.prototype.isUpdatable = function () {
  28510. return this._updatable;
  28511. };
  28512. Buffer.prototype.getData = function () {
  28513. return this._data;
  28514. };
  28515. Buffer.prototype.getBuffer = function () {
  28516. return this._buffer;
  28517. };
  28518. /**
  28519. * Gets the stride in float32 units (i.e. byte stride / 4).
  28520. * May not be an integer if the byte stride is not divisible by 4.
  28521. * DEPRECATED. Use byteStride instead.
  28522. * @returns the stride in float32 units
  28523. */
  28524. Buffer.prototype.getStrideSize = function () {
  28525. return this.byteStride / 4;
  28526. };
  28527. // Methods
  28528. Buffer.prototype.create = function (data) {
  28529. if (data === void 0) { data = null; }
  28530. if (!data && this._buffer) {
  28531. return; // nothing to do
  28532. }
  28533. data = data || this._data;
  28534. if (!data) {
  28535. return;
  28536. }
  28537. if (!this._buffer) {
  28538. if (this._updatable) {
  28539. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28540. this._data = data;
  28541. }
  28542. else {
  28543. this._buffer = this._engine.createVertexBuffer(data);
  28544. }
  28545. }
  28546. else if (this._updatable) {
  28547. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28548. this._data = data;
  28549. }
  28550. };
  28551. Buffer.prototype._rebuild = function () {
  28552. this._buffer = null;
  28553. this.create(this._data);
  28554. };
  28555. Buffer.prototype.update = function (data) {
  28556. this.create(data);
  28557. };
  28558. /**
  28559. * Updates the data directly.
  28560. * @param data the new data
  28561. * @param offset the new offset
  28562. * @param vertexCount the vertex count (optional)
  28563. * @param useBytes set to true if the offset is in bytes
  28564. */
  28565. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28566. if (useBytes === void 0) { useBytes = false; }
  28567. if (!this._buffer) {
  28568. return;
  28569. }
  28570. if (this._updatable) {
  28571. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * 4, (vertexCount ? vertexCount * this.byteStride : undefined));
  28572. this._data = null;
  28573. }
  28574. };
  28575. Buffer.prototype.dispose = function () {
  28576. if (!this._buffer) {
  28577. return;
  28578. }
  28579. if (this._engine._releaseBuffer(this._buffer)) {
  28580. this._buffer = null;
  28581. }
  28582. };
  28583. return Buffer;
  28584. }());
  28585. BABYLON.Buffer = Buffer;
  28586. })(BABYLON || (BABYLON = {}));
  28587. //# sourceMappingURL=babylon.buffer.js.map
  28588. "use strict";
  28589. var BABYLON;
  28590. (function (BABYLON) {
  28591. var VertexBuffer = /** @class */ (function () {
  28592. /**
  28593. * Constructor
  28594. * @param engine the engine
  28595. * @param data the data to use for this vertex buffer
  28596. * @param kind the vertex buffer kind
  28597. * @param updatable whether the data is updatable
  28598. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28599. * @param stride the stride (optional)
  28600. * @param instanced whether the buffer is instanced (optional)
  28601. * @param offset the offset of the data (optional)
  28602. * @param size the number of components (optional)
  28603. * @param type the type of the component (optional)
  28604. * @param normalized whether the data contains normalized data (optional)
  28605. * @param useBytes set to true if stride and offset are in bytes (optional)
  28606. */
  28607. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28608. if (normalized === void 0) { normalized = false; }
  28609. if (useBytes === void 0) { useBytes = false; }
  28610. if (data instanceof BABYLON.Buffer) {
  28611. this._buffer = data;
  28612. this._ownsBuffer = false;
  28613. }
  28614. else {
  28615. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28616. this._ownsBuffer = true;
  28617. }
  28618. this._kind = kind;
  28619. if (type == undefined) {
  28620. var data_1 = this.getData();
  28621. this.type = VertexBuffer.FLOAT;
  28622. if (data_1 instanceof Int8Array)
  28623. this.type = VertexBuffer.BYTE;
  28624. else if (data_1 instanceof Uint8Array)
  28625. this.type = VertexBuffer.UNSIGNED_BYTE;
  28626. else if (data_1 instanceof Int16Array)
  28627. this.type = VertexBuffer.SHORT;
  28628. else if (data_1 instanceof Uint16Array)
  28629. this.type = VertexBuffer.UNSIGNED_SHORT;
  28630. else if (data_1 instanceof Int32Array)
  28631. this.type = VertexBuffer.INT;
  28632. else if (data_1 instanceof Uint32Array)
  28633. this.type = VertexBuffer.UNSIGNED_INT;
  28634. }
  28635. else {
  28636. this.type = type;
  28637. }
  28638. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28639. if (useBytes) {
  28640. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28641. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28642. this.byteOffset = offset || 0;
  28643. }
  28644. else {
  28645. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28646. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28647. this.byteOffset = (offset || 0) * typeByteLength;
  28648. }
  28649. this.normalized = normalized;
  28650. this._instanced = instanced !== undefined ? instanced : false;
  28651. this._instanceDivisor = instanced ? 1 : 0;
  28652. }
  28653. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28654. /**
  28655. * Gets or sets the instance divisor when in instanced mode
  28656. */
  28657. get: function () {
  28658. return this._instanceDivisor;
  28659. },
  28660. set: function (value) {
  28661. this._instanceDivisor = value;
  28662. if (value == 0) {
  28663. this._instanced = false;
  28664. }
  28665. else {
  28666. this._instanced = true;
  28667. }
  28668. },
  28669. enumerable: true,
  28670. configurable: true
  28671. });
  28672. VertexBuffer.prototype._rebuild = function () {
  28673. if (!this._buffer) {
  28674. return;
  28675. }
  28676. this._buffer._rebuild();
  28677. };
  28678. /**
  28679. * Returns the kind of the VertexBuffer (string).
  28680. */
  28681. VertexBuffer.prototype.getKind = function () {
  28682. return this._kind;
  28683. };
  28684. // Properties
  28685. /**
  28686. * Boolean : is the VertexBuffer updatable ?
  28687. */
  28688. VertexBuffer.prototype.isUpdatable = function () {
  28689. return this._buffer.isUpdatable();
  28690. };
  28691. /**
  28692. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28693. */
  28694. VertexBuffer.prototype.getData = function () {
  28695. return this._buffer.getData();
  28696. };
  28697. /**
  28698. * Returns the WebGLBuffer associated to the VertexBuffer.
  28699. */
  28700. VertexBuffer.prototype.getBuffer = function () {
  28701. return this._buffer.getBuffer();
  28702. };
  28703. /**
  28704. * Returns the stride as a multiple of the type byte length.
  28705. * DEPRECATED. Use byteStride instead.
  28706. */
  28707. VertexBuffer.prototype.getStrideSize = function () {
  28708. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  28709. };
  28710. /**
  28711. * Returns the offset as a multiple of the type byte length.
  28712. * DEPRECATED. Use byteOffset instead.
  28713. */
  28714. VertexBuffer.prototype.getOffset = function () {
  28715. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  28716. };
  28717. /**
  28718. * Returns the number of components per vertex attribute (integer).
  28719. */
  28720. VertexBuffer.prototype.getSize = function () {
  28721. return this._size;
  28722. };
  28723. /**
  28724. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  28725. */
  28726. VertexBuffer.prototype.getIsInstanced = function () {
  28727. return this._instanced;
  28728. };
  28729. /**
  28730. * Returns the instancing divisor, zero for non-instanced (integer).
  28731. */
  28732. VertexBuffer.prototype.getInstanceDivisor = function () {
  28733. return this._instanceDivisor;
  28734. };
  28735. // Methods
  28736. /**
  28737. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  28738. * Returns the created WebGLBuffer.
  28739. */
  28740. VertexBuffer.prototype.create = function (data) {
  28741. return this._buffer.create(data);
  28742. };
  28743. /**
  28744. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28745. * This function will create a new buffer if the current one is not updatable
  28746. * Returns the updated WebGLBuffer.
  28747. */
  28748. VertexBuffer.prototype.update = function (data) {
  28749. return this._buffer.update(data);
  28750. };
  28751. /**
  28752. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  28753. * Returns the directly updated WebGLBuffer.
  28754. */
  28755. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  28756. return this._buffer.updateDirectly(data, offset);
  28757. };
  28758. /**
  28759. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  28760. */
  28761. VertexBuffer.prototype.dispose = function () {
  28762. if (this._ownsBuffer) {
  28763. this._buffer.dispose();
  28764. }
  28765. };
  28766. /**
  28767. * Enumerates each value of this vertex buffer as numbers.
  28768. * @param count the number of values to enumerate
  28769. * @param callback the callback function called for each value
  28770. */
  28771. VertexBuffer.prototype.forEach = function (count, callback) {
  28772. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  28773. };
  28774. Object.defineProperty(VertexBuffer, "PositionKind", {
  28775. get: function () {
  28776. return VertexBuffer._PositionKind;
  28777. },
  28778. enumerable: true,
  28779. configurable: true
  28780. });
  28781. Object.defineProperty(VertexBuffer, "NormalKind", {
  28782. get: function () {
  28783. return VertexBuffer._NormalKind;
  28784. },
  28785. enumerable: true,
  28786. configurable: true
  28787. });
  28788. Object.defineProperty(VertexBuffer, "TangentKind", {
  28789. get: function () {
  28790. return VertexBuffer._TangentKind;
  28791. },
  28792. enumerable: true,
  28793. configurable: true
  28794. });
  28795. Object.defineProperty(VertexBuffer, "UVKind", {
  28796. get: function () {
  28797. return VertexBuffer._UVKind;
  28798. },
  28799. enumerable: true,
  28800. configurable: true
  28801. });
  28802. Object.defineProperty(VertexBuffer, "UV2Kind", {
  28803. get: function () {
  28804. return VertexBuffer._UV2Kind;
  28805. },
  28806. enumerable: true,
  28807. configurable: true
  28808. });
  28809. Object.defineProperty(VertexBuffer, "UV3Kind", {
  28810. get: function () {
  28811. return VertexBuffer._UV3Kind;
  28812. },
  28813. enumerable: true,
  28814. configurable: true
  28815. });
  28816. Object.defineProperty(VertexBuffer, "UV4Kind", {
  28817. get: function () {
  28818. return VertexBuffer._UV4Kind;
  28819. },
  28820. enumerable: true,
  28821. configurable: true
  28822. });
  28823. Object.defineProperty(VertexBuffer, "UV5Kind", {
  28824. get: function () {
  28825. return VertexBuffer._UV5Kind;
  28826. },
  28827. enumerable: true,
  28828. configurable: true
  28829. });
  28830. Object.defineProperty(VertexBuffer, "UV6Kind", {
  28831. get: function () {
  28832. return VertexBuffer._UV6Kind;
  28833. },
  28834. enumerable: true,
  28835. configurable: true
  28836. });
  28837. Object.defineProperty(VertexBuffer, "ColorKind", {
  28838. get: function () {
  28839. return VertexBuffer._ColorKind;
  28840. },
  28841. enumerable: true,
  28842. configurable: true
  28843. });
  28844. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  28845. get: function () {
  28846. return VertexBuffer._MatricesIndicesKind;
  28847. },
  28848. enumerable: true,
  28849. configurable: true
  28850. });
  28851. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  28852. get: function () {
  28853. return VertexBuffer._MatricesWeightsKind;
  28854. },
  28855. enumerable: true,
  28856. configurable: true
  28857. });
  28858. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  28859. get: function () {
  28860. return VertexBuffer._MatricesIndicesExtraKind;
  28861. },
  28862. enumerable: true,
  28863. configurable: true
  28864. });
  28865. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  28866. get: function () {
  28867. return VertexBuffer._MatricesWeightsExtraKind;
  28868. },
  28869. enumerable: true,
  28870. configurable: true
  28871. });
  28872. /**
  28873. * Deduces the stride given a kind.
  28874. * @param kind The kind string to deduce
  28875. * @returns The deduced stride
  28876. */
  28877. VertexBuffer.DeduceStride = function (kind) {
  28878. switch (kind) {
  28879. case VertexBuffer.UVKind:
  28880. case VertexBuffer.UV2Kind:
  28881. case VertexBuffer.UV3Kind:
  28882. case VertexBuffer.UV4Kind:
  28883. case VertexBuffer.UV5Kind:
  28884. case VertexBuffer.UV6Kind:
  28885. return 2;
  28886. case VertexBuffer.NormalKind:
  28887. case VertexBuffer.PositionKind:
  28888. return 3;
  28889. case VertexBuffer.ColorKind:
  28890. case VertexBuffer.MatricesIndicesKind:
  28891. case VertexBuffer.MatricesIndicesExtraKind:
  28892. case VertexBuffer.MatricesWeightsKind:
  28893. case VertexBuffer.MatricesWeightsExtraKind:
  28894. case VertexBuffer.TangentKind:
  28895. return 4;
  28896. default:
  28897. throw new Error("Invalid kind '" + kind + "'");
  28898. }
  28899. };
  28900. /**
  28901. * Gets the byte length of the given type.
  28902. * @param type the type
  28903. * @returns the number of bytes
  28904. */
  28905. VertexBuffer.GetTypeByteLength = function (type) {
  28906. switch (type) {
  28907. case VertexBuffer.BYTE:
  28908. case VertexBuffer.UNSIGNED_BYTE:
  28909. return 1;
  28910. case VertexBuffer.SHORT:
  28911. case VertexBuffer.UNSIGNED_SHORT:
  28912. return 2;
  28913. case VertexBuffer.INT:
  28914. case VertexBuffer.FLOAT:
  28915. return 4;
  28916. default:
  28917. throw new Error("Invalid type '" + type + "'");
  28918. }
  28919. };
  28920. /**
  28921. * Enumerates each value of the given parameters as numbers.
  28922. * @param data the data to enumerate
  28923. * @param byteOffset the byte offset of the data
  28924. * @param byteStride the byte stride of the data
  28925. * @param componentCount the number of components per element
  28926. * @param componentType the type of the component
  28927. * @param count the total number of components
  28928. * @param normalized whether the data is normalized
  28929. * @param callback the callback function called for each value
  28930. */
  28931. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  28932. if (data instanceof Array) {
  28933. var offset = byteOffset / 4;
  28934. var stride = byteStride / 4;
  28935. for (var index = 0; index < count; index += componentCount) {
  28936. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28937. callback(data[offset + componentIndex], index + componentIndex);
  28938. }
  28939. offset += stride;
  28940. }
  28941. }
  28942. else {
  28943. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  28944. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  28945. for (var index = 0; index < count; index += componentCount) {
  28946. var componentByteOffset = byteOffset;
  28947. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  28948. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  28949. callback(value, index + componentIndex);
  28950. componentByteOffset += componentByteLength;
  28951. }
  28952. byteOffset += byteStride;
  28953. }
  28954. }
  28955. };
  28956. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  28957. switch (type) {
  28958. case VertexBuffer.BYTE: {
  28959. var value = dataView.getInt8(byteOffset);
  28960. if (normalized) {
  28961. value = (value + 0.5) / 127.5;
  28962. }
  28963. return value;
  28964. }
  28965. case VertexBuffer.UNSIGNED_BYTE: {
  28966. var value = dataView.getUint8(byteOffset);
  28967. if (normalized) {
  28968. value = value / 255;
  28969. }
  28970. return value;
  28971. }
  28972. case VertexBuffer.SHORT: {
  28973. var value = dataView.getInt16(byteOffset, true);
  28974. if (normalized) {
  28975. value = (value + 0.5) / 16383.5;
  28976. }
  28977. return value;
  28978. }
  28979. case VertexBuffer.UNSIGNED_SHORT: {
  28980. var value = dataView.getUint16(byteOffset, true);
  28981. if (normalized) {
  28982. value = value / 65535;
  28983. }
  28984. return value;
  28985. }
  28986. case VertexBuffer.FLOAT: {
  28987. return dataView.getFloat32(byteOffset, true);
  28988. }
  28989. default: {
  28990. throw new Error("Invalid component type " + type);
  28991. }
  28992. }
  28993. };
  28994. /**
  28995. * The byte type.
  28996. */
  28997. VertexBuffer.BYTE = 5120;
  28998. /**
  28999. * The unsigned byte type.
  29000. */
  29001. VertexBuffer.UNSIGNED_BYTE = 5121;
  29002. /**
  29003. * The short type.
  29004. */
  29005. VertexBuffer.SHORT = 5122;
  29006. /**
  29007. * The unsigned short type.
  29008. */
  29009. VertexBuffer.UNSIGNED_SHORT = 5123;
  29010. /**
  29011. * The integer type.
  29012. */
  29013. VertexBuffer.INT = 5124;
  29014. /**
  29015. * The unsigned integer type.
  29016. */
  29017. VertexBuffer.UNSIGNED_INT = 5125;
  29018. /**
  29019. * The float type.
  29020. */
  29021. VertexBuffer.FLOAT = 5126;
  29022. // Enums
  29023. VertexBuffer._PositionKind = "position";
  29024. VertexBuffer._NormalKind = "normal";
  29025. VertexBuffer._TangentKind = "tangent";
  29026. VertexBuffer._UVKind = "uv";
  29027. VertexBuffer._UV2Kind = "uv2";
  29028. VertexBuffer._UV3Kind = "uv3";
  29029. VertexBuffer._UV4Kind = "uv4";
  29030. VertexBuffer._UV5Kind = "uv5";
  29031. VertexBuffer._UV6Kind = "uv6";
  29032. VertexBuffer._ColorKind = "color";
  29033. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29034. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29035. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29036. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29037. return VertexBuffer;
  29038. }());
  29039. BABYLON.VertexBuffer = VertexBuffer;
  29040. })(BABYLON || (BABYLON = {}));
  29041. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29042. "use strict";
  29043. var BABYLON;
  29044. (function (BABYLON) {
  29045. /**
  29046. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29047. */
  29048. var DummyInternalTextureTracker = /** @class */ (function () {
  29049. function DummyInternalTextureTracker() {
  29050. /**
  29051. * Gets or set the previous tracker in the list
  29052. */
  29053. this.previous = null;
  29054. /**
  29055. * Gets or set the next tracker in the list
  29056. */
  29057. this.next = null;
  29058. }
  29059. return DummyInternalTextureTracker;
  29060. }());
  29061. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29062. })(BABYLON || (BABYLON = {}));
  29063. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29064. "use strict";
  29065. var BABYLON;
  29066. (function (BABYLON) {
  29067. /**
  29068. * Class used to store data associated with WebGL texture data for the engine
  29069. * This class should not be used directly
  29070. */
  29071. var InternalTexture = /** @class */ (function () {
  29072. /**
  29073. * Creates a new InternalTexture
  29074. * @param engine defines the engine to use
  29075. * @param dataSource defines the type of data that will be used
  29076. */
  29077. function InternalTexture(engine, dataSource) {
  29078. /**
  29079. * Observable called when the texture is loaded
  29080. */
  29081. this.onLoadedObservable = new BABYLON.Observable();
  29082. /**
  29083. * Gets or set the previous tracker in the list
  29084. */
  29085. this.previous = null;
  29086. /**
  29087. * Gets or set the next tracker in the list
  29088. */
  29089. this.next = null;
  29090. // Private
  29091. /** @ignore */
  29092. this._initialSlot = -1;
  29093. /** @ignore */
  29094. this._designatedSlot = -1;
  29095. /** @ignore */
  29096. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29097. /** @ignore */
  29098. this._comparisonFunction = 0;
  29099. /** @ignore */
  29100. this._references = 1;
  29101. this._engine = engine;
  29102. this._dataSource = dataSource;
  29103. this._webGLTexture = engine._createTexture();
  29104. }
  29105. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29106. /**
  29107. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29108. */
  29109. get: function () {
  29110. return this._dataSource;
  29111. },
  29112. enumerable: true,
  29113. configurable: true
  29114. });
  29115. /**
  29116. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29117. */
  29118. InternalTexture.prototype.incrementReferences = function () {
  29119. this._references++;
  29120. };
  29121. /**
  29122. * Change the size of the texture (not the size of the content)
  29123. * @param width defines the new width
  29124. * @param height defines the new height
  29125. * @param depth defines the new depth (1 by default)
  29126. */
  29127. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29128. if (depth === void 0) { depth = 1; }
  29129. this.width = width;
  29130. this.height = height;
  29131. this.depth = depth;
  29132. this.baseWidth = width;
  29133. this.baseHeight = height;
  29134. this.baseDepth = depth;
  29135. this._size = width * height * depth;
  29136. };
  29137. /** @ignore */
  29138. InternalTexture.prototype._rebuild = function () {
  29139. var _this = this;
  29140. var proxy;
  29141. this.isReady = false;
  29142. this._cachedCoordinatesMode = null;
  29143. this._cachedWrapU = null;
  29144. this._cachedWrapV = null;
  29145. this._cachedAnisotropicFilteringLevel = null;
  29146. switch (this._dataSource) {
  29147. case InternalTexture.DATASOURCE_TEMP:
  29148. return;
  29149. case InternalTexture.DATASOURCE_URL:
  29150. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29151. _this.isReady = true;
  29152. }, null, this._buffer, undefined, this.format);
  29153. proxy._swapAndDie(this);
  29154. return;
  29155. case InternalTexture.DATASOURCE_RAW:
  29156. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29157. proxy._swapAndDie(this);
  29158. this.isReady = true;
  29159. return;
  29160. case InternalTexture.DATASOURCE_RAW3D:
  29161. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29162. proxy._swapAndDie(this);
  29163. this.isReady = true;
  29164. return;
  29165. case InternalTexture.DATASOURCE_DYNAMIC:
  29166. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29167. proxy._swapAndDie(this);
  29168. // The engine will make sure to update content so no need to flag it as isReady = true
  29169. return;
  29170. case InternalTexture.DATASOURCE_RENDERTARGET:
  29171. var options = new BABYLON.RenderTargetCreationOptions();
  29172. options.generateDepthBuffer = this._generateDepthBuffer;
  29173. options.generateMipMaps = this.generateMipMaps;
  29174. options.generateStencilBuffer = this._generateStencilBuffer;
  29175. options.samplingMode = this.samplingMode;
  29176. options.type = this.type;
  29177. if (this.isCube) {
  29178. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29179. }
  29180. else {
  29181. var size = {
  29182. width: this.width,
  29183. height: this.height
  29184. };
  29185. proxy = this._engine.createRenderTargetTexture(size, options);
  29186. }
  29187. proxy._swapAndDie(this);
  29188. this.isReady = true;
  29189. return;
  29190. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29191. var depthTextureOptions = {
  29192. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29193. comparisonFunction: this._comparisonFunction,
  29194. generateStencil: this._generateStencilBuffer,
  29195. isCube: this.isCube
  29196. };
  29197. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29198. proxy._swapAndDie(this);
  29199. this.isReady = true;
  29200. return;
  29201. case InternalTexture.DATASOURCE_CUBE:
  29202. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29203. _this.isReady = true;
  29204. }, null, this.format, this._extension);
  29205. proxy._swapAndDie(this);
  29206. return;
  29207. case InternalTexture.DATASOURCE_CUBERAW:
  29208. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29209. proxy._swapAndDie(this);
  29210. this.isReady = true;
  29211. return;
  29212. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29213. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29214. if (proxy) {
  29215. proxy._swapAndDie(_this);
  29216. }
  29217. _this.isReady = true;
  29218. }, null, this.format, this._extension);
  29219. return;
  29220. }
  29221. };
  29222. InternalTexture.prototype._swapAndDie = function (target) {
  29223. target._webGLTexture = this._webGLTexture;
  29224. if (this._framebuffer) {
  29225. target._framebuffer = this._framebuffer;
  29226. }
  29227. if (this._depthStencilBuffer) {
  29228. target._depthStencilBuffer = this._depthStencilBuffer;
  29229. }
  29230. if (this._lodTextureHigh) {
  29231. if (target._lodTextureHigh) {
  29232. target._lodTextureHigh.dispose();
  29233. }
  29234. target._lodTextureHigh = this._lodTextureHigh;
  29235. }
  29236. if (this._lodTextureMid) {
  29237. if (target._lodTextureMid) {
  29238. target._lodTextureMid.dispose();
  29239. }
  29240. target._lodTextureMid = this._lodTextureMid;
  29241. }
  29242. if (this._lodTextureLow) {
  29243. if (target._lodTextureLow) {
  29244. target._lodTextureLow.dispose();
  29245. }
  29246. target._lodTextureLow = this._lodTextureLow;
  29247. }
  29248. var cache = this._engine.getLoadedTexturesCache();
  29249. var index = cache.indexOf(this);
  29250. if (index !== -1) {
  29251. cache.splice(index, 1);
  29252. }
  29253. };
  29254. /**
  29255. * Dispose the current allocated resources
  29256. */
  29257. InternalTexture.prototype.dispose = function () {
  29258. if (!this._webGLTexture) {
  29259. return;
  29260. }
  29261. this._references--;
  29262. if (this._references === 0) {
  29263. this._engine._releaseTexture(this);
  29264. this._webGLTexture = null;
  29265. this.previous = null;
  29266. this.next = null;
  29267. }
  29268. };
  29269. /**
  29270. * The source of the texture data is unknown
  29271. */
  29272. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29273. /**
  29274. * Texture data comes from an URL
  29275. */
  29276. InternalTexture.DATASOURCE_URL = 1;
  29277. /**
  29278. * Texture data is only used for temporary storage
  29279. */
  29280. InternalTexture.DATASOURCE_TEMP = 2;
  29281. /**
  29282. * Texture data comes from raw data (ArrayBuffer)
  29283. */
  29284. InternalTexture.DATASOURCE_RAW = 3;
  29285. /**
  29286. * Texture content is dynamic (video or dynamic texture)
  29287. */
  29288. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29289. /**
  29290. * Texture content is generated by rendering to it
  29291. */
  29292. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29293. /**
  29294. * Texture content is part of a multi render target process
  29295. */
  29296. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29297. /**
  29298. * Texture data comes from a cube data file
  29299. */
  29300. InternalTexture.DATASOURCE_CUBE = 7;
  29301. /**
  29302. * Texture data comes from a raw cube data
  29303. */
  29304. InternalTexture.DATASOURCE_CUBERAW = 8;
  29305. /**
  29306. * Texture data come from a prefiltered cube data file
  29307. */
  29308. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29309. /**
  29310. * Texture content is raw 3D data
  29311. */
  29312. InternalTexture.DATASOURCE_RAW3D = 10;
  29313. /**
  29314. * Texture content is a depth texture
  29315. */
  29316. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29317. return InternalTexture;
  29318. }());
  29319. BABYLON.InternalTexture = InternalTexture;
  29320. })(BABYLON || (BABYLON = {}));
  29321. //# sourceMappingURL=babylon.internalTexture.js.map
  29322. "use strict";
  29323. var BABYLON;
  29324. (function (BABYLON) {
  29325. var BaseTexture = /** @class */ (function () {
  29326. function BaseTexture(scene) {
  29327. this._hasAlpha = false;
  29328. this.getAlphaFromRGB = false;
  29329. this.level = 1;
  29330. this.coordinatesIndex = 0;
  29331. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29332. /**
  29333. * | Value | Type | Description |
  29334. * | ----- | ------------------ | ----------- |
  29335. * | 0 | CLAMP_ADDRESSMODE | |
  29336. * | 1 | WRAP_ADDRESSMODE | |
  29337. * | 2 | MIRROR_ADDRESSMODE | |
  29338. */
  29339. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29340. /**
  29341. * | Value | Type | Description |
  29342. * | ----- | ------------------ | ----------- |
  29343. * | 0 | CLAMP_ADDRESSMODE | |
  29344. * | 1 | WRAP_ADDRESSMODE | |
  29345. * | 2 | MIRROR_ADDRESSMODE | |
  29346. */
  29347. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29348. /**
  29349. * | Value | Type | Description |
  29350. * | ----- | ------------------ | ----------- |
  29351. * | 0 | CLAMP_ADDRESSMODE | |
  29352. * | 1 | WRAP_ADDRESSMODE | |
  29353. * | 2 | MIRROR_ADDRESSMODE | |
  29354. */
  29355. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29356. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29357. this.isCube = false;
  29358. this.is3D = false;
  29359. this.gammaSpace = true;
  29360. this.invertZ = false;
  29361. this.lodLevelInAlpha = false;
  29362. this.lodGenerationOffset = 0.0;
  29363. this.lodGenerationScale = 0.8;
  29364. this.isRenderTarget = false;
  29365. this.animations = new Array();
  29366. /**
  29367. * An event triggered when the texture is disposed.
  29368. */
  29369. this.onDisposeObservable = new BABYLON.Observable();
  29370. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29371. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29372. if (this._scene) {
  29373. this._scene.textures.push(this);
  29374. }
  29375. this._uid = null;
  29376. }
  29377. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29378. get: function () {
  29379. return this._hasAlpha;
  29380. },
  29381. set: function (value) {
  29382. if (this._hasAlpha === value) {
  29383. return;
  29384. }
  29385. this._hasAlpha = value;
  29386. if (this._scene) {
  29387. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29388. }
  29389. },
  29390. enumerable: true,
  29391. configurable: true
  29392. });
  29393. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29394. get: function () {
  29395. return this._coordinatesMode;
  29396. },
  29397. /**
  29398. * How a texture is mapped.
  29399. *
  29400. * | Value | Type | Description |
  29401. * | ----- | ----------------------------------- | ----------- |
  29402. * | 0 | EXPLICIT_MODE | |
  29403. * | 1 | SPHERICAL_MODE | |
  29404. * | 2 | PLANAR_MODE | |
  29405. * | 3 | CUBIC_MODE | |
  29406. * | 4 | PROJECTION_MODE | |
  29407. * | 5 | SKYBOX_MODE | |
  29408. * | 6 | INVCUBIC_MODE | |
  29409. * | 7 | EQUIRECTANGULAR_MODE | |
  29410. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29411. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29412. */
  29413. set: function (value) {
  29414. if (this._coordinatesMode === value) {
  29415. return;
  29416. }
  29417. this._coordinatesMode = value;
  29418. if (this._scene) {
  29419. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29420. }
  29421. },
  29422. enumerable: true,
  29423. configurable: true
  29424. });
  29425. Object.defineProperty(BaseTexture.prototype, "uid", {
  29426. get: function () {
  29427. if (!this._uid) {
  29428. this._uid = BABYLON.Tools.RandomId();
  29429. }
  29430. return this._uid;
  29431. },
  29432. enumerable: true,
  29433. configurable: true
  29434. });
  29435. BaseTexture.prototype.toString = function () {
  29436. return this.name;
  29437. };
  29438. BaseTexture.prototype.getClassName = function () {
  29439. return "BaseTexture";
  29440. };
  29441. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29442. set: function (callback) {
  29443. if (this._onDisposeObserver) {
  29444. this.onDisposeObservable.remove(this._onDisposeObserver);
  29445. }
  29446. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29447. },
  29448. enumerable: true,
  29449. configurable: true
  29450. });
  29451. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29452. get: function () {
  29453. return true;
  29454. },
  29455. enumerable: true,
  29456. configurable: true
  29457. });
  29458. BaseTexture.prototype.getScene = function () {
  29459. return this._scene;
  29460. };
  29461. BaseTexture.prototype.getTextureMatrix = function () {
  29462. return BABYLON.Matrix.IdentityReadOnly;
  29463. };
  29464. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29465. return BABYLON.Matrix.IdentityReadOnly;
  29466. };
  29467. BaseTexture.prototype.getInternalTexture = function () {
  29468. return this._texture;
  29469. };
  29470. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29471. return !this.isBlocking || this.isReady();
  29472. };
  29473. BaseTexture.prototype.isReady = function () {
  29474. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29475. this.delayLoad();
  29476. return false;
  29477. }
  29478. if (this._texture) {
  29479. return this._texture.isReady;
  29480. }
  29481. return false;
  29482. };
  29483. BaseTexture.prototype.getSize = function () {
  29484. if (this._texture && this._texture.width) {
  29485. return new BABYLON.Size(this._texture.width, this._texture.height);
  29486. }
  29487. if (this._texture && this._texture._size) {
  29488. return new BABYLON.Size(this._texture._size, this._texture._size);
  29489. }
  29490. return BABYLON.Size.Zero();
  29491. };
  29492. BaseTexture.prototype.getBaseSize = function () {
  29493. if (!this.isReady() || !this._texture)
  29494. return BABYLON.Size.Zero();
  29495. if (this._texture._size) {
  29496. return new BABYLON.Size(this._texture._size, this._texture._size);
  29497. }
  29498. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29499. };
  29500. BaseTexture.prototype.scale = function (ratio) {
  29501. };
  29502. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29503. get: function () {
  29504. return false;
  29505. },
  29506. enumerable: true,
  29507. configurable: true
  29508. });
  29509. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29510. if (!this._scene) {
  29511. return null;
  29512. }
  29513. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29514. for (var index = 0; index < texturesCache.length; index++) {
  29515. var texturesCacheEntry = texturesCache[index];
  29516. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29517. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29518. texturesCacheEntry.incrementReferences();
  29519. return texturesCacheEntry;
  29520. }
  29521. }
  29522. }
  29523. return null;
  29524. };
  29525. BaseTexture.prototype._rebuild = function () {
  29526. };
  29527. BaseTexture.prototype.delayLoad = function () {
  29528. };
  29529. BaseTexture.prototype.clone = function () {
  29530. return null;
  29531. };
  29532. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29533. get: function () {
  29534. if (!this._texture) {
  29535. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29536. }
  29537. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29538. },
  29539. enumerable: true,
  29540. configurable: true
  29541. });
  29542. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29543. get: function () {
  29544. if (!this._texture) {
  29545. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29546. }
  29547. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29548. },
  29549. enumerable: true,
  29550. configurable: true
  29551. });
  29552. BaseTexture.prototype.readPixels = function (faceIndex) {
  29553. if (faceIndex === void 0) { faceIndex = 0; }
  29554. if (!this._texture) {
  29555. return null;
  29556. }
  29557. var size = this.getSize();
  29558. var scene = this.getScene();
  29559. if (!scene) {
  29560. return null;
  29561. }
  29562. var engine = scene.getEngine();
  29563. if (this._texture.isCube) {
  29564. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29565. }
  29566. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29567. };
  29568. BaseTexture.prototype.releaseInternalTexture = function () {
  29569. if (this._texture) {
  29570. this._texture.dispose();
  29571. this._texture = null;
  29572. }
  29573. };
  29574. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29575. get: function () {
  29576. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29577. return null;
  29578. }
  29579. if (!this._texture._sphericalPolynomial) {
  29580. this._texture._sphericalPolynomial =
  29581. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29582. }
  29583. return this._texture._sphericalPolynomial;
  29584. },
  29585. set: function (value) {
  29586. if (this._texture) {
  29587. this._texture._sphericalPolynomial = value;
  29588. }
  29589. },
  29590. enumerable: true,
  29591. configurable: true
  29592. });
  29593. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29594. get: function () {
  29595. if (this._texture) {
  29596. return this._texture._lodTextureHigh;
  29597. }
  29598. return null;
  29599. },
  29600. enumerable: true,
  29601. configurable: true
  29602. });
  29603. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29604. get: function () {
  29605. if (this._texture) {
  29606. return this._texture._lodTextureMid;
  29607. }
  29608. return null;
  29609. },
  29610. enumerable: true,
  29611. configurable: true
  29612. });
  29613. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29614. get: function () {
  29615. if (this._texture) {
  29616. return this._texture._lodTextureLow;
  29617. }
  29618. return null;
  29619. },
  29620. enumerable: true,
  29621. configurable: true
  29622. });
  29623. BaseTexture.prototype.dispose = function () {
  29624. if (!this._scene) {
  29625. return;
  29626. }
  29627. // Animations
  29628. this._scene.stopAnimation(this);
  29629. // Remove from scene
  29630. this._scene._removePendingData(this);
  29631. var index = this._scene.textures.indexOf(this);
  29632. if (index >= 0) {
  29633. this._scene.textures.splice(index, 1);
  29634. }
  29635. if (this._texture === undefined) {
  29636. return;
  29637. }
  29638. // Release
  29639. this.releaseInternalTexture();
  29640. // Callback
  29641. this.onDisposeObservable.notifyObservers(this);
  29642. this.onDisposeObservable.clear();
  29643. };
  29644. BaseTexture.prototype.serialize = function () {
  29645. if (!this.name) {
  29646. return null;
  29647. }
  29648. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29649. // Animations
  29650. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29651. return serializationObject;
  29652. };
  29653. BaseTexture.WhenAllReady = function (textures, callback) {
  29654. var numRemaining = textures.length;
  29655. if (numRemaining === 0) {
  29656. callback();
  29657. return;
  29658. }
  29659. var _loop_1 = function () {
  29660. texture = textures[i];
  29661. if (texture.isReady()) {
  29662. if (--numRemaining === 0) {
  29663. callback();
  29664. }
  29665. }
  29666. else {
  29667. onLoadObservable = texture.onLoadObservable;
  29668. var onLoadCallback_1 = function () {
  29669. onLoadObservable.removeCallback(onLoadCallback_1);
  29670. if (--numRemaining === 0) {
  29671. callback();
  29672. }
  29673. };
  29674. onLoadObservable.add(onLoadCallback_1);
  29675. }
  29676. };
  29677. var texture, onLoadObservable;
  29678. for (var i = 0; i < textures.length; i++) {
  29679. _loop_1();
  29680. }
  29681. };
  29682. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29683. __decorate([
  29684. BABYLON.serialize()
  29685. ], BaseTexture.prototype, "name", void 0);
  29686. __decorate([
  29687. BABYLON.serialize("hasAlpha")
  29688. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29689. __decorate([
  29690. BABYLON.serialize()
  29691. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29692. __decorate([
  29693. BABYLON.serialize()
  29694. ], BaseTexture.prototype, "level", void 0);
  29695. __decorate([
  29696. BABYLON.serialize()
  29697. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29698. __decorate([
  29699. BABYLON.serialize("coordinatesMode")
  29700. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29701. __decorate([
  29702. BABYLON.serialize()
  29703. ], BaseTexture.prototype, "wrapU", void 0);
  29704. __decorate([
  29705. BABYLON.serialize()
  29706. ], BaseTexture.prototype, "wrapV", void 0);
  29707. __decorate([
  29708. BABYLON.serialize()
  29709. ], BaseTexture.prototype, "wrapR", void 0);
  29710. __decorate([
  29711. BABYLON.serialize()
  29712. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  29713. __decorate([
  29714. BABYLON.serialize()
  29715. ], BaseTexture.prototype, "isCube", void 0);
  29716. __decorate([
  29717. BABYLON.serialize()
  29718. ], BaseTexture.prototype, "is3D", void 0);
  29719. __decorate([
  29720. BABYLON.serialize()
  29721. ], BaseTexture.prototype, "gammaSpace", void 0);
  29722. __decorate([
  29723. BABYLON.serialize()
  29724. ], BaseTexture.prototype, "invertZ", void 0);
  29725. __decorate([
  29726. BABYLON.serialize()
  29727. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  29728. __decorate([
  29729. BABYLON.serialize()
  29730. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  29731. __decorate([
  29732. BABYLON.serialize()
  29733. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  29734. __decorate([
  29735. BABYLON.serialize()
  29736. ], BaseTexture.prototype, "isRenderTarget", void 0);
  29737. return BaseTexture;
  29738. }());
  29739. BABYLON.BaseTexture = BaseTexture;
  29740. })(BABYLON || (BABYLON = {}));
  29741. //# sourceMappingURL=babylon.baseTexture.js.map
  29742. "use strict";
  29743. var BABYLON;
  29744. (function (BABYLON) {
  29745. var Texture = /** @class */ (function (_super) {
  29746. __extends(Texture, _super);
  29747. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  29748. if (noMipmap === void 0) { noMipmap = false; }
  29749. if (invertY === void 0) { invertY = true; }
  29750. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  29751. if (onLoad === void 0) { onLoad = null; }
  29752. if (onError === void 0) { onError = null; }
  29753. if (buffer === void 0) { buffer = null; }
  29754. if (deleteBuffer === void 0) { deleteBuffer = false; }
  29755. var _this = _super.call(this, scene) || this;
  29756. _this.uOffset = 0;
  29757. _this.vOffset = 0;
  29758. _this.uScale = 1.0;
  29759. _this.vScale = 1.0;
  29760. _this.uAng = 0;
  29761. _this.vAng = 0;
  29762. _this.wAng = 0;
  29763. _this._isBlocking = true;
  29764. _this.name = url || "";
  29765. _this.url = url;
  29766. _this._noMipmap = noMipmap;
  29767. _this._invertY = invertY;
  29768. _this._samplingMode = samplingMode;
  29769. _this._buffer = buffer;
  29770. _this._deleteBuffer = deleteBuffer;
  29771. if (format) {
  29772. _this._format = format;
  29773. }
  29774. scene = _this.getScene();
  29775. if (!scene) {
  29776. return _this;
  29777. }
  29778. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  29779. var load = function () {
  29780. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  29781. _this.onLoadObservable.notifyObservers(_this);
  29782. }
  29783. if (onLoad) {
  29784. onLoad();
  29785. }
  29786. if (!_this.isBlocking && scene) {
  29787. scene.resetCachedMaterial();
  29788. }
  29789. };
  29790. if (!_this.url) {
  29791. _this._delayedOnLoad = load;
  29792. _this._delayedOnError = onError;
  29793. return _this;
  29794. }
  29795. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  29796. if (!_this._texture) {
  29797. if (!scene.useDelayedTextureLoading) {
  29798. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  29799. if (deleteBuffer) {
  29800. delete _this._buffer;
  29801. }
  29802. }
  29803. else {
  29804. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29805. _this._delayedOnLoad = load;
  29806. _this._delayedOnError = onError;
  29807. }
  29808. }
  29809. else {
  29810. if (_this._texture.isReady) {
  29811. BABYLON.Tools.SetImmediate(function () { return load(); });
  29812. }
  29813. else {
  29814. _this._texture.onLoadedObservable.add(load);
  29815. }
  29816. }
  29817. return _this;
  29818. }
  29819. Object.defineProperty(Texture.prototype, "noMipmap", {
  29820. get: function () {
  29821. return this._noMipmap;
  29822. },
  29823. enumerable: true,
  29824. configurable: true
  29825. });
  29826. Object.defineProperty(Texture.prototype, "isBlocking", {
  29827. get: function () {
  29828. return this._isBlocking;
  29829. },
  29830. set: function (value) {
  29831. this._isBlocking = value;
  29832. },
  29833. enumerable: true,
  29834. configurable: true
  29835. });
  29836. Object.defineProperty(Texture.prototype, "samplingMode", {
  29837. get: function () {
  29838. return this._samplingMode;
  29839. },
  29840. enumerable: true,
  29841. configurable: true
  29842. });
  29843. Texture.prototype.updateURL = function (url) {
  29844. this.url = url;
  29845. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29846. this.delayLoad();
  29847. };
  29848. Texture.prototype.delayLoad = function () {
  29849. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29850. return;
  29851. }
  29852. var scene = this.getScene();
  29853. if (!scene) {
  29854. return;
  29855. }
  29856. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29857. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  29858. if (!this._texture) {
  29859. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  29860. if (this._deleteBuffer) {
  29861. delete this._buffer;
  29862. }
  29863. }
  29864. else {
  29865. if (this._delayedOnLoad) {
  29866. if (this._texture.isReady) {
  29867. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  29868. }
  29869. else {
  29870. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  29871. }
  29872. }
  29873. }
  29874. this._delayedOnLoad = null;
  29875. this._delayedOnError = null;
  29876. };
  29877. Texture.prototype.updateSamplingMode = function (samplingMode) {
  29878. if (!this._texture) {
  29879. return;
  29880. }
  29881. var scene = this.getScene();
  29882. if (!scene) {
  29883. return;
  29884. }
  29885. this._samplingMode = samplingMode;
  29886. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  29887. };
  29888. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  29889. x *= this.uScale;
  29890. y *= this.vScale;
  29891. x -= 0.5 * this.uScale;
  29892. y -= 0.5 * this.vScale;
  29893. z -= 0.5;
  29894. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  29895. t.x += 0.5 * this.uScale + this.uOffset;
  29896. t.y += 0.5 * this.vScale + this.vOffset;
  29897. t.z += 0.5;
  29898. };
  29899. Texture.prototype.getTextureMatrix = function () {
  29900. var _this = this;
  29901. if (this.uOffset === this._cachedUOffset &&
  29902. this.vOffset === this._cachedVOffset &&
  29903. this.uScale === this._cachedUScale &&
  29904. this.vScale === this._cachedVScale &&
  29905. this.uAng === this._cachedUAng &&
  29906. this.vAng === this._cachedVAng &&
  29907. this.wAng === this._cachedWAng) {
  29908. return this._cachedTextureMatrix;
  29909. }
  29910. this._cachedUOffset = this.uOffset;
  29911. this._cachedVOffset = this.vOffset;
  29912. this._cachedUScale = this.uScale;
  29913. this._cachedVScale = this.vScale;
  29914. this._cachedUAng = this.uAng;
  29915. this._cachedVAng = this.vAng;
  29916. this._cachedWAng = this.wAng;
  29917. if (!this._cachedTextureMatrix) {
  29918. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29919. this._rowGenerationMatrix = new BABYLON.Matrix();
  29920. this._t0 = BABYLON.Vector3.Zero();
  29921. this._t1 = BABYLON.Vector3.Zero();
  29922. this._t2 = BABYLON.Vector3.Zero();
  29923. }
  29924. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  29925. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  29926. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  29927. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  29928. this._t1.subtractInPlace(this._t0);
  29929. this._t2.subtractInPlace(this._t0);
  29930. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29931. this._cachedTextureMatrix.m[0] = this._t1.x;
  29932. this._cachedTextureMatrix.m[1] = this._t1.y;
  29933. this._cachedTextureMatrix.m[2] = this._t1.z;
  29934. this._cachedTextureMatrix.m[4] = this._t2.x;
  29935. this._cachedTextureMatrix.m[5] = this._t2.y;
  29936. this._cachedTextureMatrix.m[6] = this._t2.z;
  29937. this._cachedTextureMatrix.m[8] = this._t0.x;
  29938. this._cachedTextureMatrix.m[9] = this._t0.y;
  29939. this._cachedTextureMatrix.m[10] = this._t0.z;
  29940. var scene = this.getScene();
  29941. if (!scene) {
  29942. return this._cachedTextureMatrix;
  29943. }
  29944. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  29945. return mat.hasTexture(_this);
  29946. });
  29947. return this._cachedTextureMatrix;
  29948. };
  29949. Texture.prototype.getReflectionTextureMatrix = function () {
  29950. var _this = this;
  29951. var scene = this.getScene();
  29952. if (!scene) {
  29953. return this._cachedTextureMatrix;
  29954. }
  29955. if (this.uOffset === this._cachedUOffset &&
  29956. this.vOffset === this._cachedVOffset &&
  29957. this.uScale === this._cachedUScale &&
  29958. this.vScale === this._cachedVScale &&
  29959. this.coordinatesMode === this._cachedCoordinatesMode) {
  29960. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  29961. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  29962. return this._cachedTextureMatrix;
  29963. }
  29964. }
  29965. else {
  29966. return this._cachedTextureMatrix;
  29967. }
  29968. }
  29969. if (!this._cachedTextureMatrix) {
  29970. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  29971. }
  29972. if (!this._projectionModeMatrix) {
  29973. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  29974. }
  29975. this._cachedUOffset = this.uOffset;
  29976. this._cachedVOffset = this.vOffset;
  29977. this._cachedUScale = this.uScale;
  29978. this._cachedVScale = this.vScale;
  29979. this._cachedCoordinatesMode = this.coordinatesMode;
  29980. switch (this.coordinatesMode) {
  29981. case Texture.PLANAR_MODE:
  29982. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  29983. this._cachedTextureMatrix[0] = this.uScale;
  29984. this._cachedTextureMatrix[5] = this.vScale;
  29985. this._cachedTextureMatrix[12] = this.uOffset;
  29986. this._cachedTextureMatrix[13] = this.vOffset;
  29987. break;
  29988. case Texture.PROJECTION_MODE:
  29989. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  29990. this._projectionModeMatrix.m[0] = 0.5;
  29991. this._projectionModeMatrix.m[5] = -0.5;
  29992. this._projectionModeMatrix.m[10] = 0.0;
  29993. this._projectionModeMatrix.m[12] = 0.5;
  29994. this._projectionModeMatrix.m[13] = 0.5;
  29995. this._projectionModeMatrix.m[14] = 1.0;
  29996. this._projectionModeMatrix.m[15] = 1.0;
  29997. var projectionMatrix = scene.getProjectionMatrix();
  29998. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  29999. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30000. break;
  30001. default:
  30002. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30003. break;
  30004. }
  30005. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30006. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30007. });
  30008. return this._cachedTextureMatrix;
  30009. };
  30010. Texture.prototype.clone = function () {
  30011. var _this = this;
  30012. return BABYLON.SerializationHelper.Clone(function () {
  30013. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30014. }, this);
  30015. };
  30016. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30017. get: function () {
  30018. if (!this._onLoadObservable) {
  30019. this._onLoadObservable = new BABYLON.Observable();
  30020. }
  30021. return this._onLoadObservable;
  30022. },
  30023. enumerable: true,
  30024. configurable: true
  30025. });
  30026. Texture.prototype.serialize = function () {
  30027. var serializationObject = _super.prototype.serialize.call(this);
  30028. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30029. serializationObject.base64String = this._buffer;
  30030. serializationObject.name = serializationObject.name.replace("data:", "");
  30031. }
  30032. serializationObject.invertY = this._invertY;
  30033. serializationObject.samplingMode = this.samplingMode;
  30034. return serializationObject;
  30035. };
  30036. Texture.prototype.getClassName = function () {
  30037. return "Texture";
  30038. };
  30039. Texture.prototype.dispose = function () {
  30040. _super.prototype.dispose.call(this);
  30041. if (this.onLoadObservable) {
  30042. this.onLoadObservable.clear();
  30043. this._onLoadObservable = null;
  30044. }
  30045. this._delayedOnLoad = null;
  30046. this._delayedOnError = null;
  30047. };
  30048. // Statics
  30049. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30050. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30051. if (onLoad === void 0) { onLoad = null; }
  30052. if (onError === void 0) { onError = null; }
  30053. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30054. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30055. };
  30056. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30057. if (parsedTexture.customType) {
  30058. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30059. // Update Sampling Mode
  30060. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30061. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30062. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30063. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30064. }
  30065. }
  30066. return parsedCustomTexture;
  30067. }
  30068. if (parsedTexture.isCube) {
  30069. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30070. }
  30071. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30072. return null;
  30073. }
  30074. var texture = BABYLON.SerializationHelper.Parse(function () {
  30075. var generateMipMaps = true;
  30076. if (parsedTexture.noMipmap) {
  30077. generateMipMaps = false;
  30078. }
  30079. if (parsedTexture.mirrorPlane) {
  30080. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30081. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30082. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30083. return mirrorTexture;
  30084. }
  30085. else if (parsedTexture.isRenderTarget) {
  30086. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30087. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30088. return renderTargetTexture;
  30089. }
  30090. else {
  30091. var texture;
  30092. if (parsedTexture.base64String) {
  30093. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30094. }
  30095. else {
  30096. var url = rootUrl + parsedTexture.name;
  30097. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30098. url = parsedTexture.url;
  30099. }
  30100. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30101. }
  30102. return texture;
  30103. }
  30104. }, parsedTexture, scene);
  30105. // Update Sampling Mode
  30106. if (parsedTexture.samplingMode) {
  30107. var sampling = parsedTexture.samplingMode;
  30108. if (texture._samplingMode !== sampling) {
  30109. texture.updateSamplingMode(sampling);
  30110. }
  30111. }
  30112. // Animations
  30113. if (parsedTexture.animations) {
  30114. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30115. var parsedAnimation = parsedTexture.animations[animationIndex];
  30116. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30117. }
  30118. }
  30119. return texture;
  30120. };
  30121. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30122. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30123. if (noMipmap === void 0) { noMipmap = false; }
  30124. if (invertY === void 0) { invertY = true; }
  30125. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30126. if (onLoad === void 0) { onLoad = null; }
  30127. if (onError === void 0) { onError = null; }
  30128. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30129. if (name.substr(0, 5) !== "data:") {
  30130. name = "data:" + name;
  30131. }
  30132. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30133. };
  30134. // Constants
  30135. Texture.NEAREST_SAMPLINGMODE = 1;
  30136. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30137. Texture.BILINEAR_SAMPLINGMODE = 2;
  30138. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30139. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30140. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30141. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30142. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30143. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30144. Texture.NEAREST_LINEAR = 7;
  30145. Texture.NEAREST_NEAREST = 8;
  30146. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30147. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30148. Texture.LINEAR_LINEAR = 11;
  30149. Texture.LINEAR_NEAREST = 12;
  30150. Texture.EXPLICIT_MODE = 0;
  30151. Texture.SPHERICAL_MODE = 1;
  30152. Texture.PLANAR_MODE = 2;
  30153. Texture.CUBIC_MODE = 3;
  30154. Texture.PROJECTION_MODE = 4;
  30155. Texture.SKYBOX_MODE = 5;
  30156. Texture.INVCUBIC_MODE = 6;
  30157. Texture.EQUIRECTANGULAR_MODE = 7;
  30158. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30159. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30160. Texture.CLAMP_ADDRESSMODE = 0;
  30161. Texture.WRAP_ADDRESSMODE = 1;
  30162. Texture.MIRROR_ADDRESSMODE = 2;
  30163. /**
  30164. * 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
  30165. */
  30166. Texture.UseSerializedUrlIfAny = false;
  30167. __decorate([
  30168. BABYLON.serialize()
  30169. ], Texture.prototype, "url", void 0);
  30170. __decorate([
  30171. BABYLON.serialize()
  30172. ], Texture.prototype, "uOffset", void 0);
  30173. __decorate([
  30174. BABYLON.serialize()
  30175. ], Texture.prototype, "vOffset", void 0);
  30176. __decorate([
  30177. BABYLON.serialize()
  30178. ], Texture.prototype, "uScale", void 0);
  30179. __decorate([
  30180. BABYLON.serialize()
  30181. ], Texture.prototype, "vScale", void 0);
  30182. __decorate([
  30183. BABYLON.serialize()
  30184. ], Texture.prototype, "uAng", void 0);
  30185. __decorate([
  30186. BABYLON.serialize()
  30187. ], Texture.prototype, "vAng", void 0);
  30188. __decorate([
  30189. BABYLON.serialize()
  30190. ], Texture.prototype, "wAng", void 0);
  30191. __decorate([
  30192. BABYLON.serialize()
  30193. ], Texture.prototype, "isBlocking", null);
  30194. return Texture;
  30195. }(BABYLON.BaseTexture));
  30196. BABYLON.Texture = Texture;
  30197. })(BABYLON || (BABYLON = {}));
  30198. //# sourceMappingURL=babylon.texture.js.map
  30199. "use strict";
  30200. var BABYLON;
  30201. (function (BABYLON) {
  30202. var _InstancesBatch = /** @class */ (function () {
  30203. function _InstancesBatch() {
  30204. this.mustReturn = false;
  30205. this.visibleInstances = new Array();
  30206. this.renderSelf = new Array();
  30207. }
  30208. return _InstancesBatch;
  30209. }());
  30210. BABYLON._InstancesBatch = _InstancesBatch;
  30211. var Mesh = /** @class */ (function (_super) {
  30212. __extends(Mesh, _super);
  30213. /**
  30214. * @constructor
  30215. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30216. * @param {Scene} scene The scene to add this mesh to.
  30217. * @param {Node} parent The parent of this mesh, if it has one
  30218. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30219. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30220. * When false, achieved by calling a clone(), also passing False.
  30221. * This will make creation of children, recursive.
  30222. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30223. */
  30224. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30225. if (scene === void 0) { scene = null; }
  30226. if (parent === void 0) { parent = null; }
  30227. if (source === void 0) { source = null; }
  30228. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30229. var _this = _super.call(this, name, scene) || this;
  30230. // Events
  30231. /**
  30232. * An event triggered before rendering the mesh
  30233. */
  30234. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30235. /**
  30236. * An event triggered after rendering the mesh
  30237. */
  30238. _this.onAfterRenderObservable = new BABYLON.Observable();
  30239. /**
  30240. * An event triggered before drawing the mesh
  30241. */
  30242. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30243. // Members
  30244. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30245. _this.instances = new Array();
  30246. _this._LODLevels = new Array();
  30247. _this._visibleInstances = {};
  30248. _this._renderIdForInstances = new Array();
  30249. _this._batchCache = new _InstancesBatch();
  30250. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30251. // Use by builder only to know what orientation were the mesh build in.
  30252. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30253. _this.overrideMaterialSideOrientation = null;
  30254. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30255. // Will be used to save a source mesh reference, If any
  30256. _this._source = null;
  30257. scene = _this.getScene();
  30258. if (source) {
  30259. // Source mesh
  30260. _this._source = source;
  30261. // Geometry
  30262. if (source._geometry) {
  30263. source._geometry.applyToMesh(_this);
  30264. }
  30265. // Deep copy
  30266. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30267. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30268. // Metadata
  30269. if (source.metadata && source.metadata.clone) {
  30270. _this.metadata = source.metadata.clone();
  30271. }
  30272. else {
  30273. _this.metadata = source.metadata;
  30274. }
  30275. // Tags
  30276. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30277. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30278. }
  30279. // Parent
  30280. _this.parent = source.parent;
  30281. // Pivot
  30282. _this.setPivotMatrix(source.getPivotMatrix());
  30283. _this.id = name + "." + source.id;
  30284. // Material
  30285. _this.material = source.material;
  30286. var index;
  30287. if (!doNotCloneChildren) {
  30288. // Children
  30289. var directDescendants = source.getDescendants(true);
  30290. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30291. var child = directDescendants[index_1];
  30292. if (child.clone) {
  30293. child.clone(name + "." + child.name, _this);
  30294. }
  30295. }
  30296. }
  30297. // Physics clone
  30298. var physicsEngine = _this.getScene().getPhysicsEngine();
  30299. if (clonePhysicsImpostor && physicsEngine) {
  30300. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30301. if (impostor) {
  30302. _this.physicsImpostor = impostor.clone(_this);
  30303. }
  30304. }
  30305. // Particles
  30306. for (index = 0; index < scene.particleSystems.length; index++) {
  30307. var system = scene.particleSystems[index];
  30308. if (system.emitter === source) {
  30309. system.clone(system.name, _this);
  30310. }
  30311. }
  30312. _this.computeWorldMatrix(true);
  30313. }
  30314. // Parent
  30315. if (parent !== null) {
  30316. _this.parent = parent;
  30317. }
  30318. return _this;
  30319. }
  30320. Object.defineProperty(Mesh, "FRONTSIDE", {
  30321. /**
  30322. * Mesh side orientation : usually the external or front surface
  30323. */
  30324. get: function () {
  30325. return Mesh._FRONTSIDE;
  30326. },
  30327. enumerable: true,
  30328. configurable: true
  30329. });
  30330. Object.defineProperty(Mesh, "BACKSIDE", {
  30331. /**
  30332. * Mesh side orientation : usually the internal or back surface
  30333. */
  30334. get: function () {
  30335. return Mesh._BACKSIDE;
  30336. },
  30337. enumerable: true,
  30338. configurable: true
  30339. });
  30340. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30341. /**
  30342. * Mesh side orientation : both internal and external or front and back surfaces
  30343. */
  30344. get: function () {
  30345. return Mesh._DOUBLESIDE;
  30346. },
  30347. enumerable: true,
  30348. configurable: true
  30349. });
  30350. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30351. /**
  30352. * Mesh side orientation : by default, `FRONTSIDE`
  30353. */
  30354. get: function () {
  30355. return Mesh._DEFAULTSIDE;
  30356. },
  30357. enumerable: true,
  30358. configurable: true
  30359. });
  30360. Object.defineProperty(Mesh, "NO_CAP", {
  30361. /**
  30362. * Mesh cap setting : no cap
  30363. */
  30364. get: function () {
  30365. return Mesh._NO_CAP;
  30366. },
  30367. enumerable: true,
  30368. configurable: true
  30369. });
  30370. Object.defineProperty(Mesh, "CAP_START", {
  30371. /**
  30372. * Mesh cap setting : one cap at the beginning of the mesh
  30373. */
  30374. get: function () {
  30375. return Mesh._CAP_START;
  30376. },
  30377. enumerable: true,
  30378. configurable: true
  30379. });
  30380. Object.defineProperty(Mesh, "CAP_END", {
  30381. /**
  30382. * Mesh cap setting : one cap at the end of the mesh
  30383. */
  30384. get: function () {
  30385. return Mesh._CAP_END;
  30386. },
  30387. enumerable: true,
  30388. configurable: true
  30389. });
  30390. Object.defineProperty(Mesh, "CAP_ALL", {
  30391. /**
  30392. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30393. */
  30394. get: function () {
  30395. return Mesh._CAP_ALL;
  30396. },
  30397. enumerable: true,
  30398. configurable: true
  30399. });
  30400. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30401. set: function (callback) {
  30402. if (this._onBeforeDrawObserver) {
  30403. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30404. }
  30405. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30406. },
  30407. enumerable: true,
  30408. configurable: true
  30409. });
  30410. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30411. get: function () {
  30412. return this._morphTargetManager;
  30413. },
  30414. set: function (value) {
  30415. if (this._morphTargetManager === value) {
  30416. return;
  30417. }
  30418. this._morphTargetManager = value;
  30419. this._syncGeometryWithMorphTargetManager();
  30420. },
  30421. enumerable: true,
  30422. configurable: true
  30423. });
  30424. Object.defineProperty(Mesh.prototype, "source", {
  30425. get: function () {
  30426. return this._source;
  30427. },
  30428. enumerable: true,
  30429. configurable: true
  30430. });
  30431. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30432. get: function () {
  30433. return this._unIndexed;
  30434. },
  30435. set: function (value) {
  30436. if (this._unIndexed !== value) {
  30437. this._unIndexed = value;
  30438. this._markSubMeshesAsAttributesDirty();
  30439. }
  30440. },
  30441. enumerable: true,
  30442. configurable: true
  30443. });
  30444. // Methods
  30445. /**
  30446. * Returns the string "Mesh".
  30447. */
  30448. Mesh.prototype.getClassName = function () {
  30449. return "Mesh";
  30450. };
  30451. /**
  30452. * Returns a string.
  30453. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30454. */
  30455. Mesh.prototype.toString = function (fullDetails) {
  30456. var ret = _super.prototype.toString.call(this, fullDetails);
  30457. ret += ", n vertices: " + this.getTotalVertices();
  30458. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30459. if (this.animations) {
  30460. for (var i = 0; i < this.animations.length; i++) {
  30461. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30462. }
  30463. }
  30464. if (fullDetails) {
  30465. if (this._geometry) {
  30466. var ib = this.getIndices();
  30467. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30468. if (vb && ib) {
  30469. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30470. }
  30471. }
  30472. else {
  30473. ret += ", flat shading: UNKNOWN";
  30474. }
  30475. }
  30476. return ret;
  30477. };
  30478. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30479. /**
  30480. * True if the mesh has some Levels Of Details (LOD).
  30481. * Returns a boolean.
  30482. */
  30483. get: function () {
  30484. return this._LODLevels.length > 0;
  30485. },
  30486. enumerable: true,
  30487. configurable: true
  30488. });
  30489. /**
  30490. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30491. * @returns an array of {BABYLON.MeshLODLevel}
  30492. */
  30493. Mesh.prototype.getLODLevels = function () {
  30494. return this._LODLevels;
  30495. };
  30496. Mesh.prototype._sortLODLevels = function () {
  30497. this._LODLevels.sort(function (a, b) {
  30498. if (a.distance < b.distance) {
  30499. return 1;
  30500. }
  30501. if (a.distance > b.distance) {
  30502. return -1;
  30503. }
  30504. return 0;
  30505. });
  30506. };
  30507. /**
  30508. * Add a mesh as LOD level triggered at the given distance.
  30509. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30510. * @param {number} distance The distance from the center of the object to show this level
  30511. * @param {Mesh} mesh The mesh to be added as LOD level
  30512. * @return {Mesh} This mesh (for chaining)
  30513. */
  30514. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30515. if (mesh && mesh._masterMesh) {
  30516. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30517. return this;
  30518. }
  30519. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30520. this._LODLevels.push(level);
  30521. if (mesh) {
  30522. mesh._masterMesh = this;
  30523. }
  30524. this._sortLODLevels();
  30525. return this;
  30526. };
  30527. /**
  30528. * Returns the LOD level mesh at the passed distance or null if not found.
  30529. * It is related to the method `addLODLevel(distance, mesh)`.
  30530. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30531. * Returns an object Mesh or `null`.
  30532. */
  30533. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30534. for (var index = 0; index < this._LODLevels.length; index++) {
  30535. var level = this._LODLevels[index];
  30536. if (level.distance === distance) {
  30537. return level.mesh;
  30538. }
  30539. }
  30540. return null;
  30541. };
  30542. /**
  30543. * Remove a mesh from the LOD array
  30544. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30545. * @param {Mesh} mesh The mesh to be removed.
  30546. * @return {Mesh} This mesh (for chaining)
  30547. */
  30548. Mesh.prototype.removeLODLevel = function (mesh) {
  30549. for (var index = 0; index < this._LODLevels.length; index++) {
  30550. if (this._LODLevels[index].mesh === mesh) {
  30551. this._LODLevels.splice(index, 1);
  30552. if (mesh) {
  30553. mesh._masterMesh = null;
  30554. }
  30555. }
  30556. }
  30557. this._sortLODLevels();
  30558. return this;
  30559. };
  30560. /**
  30561. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30562. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30563. */
  30564. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30565. if (!this._LODLevels || this._LODLevels.length === 0) {
  30566. return this;
  30567. }
  30568. var bSphere;
  30569. if (boundingSphere) {
  30570. bSphere = boundingSphere;
  30571. }
  30572. else {
  30573. var boundingInfo = this.getBoundingInfo();
  30574. bSphere = boundingInfo.boundingSphere;
  30575. }
  30576. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30577. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30578. if (this.onLODLevelSelection) {
  30579. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30580. }
  30581. return this;
  30582. }
  30583. for (var index = 0; index < this._LODLevels.length; index++) {
  30584. var level = this._LODLevels[index];
  30585. if (level.distance < distanceToCamera) {
  30586. if (level.mesh) {
  30587. level.mesh._preActivate();
  30588. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30589. }
  30590. if (this.onLODLevelSelection) {
  30591. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30592. }
  30593. return level.mesh;
  30594. }
  30595. }
  30596. if (this.onLODLevelSelection) {
  30597. this.onLODLevelSelection(distanceToCamera, this, this);
  30598. }
  30599. return this;
  30600. };
  30601. Object.defineProperty(Mesh.prototype, "geometry", {
  30602. /**
  30603. * Returns the mesh internal Geometry object.
  30604. */
  30605. get: function () {
  30606. return this._geometry;
  30607. },
  30608. enumerable: true,
  30609. configurable: true
  30610. });
  30611. /**
  30612. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30613. */
  30614. Mesh.prototype.getTotalVertices = function () {
  30615. if (this._geometry === null || this._geometry === undefined) {
  30616. return 0;
  30617. }
  30618. return this._geometry.getTotalVertices();
  30619. };
  30620. /**
  30621. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30622. * 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.
  30623. * You can force the copy with forceCopy === true
  30624. * Returns null if the mesh has no geometry or no vertex buffer.
  30625. * Possible `kind` values :
  30626. * - BABYLON.VertexBuffer.PositionKind
  30627. * - BABYLON.VertexBuffer.UVKind
  30628. * - BABYLON.VertexBuffer.UV2Kind
  30629. * - BABYLON.VertexBuffer.UV3Kind
  30630. * - BABYLON.VertexBuffer.UV4Kind
  30631. * - BABYLON.VertexBuffer.UV5Kind
  30632. * - BABYLON.VertexBuffer.UV6Kind
  30633. * - BABYLON.VertexBuffer.ColorKind
  30634. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30635. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30636. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30637. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30638. */
  30639. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30640. if (!this._geometry) {
  30641. return null;
  30642. }
  30643. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30644. };
  30645. /**
  30646. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30647. * Returns `null` if the mesh has no geometry.
  30648. * Possible `kind` values :
  30649. * - BABYLON.VertexBuffer.PositionKind
  30650. * - BABYLON.VertexBuffer.UVKind
  30651. * - BABYLON.VertexBuffer.UV2Kind
  30652. * - BABYLON.VertexBuffer.UV3Kind
  30653. * - BABYLON.VertexBuffer.UV4Kind
  30654. * - BABYLON.VertexBuffer.UV5Kind
  30655. * - BABYLON.VertexBuffer.UV6Kind
  30656. * - BABYLON.VertexBuffer.ColorKind
  30657. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30658. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30659. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30660. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30661. */
  30662. Mesh.prototype.getVertexBuffer = function (kind) {
  30663. if (!this._geometry) {
  30664. return null;
  30665. }
  30666. return this._geometry.getVertexBuffer(kind);
  30667. };
  30668. /**
  30669. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30670. * Possible `kind` values :
  30671. * - BABYLON.VertexBuffer.PositionKind
  30672. * - BABYLON.VertexBuffer.UVKind
  30673. * - BABYLON.VertexBuffer.UV2Kind
  30674. * - BABYLON.VertexBuffer.UV3Kind
  30675. * - BABYLON.VertexBuffer.UV4Kind
  30676. * - BABYLON.VertexBuffer.UV5Kind
  30677. * - BABYLON.VertexBuffer.UV6Kind
  30678. * - BABYLON.VertexBuffer.ColorKind
  30679. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30680. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30681. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30682. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30683. */
  30684. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30685. if (!this._geometry) {
  30686. if (this._delayInfo) {
  30687. return this._delayInfo.indexOf(kind) !== -1;
  30688. }
  30689. return false;
  30690. }
  30691. return this._geometry.isVerticesDataPresent(kind);
  30692. };
  30693. /**
  30694. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30695. * Possible `kind` values :
  30696. * - BABYLON.VertexBuffer.PositionKind
  30697. * - BABYLON.VertexBuffer.UVKind
  30698. * - BABYLON.VertexBuffer.UV2Kind
  30699. * - BABYLON.VertexBuffer.UV3Kind
  30700. * - BABYLON.VertexBuffer.UV4Kind
  30701. * - BABYLON.VertexBuffer.UV5Kind
  30702. * - BABYLON.VertexBuffer.UV6Kind
  30703. * - BABYLON.VertexBuffer.ColorKind
  30704. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30705. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30706. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30707. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30708. */
  30709. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  30710. if (!this._geometry) {
  30711. if (this._delayInfo) {
  30712. return this._delayInfo.indexOf(kind) !== -1;
  30713. }
  30714. return false;
  30715. }
  30716. return this._geometry.isVertexBufferUpdatable(kind);
  30717. };
  30718. /**
  30719. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  30720. * Possible `kind` values :
  30721. * - BABYLON.VertexBuffer.PositionKind
  30722. * - BABYLON.VertexBuffer.UVKind
  30723. * - BABYLON.VertexBuffer.UV2Kind
  30724. * - BABYLON.VertexBuffer.UV3Kind
  30725. * - BABYLON.VertexBuffer.UV4Kind
  30726. * - BABYLON.VertexBuffer.UV5Kind
  30727. * - BABYLON.VertexBuffer.UV6Kind
  30728. * - BABYLON.VertexBuffer.ColorKind
  30729. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30730. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30731. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30732. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30733. */
  30734. Mesh.prototype.getVerticesDataKinds = function () {
  30735. if (!this._geometry) {
  30736. var result = new Array();
  30737. if (this._delayInfo) {
  30738. this._delayInfo.forEach(function (kind, index, array) {
  30739. result.push(kind);
  30740. });
  30741. }
  30742. return result;
  30743. }
  30744. return this._geometry.getVerticesDataKinds();
  30745. };
  30746. /**
  30747. * Returns a positive integer : the total number of indices in this mesh geometry.
  30748. * Returns zero if the mesh has no geometry.
  30749. */
  30750. Mesh.prototype.getTotalIndices = function () {
  30751. if (!this._geometry) {
  30752. return 0;
  30753. }
  30754. return this._geometry.getTotalIndices();
  30755. };
  30756. /**
  30757. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  30758. * 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.
  30759. * Returns an empty array if the mesh has no geometry.
  30760. */
  30761. Mesh.prototype.getIndices = function (copyWhenShared) {
  30762. if (!this._geometry) {
  30763. return [];
  30764. }
  30765. return this._geometry.getIndices(copyWhenShared);
  30766. };
  30767. Object.defineProperty(Mesh.prototype, "isBlocked", {
  30768. get: function () {
  30769. return this._masterMesh !== null && this._masterMesh !== undefined;
  30770. },
  30771. enumerable: true,
  30772. configurable: true
  30773. });
  30774. /**
  30775. * Determine if the current mesh is ready to be rendered
  30776. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  30777. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  30778. * @returns true if all associated assets are ready (material, textures, shaders)
  30779. */
  30780. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  30781. if (completeCheck === void 0) { completeCheck = false; }
  30782. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  30783. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30784. return false;
  30785. }
  30786. if (!_super.prototype.isReady.call(this, completeCheck)) {
  30787. return false;
  30788. }
  30789. if (!this.subMeshes || this.subMeshes.length === 0) {
  30790. return true;
  30791. }
  30792. if (!completeCheck) {
  30793. return true;
  30794. }
  30795. var engine = this.getEngine();
  30796. var scene = this.getScene();
  30797. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  30798. this.computeWorldMatrix();
  30799. var mat = this.material || scene.defaultMaterial;
  30800. if (mat) {
  30801. if (mat.storeEffectOnSubMeshes) {
  30802. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30803. var subMesh = _a[_i];
  30804. var effectiveMaterial = subMesh.getMaterial();
  30805. if (effectiveMaterial) {
  30806. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  30807. return false;
  30808. }
  30809. }
  30810. }
  30811. }
  30812. else {
  30813. if (!mat.isReady(this, hardwareInstancedRendering)) {
  30814. return false;
  30815. }
  30816. }
  30817. }
  30818. // Shadows
  30819. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  30820. var light = _c[_b];
  30821. var generator = light.getShadowGenerator();
  30822. if (generator) {
  30823. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  30824. var subMesh = _e[_d];
  30825. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  30826. return false;
  30827. }
  30828. }
  30829. }
  30830. }
  30831. // LOD
  30832. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  30833. var lod = _g[_f];
  30834. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  30835. return false;
  30836. }
  30837. }
  30838. return true;
  30839. };
  30840. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  30841. /**
  30842. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  30843. * This property is pertinent only for updatable parametric shapes.
  30844. */
  30845. get: function () {
  30846. return this._areNormalsFrozen;
  30847. },
  30848. enumerable: true,
  30849. configurable: true
  30850. });
  30851. /**
  30852. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30853. * It has no effect at all on other shapes.
  30854. * It prevents the mesh normals from being recomputed on next `positions` array update.
  30855. * Returns the Mesh.
  30856. */
  30857. Mesh.prototype.freezeNormals = function () {
  30858. this._areNormalsFrozen = true;
  30859. return this;
  30860. };
  30861. /**
  30862. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  30863. * It has no effect at all on other shapes.
  30864. * It reactivates the mesh normals computation if it was previously frozen.
  30865. * Returns the Mesh.
  30866. */
  30867. Mesh.prototype.unfreezeNormals = function () {
  30868. this._areNormalsFrozen = false;
  30869. return this;
  30870. };
  30871. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  30872. /**
  30873. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  30874. */
  30875. set: function (count) {
  30876. this._overridenInstanceCount = count;
  30877. },
  30878. enumerable: true,
  30879. configurable: true
  30880. });
  30881. // Methods
  30882. Mesh.prototype._preActivate = function () {
  30883. var sceneRenderId = this.getScene().getRenderId();
  30884. if (this._preActivateId === sceneRenderId) {
  30885. return this;
  30886. }
  30887. this._preActivateId = sceneRenderId;
  30888. this._visibleInstances = null;
  30889. return this;
  30890. };
  30891. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  30892. if (this._visibleInstances) {
  30893. this._visibleInstances.intermediateDefaultRenderId = renderId;
  30894. }
  30895. return this;
  30896. };
  30897. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  30898. if (!this._visibleInstances) {
  30899. this._visibleInstances = {};
  30900. this._visibleInstances.defaultRenderId = renderId;
  30901. this._visibleInstances.selfDefaultRenderId = this._renderId;
  30902. }
  30903. if (!this._visibleInstances[renderId]) {
  30904. this._visibleInstances[renderId] = new Array();
  30905. }
  30906. this._visibleInstances[renderId].push(instance);
  30907. return this;
  30908. };
  30909. /**
  30910. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  30911. * This means the mesh underlying bounding box and sphere are recomputed.
  30912. * Returns the Mesh.
  30913. */
  30914. Mesh.prototype.refreshBoundingInfo = function () {
  30915. return this._refreshBoundingInfo(false);
  30916. };
  30917. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  30918. if (this._boundingInfo && this._boundingInfo.isLocked) {
  30919. return this;
  30920. }
  30921. var data = this._getPositionData(applySkeleton);
  30922. if (data) {
  30923. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  30924. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30925. }
  30926. if (this.subMeshes) {
  30927. for (var index = 0; index < this.subMeshes.length; index++) {
  30928. this.subMeshes[index].refreshBoundingInfo();
  30929. }
  30930. }
  30931. this._updateBoundingInfo();
  30932. return this;
  30933. };
  30934. Mesh.prototype._getPositionData = function (applySkeleton) {
  30935. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30936. if (data && applySkeleton && this.skeleton) {
  30937. data = BABYLON.Tools.Slice(data);
  30938. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30939. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30940. if (matricesWeightsData && matricesIndicesData) {
  30941. var needExtras = this.numBoneInfluencers > 4;
  30942. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30943. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30944. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  30945. var tempVector = BABYLON.Tmp.Vector3[0];
  30946. var finalMatrix = BABYLON.Tmp.Matrix[0];
  30947. var tempMatrix = BABYLON.Tmp.Matrix[1];
  30948. var matWeightIdx = 0;
  30949. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  30950. finalMatrix.reset();
  30951. var inf;
  30952. var weight;
  30953. for (inf = 0; inf < 4; inf++) {
  30954. weight = matricesWeightsData[matWeightIdx + inf];
  30955. if (weight <= 0)
  30956. break;
  30957. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30958. finalMatrix.addToSelf(tempMatrix);
  30959. }
  30960. if (needExtras) {
  30961. for (inf = 0; inf < 4; inf++) {
  30962. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30963. if (weight <= 0)
  30964. break;
  30965. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30966. finalMatrix.addToSelf(tempMatrix);
  30967. }
  30968. }
  30969. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  30970. tempVector.toArray(data, index);
  30971. }
  30972. }
  30973. }
  30974. return data;
  30975. };
  30976. Mesh.prototype._createGlobalSubMesh = function (force) {
  30977. var totalVertices = this.getTotalVertices();
  30978. if (!totalVertices || !this.getIndices()) {
  30979. return null;
  30980. }
  30981. // Check if we need to recreate the submeshes
  30982. if (this.subMeshes && this.subMeshes.length > 0) {
  30983. var ib = this.getIndices();
  30984. if (!ib) {
  30985. return null;
  30986. }
  30987. var totalIndices = ib.length;
  30988. var needToRecreate = false;
  30989. if (force) {
  30990. needToRecreate = true;
  30991. }
  30992. else {
  30993. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  30994. var submesh = _a[_i];
  30995. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  30996. needToRecreate = true;
  30997. break;
  30998. }
  30999. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31000. needToRecreate = true;
  31001. break;
  31002. }
  31003. }
  31004. }
  31005. if (!needToRecreate) {
  31006. return this.subMeshes[0];
  31007. }
  31008. }
  31009. this.releaseSubMeshes();
  31010. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31011. };
  31012. Mesh.prototype.subdivide = function (count) {
  31013. if (count < 1) {
  31014. return;
  31015. }
  31016. var totalIndices = this.getTotalIndices();
  31017. var subdivisionSize = (totalIndices / count) | 0;
  31018. var offset = 0;
  31019. // Ensure that subdivisionSize is a multiple of 3
  31020. while (subdivisionSize % 3 !== 0) {
  31021. subdivisionSize++;
  31022. }
  31023. this.releaseSubMeshes();
  31024. for (var index = 0; index < count; index++) {
  31025. if (offset >= totalIndices) {
  31026. break;
  31027. }
  31028. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31029. offset += subdivisionSize;
  31030. }
  31031. this.synchronizeInstances();
  31032. };
  31033. /**
  31034. * Sets the vertex data of the mesh geometry for the requested `kind`.
  31035. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  31036. * The `data` are either a numeric array either a Float32Array.
  31037. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  31038. * 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).
  31039. * Note that a new underlying VertexBuffer object is created each call.
  31040. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  31041. *
  31042. * Possible `kind` values :
  31043. * - BABYLON.VertexBuffer.PositionKind
  31044. * - BABYLON.VertexBuffer.UVKind
  31045. * - BABYLON.VertexBuffer.UV2Kind
  31046. * - BABYLON.VertexBuffer.UV3Kind
  31047. * - BABYLON.VertexBuffer.UV4Kind
  31048. * - BABYLON.VertexBuffer.UV5Kind
  31049. * - BABYLON.VertexBuffer.UV6Kind
  31050. * - BABYLON.VertexBuffer.ColorKind
  31051. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31052. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31053. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31054. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31055. *
  31056. * Returns the Mesh.
  31057. */
  31058. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31059. if (updatable === void 0) { updatable = false; }
  31060. if (!this._geometry) {
  31061. var vertexData = new BABYLON.VertexData();
  31062. vertexData.set(data, kind);
  31063. var scene = this.getScene();
  31064. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31065. }
  31066. else {
  31067. this._geometry.setVerticesData(kind, data, updatable, stride);
  31068. }
  31069. return this;
  31070. };
  31071. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31072. if (updatable === void 0) { updatable = true; }
  31073. var vb = this.getVertexBuffer(kind);
  31074. if (!vb || vb.isUpdatable() === updatable) {
  31075. return;
  31076. }
  31077. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31078. };
  31079. /**
  31080. * Sets the mesh VertexBuffer.
  31081. * Returns the Mesh.
  31082. */
  31083. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31084. if (!this._geometry) {
  31085. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31086. }
  31087. this._geometry.setVerticesBuffer(buffer);
  31088. return this;
  31089. };
  31090. /**
  31091. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  31092. * If the mesh has no geometry, it is simply returned as it is.
  31093. * The `data` are either a numeric array either a Float32Array.
  31094. * No new underlying VertexBuffer object is created.
  31095. * 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.
  31096. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  31097. *
  31098. * Possible `kind` values :
  31099. * - BABYLON.VertexBuffer.PositionKind
  31100. * - BABYLON.VertexBuffer.UVKind
  31101. * - BABYLON.VertexBuffer.UV2Kind
  31102. * - BABYLON.VertexBuffer.UV3Kind
  31103. * - BABYLON.VertexBuffer.UV4Kind
  31104. * - BABYLON.VertexBuffer.UV5Kind
  31105. * - BABYLON.VertexBuffer.UV6Kind
  31106. * - BABYLON.VertexBuffer.ColorKind
  31107. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31108. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31109. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31110. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31111. *
  31112. * Returns the Mesh.
  31113. */
  31114. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31115. if (!this._geometry) {
  31116. return this;
  31117. }
  31118. if (!makeItUnique) {
  31119. this._geometry.updateVerticesData(kind, data, updateExtends);
  31120. }
  31121. else {
  31122. this.makeGeometryUnique();
  31123. this.updateVerticesData(kind, data, updateExtends, false);
  31124. }
  31125. return this;
  31126. };
  31127. /**
  31128. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31129. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31130. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31131. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31132. * Returns the Mesh.
  31133. */
  31134. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31135. if (computeNormals === void 0) { computeNormals = true; }
  31136. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31137. if (!positions) {
  31138. return this;
  31139. }
  31140. positionFunction(positions);
  31141. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31142. if (computeNormals) {
  31143. var indices = this.getIndices();
  31144. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31145. if (!normals) {
  31146. return this;
  31147. }
  31148. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31149. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31150. }
  31151. return this;
  31152. };
  31153. /**
  31154. * Creates a un-shared specific occurence of the geometry for the mesh.
  31155. * Returns the Mesh.
  31156. */
  31157. Mesh.prototype.makeGeometryUnique = function () {
  31158. if (!this._geometry) {
  31159. return this;
  31160. }
  31161. var oldGeometry = this._geometry;
  31162. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31163. oldGeometry.releaseForMesh(this, true);
  31164. geometry.applyToMesh(this);
  31165. return this;
  31166. };
  31167. /**
  31168. * Sets the mesh indices.
  31169. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  31170. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  31171. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  31172. * This method creates a new index buffer each call.
  31173. * Returns the Mesh.
  31174. */
  31175. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31176. if (totalVertices === void 0) { totalVertices = null; }
  31177. if (updatable === void 0) { updatable = false; }
  31178. if (!this._geometry) {
  31179. var vertexData = new BABYLON.VertexData();
  31180. vertexData.indices = indices;
  31181. var scene = this.getScene();
  31182. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31183. }
  31184. else {
  31185. this._geometry.setIndices(indices, totalVertices, updatable);
  31186. }
  31187. return this;
  31188. };
  31189. /**
  31190. * Update the current index buffer
  31191. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31192. * Returns the Mesh.
  31193. */
  31194. Mesh.prototype.updateIndices = function (indices, offset) {
  31195. if (!this._geometry) {
  31196. return this;
  31197. }
  31198. this._geometry.updateIndices(indices, offset);
  31199. return this;
  31200. };
  31201. /**
  31202. * Invert the geometry to move from a right handed system to a left handed one.
  31203. * Returns the Mesh.
  31204. */
  31205. Mesh.prototype.toLeftHanded = function () {
  31206. if (!this._geometry) {
  31207. return this;
  31208. }
  31209. this._geometry.toLeftHanded();
  31210. return this;
  31211. };
  31212. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31213. if (!this._geometry) {
  31214. return this;
  31215. }
  31216. var engine = this.getScene().getEngine();
  31217. // Wireframe
  31218. var indexToBind;
  31219. if (this._unIndexed) {
  31220. indexToBind = null;
  31221. }
  31222. else {
  31223. switch (fillMode) {
  31224. case BABYLON.Material.PointFillMode:
  31225. indexToBind = null;
  31226. break;
  31227. case BABYLON.Material.WireFrameFillMode:
  31228. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31229. break;
  31230. default:
  31231. case BABYLON.Material.TriangleFillMode:
  31232. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31233. break;
  31234. }
  31235. }
  31236. // VBOs
  31237. this._geometry._bind(effect, indexToBind);
  31238. return this;
  31239. };
  31240. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31241. if (alternate === void 0) { alternate = false; }
  31242. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31243. return this;
  31244. }
  31245. this.onBeforeDrawObservable.notifyObservers(this);
  31246. var scene = this.getScene();
  31247. var engine = scene.getEngine();
  31248. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31249. // or triangles as points
  31250. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31251. }
  31252. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31253. // Triangles as wireframe
  31254. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31255. }
  31256. else {
  31257. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31258. }
  31259. if (scene._isAlternateRenderingEnabled && !alternate) {
  31260. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31261. if (!effect || !scene.activeCamera) {
  31262. return this;
  31263. }
  31264. scene._switchToAlternateCameraConfiguration(true);
  31265. this._effectiveMaterial.bindView(effect);
  31266. this._effectiveMaterial.bindViewProjection(effect);
  31267. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31268. this._draw(subMesh, fillMode, instancesCount, true);
  31269. engine.setViewport(scene.activeCamera.viewport);
  31270. scene._switchToAlternateCameraConfiguration(false);
  31271. this._effectiveMaterial.bindView(effect);
  31272. this._effectiveMaterial.bindViewProjection(effect);
  31273. }
  31274. return this;
  31275. };
  31276. /**
  31277. * Registers for this mesh a javascript function called just before the rendering process.
  31278. * This function is passed the current mesh.
  31279. * Return the Mesh.
  31280. */
  31281. Mesh.prototype.registerBeforeRender = function (func) {
  31282. this.onBeforeRenderObservable.add(func);
  31283. return this;
  31284. };
  31285. /**
  31286. * Disposes a previously registered javascript function called before the rendering.
  31287. * This function is passed the current mesh.
  31288. * Returns the Mesh.
  31289. */
  31290. Mesh.prototype.unregisterBeforeRender = function (func) {
  31291. this.onBeforeRenderObservable.removeCallback(func);
  31292. return this;
  31293. };
  31294. /**
  31295. * Registers for this mesh a javascript function called just after the rendering is complete.
  31296. * This function is passed the current mesh.
  31297. * Returns the Mesh.
  31298. */
  31299. Mesh.prototype.registerAfterRender = function (func) {
  31300. this.onAfterRenderObservable.add(func);
  31301. return this;
  31302. };
  31303. /**
  31304. * Disposes a previously registered javascript function called after the rendering.
  31305. * This function is passed the current mesh.
  31306. * Return the Mesh.
  31307. */
  31308. Mesh.prototype.unregisterAfterRender = function (func) {
  31309. this.onAfterRenderObservable.removeCallback(func);
  31310. return this;
  31311. };
  31312. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31313. var scene = this.getScene();
  31314. this._batchCache.mustReturn = false;
  31315. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31316. this._batchCache.visibleInstances[subMeshId] = null;
  31317. if (this._visibleInstances) {
  31318. var currentRenderId = scene.getRenderId();
  31319. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31320. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31321. var selfRenderId = this._renderId;
  31322. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31323. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31324. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31325. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31326. }
  31327. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31328. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31329. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31330. this._batchCache.mustReturn = true;
  31331. return this._batchCache;
  31332. }
  31333. if (currentRenderId !== selfRenderId) {
  31334. this._batchCache.renderSelf[subMeshId] = false;
  31335. }
  31336. }
  31337. this._renderIdForInstances[subMeshId] = currentRenderId;
  31338. }
  31339. return this._batchCache;
  31340. };
  31341. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31342. var visibleInstances = batch.visibleInstances[subMesh._id];
  31343. if (!visibleInstances) {
  31344. return this;
  31345. }
  31346. var matricesCount = visibleInstances.length + 1;
  31347. var bufferSize = matricesCount * 16 * 4;
  31348. var currentInstancesBufferSize = this._instancesBufferSize;
  31349. var instancesBuffer = this._instancesBuffer;
  31350. while (this._instancesBufferSize < bufferSize) {
  31351. this._instancesBufferSize *= 2;
  31352. }
  31353. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31354. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31355. }
  31356. var offset = 0;
  31357. var instancesCount = 0;
  31358. var world = this.getWorldMatrix();
  31359. if (batch.renderSelf[subMesh._id]) {
  31360. world.copyToArray(this._instancesData, offset);
  31361. offset += 16;
  31362. instancesCount++;
  31363. }
  31364. if (visibleInstances) {
  31365. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31366. var instance = visibleInstances[instanceIndex];
  31367. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31368. offset += 16;
  31369. instancesCount++;
  31370. }
  31371. }
  31372. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31373. if (instancesBuffer) {
  31374. instancesBuffer.dispose();
  31375. }
  31376. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31377. this._instancesBuffer = instancesBuffer;
  31378. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31379. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31380. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31381. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31382. }
  31383. else {
  31384. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31385. }
  31386. this._bind(subMesh, effect, fillMode);
  31387. this._draw(subMesh, fillMode, instancesCount);
  31388. engine.unbindInstanceAttributes();
  31389. return this;
  31390. };
  31391. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31392. var scene = this.getScene();
  31393. var engine = scene.getEngine();
  31394. if (hardwareInstancedRendering) {
  31395. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31396. }
  31397. else {
  31398. if (batch.renderSelf[subMesh._id]) {
  31399. // Draw
  31400. if (onBeforeDraw) {
  31401. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31402. }
  31403. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31404. }
  31405. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31406. if (visibleInstancesForSubMesh) {
  31407. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31408. var instance = visibleInstancesForSubMesh[instanceIndex];
  31409. // World
  31410. var world = instance.getWorldMatrix();
  31411. if (onBeforeDraw) {
  31412. onBeforeDraw(true, world, effectiveMaterial);
  31413. }
  31414. // Draw
  31415. this._draw(subMesh, fillMode);
  31416. }
  31417. }
  31418. }
  31419. return this;
  31420. };
  31421. /**
  31422. * Triggers the draw call for the mesh.
  31423. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31424. * Returns the Mesh.
  31425. */
  31426. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31427. this.checkOcclusionQuery();
  31428. if (this._isOccluded) {
  31429. return this;
  31430. }
  31431. var scene = this.getScene();
  31432. // Managing instances
  31433. var batch = this._getInstancesRenderList(subMesh._id);
  31434. if (batch.mustReturn) {
  31435. return this;
  31436. }
  31437. // Checking geometry state
  31438. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31439. return this;
  31440. }
  31441. this.onBeforeRenderObservable.notifyObservers(this);
  31442. var engine = scene.getEngine();
  31443. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31444. // Material
  31445. var material = subMesh.getMaterial();
  31446. if (!material) {
  31447. return this;
  31448. }
  31449. this._effectiveMaterial = material;
  31450. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31451. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31452. return this;
  31453. }
  31454. }
  31455. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31456. return this;
  31457. }
  31458. // Alpha mode
  31459. if (enableAlphaMode) {
  31460. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31461. }
  31462. // Outline - step 1
  31463. var savedDepthWrite = engine.getDepthWrite();
  31464. if (this.renderOutline) {
  31465. engine.setDepthWrite(false);
  31466. scene.getOutlineRenderer().render(subMesh, batch);
  31467. engine.setDepthWrite(savedDepthWrite);
  31468. }
  31469. var effect;
  31470. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31471. effect = subMesh.effect;
  31472. }
  31473. else {
  31474. effect = this._effectiveMaterial.getEffect();
  31475. }
  31476. if (!effect) {
  31477. return this;
  31478. }
  31479. var sideOrientation = this.overrideMaterialSideOrientation;
  31480. if (sideOrientation == null) {
  31481. sideOrientation = this._effectiveMaterial.sideOrientation;
  31482. if (this._getWorldMatrixDeterminant() < 0) {
  31483. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31484. }
  31485. }
  31486. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31487. if (this._effectiveMaterial.forceDepthWrite) {
  31488. engine.setDepthWrite(true);
  31489. }
  31490. // Bind
  31491. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31492. if (!hardwareInstancedRendering) {
  31493. this._bind(subMesh, effect, fillMode);
  31494. }
  31495. var world = this.getWorldMatrix();
  31496. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31497. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31498. }
  31499. else {
  31500. this._effectiveMaterial.bind(world, this);
  31501. }
  31502. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31503. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31504. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31505. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31506. }
  31507. // Draw
  31508. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31509. // Unbind
  31510. this._effectiveMaterial.unbind();
  31511. // Outline - step 2
  31512. if (this.renderOutline && savedDepthWrite) {
  31513. engine.setDepthWrite(true);
  31514. engine.setColorWrite(false);
  31515. scene.getOutlineRenderer().render(subMesh, batch);
  31516. engine.setColorWrite(true);
  31517. }
  31518. // Overlay
  31519. if (this.renderOverlay) {
  31520. var currentMode = engine.getAlphaMode();
  31521. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31522. scene.getOutlineRenderer().render(subMesh, batch, true);
  31523. engine.setAlphaMode(currentMode);
  31524. }
  31525. this.onAfterRenderObservable.notifyObservers(this);
  31526. return this;
  31527. };
  31528. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31529. if (isInstance && effectiveMaterial) {
  31530. effectiveMaterial.bindOnlyWorldMatrix(world);
  31531. }
  31532. };
  31533. /**
  31534. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31535. */
  31536. Mesh.prototype.getEmittedParticleSystems = function () {
  31537. var results = new Array();
  31538. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31539. var particleSystem = this.getScene().particleSystems[index];
  31540. if (particleSystem.emitter === this) {
  31541. results.push(particleSystem);
  31542. }
  31543. }
  31544. return results;
  31545. };
  31546. /**
  31547. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31548. */
  31549. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31550. var results = new Array();
  31551. var descendants = this.getDescendants();
  31552. descendants.push(this);
  31553. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31554. var particleSystem = this.getScene().particleSystems[index];
  31555. var emitter = particleSystem.emitter;
  31556. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31557. results.push(particleSystem);
  31558. }
  31559. }
  31560. return results;
  31561. };
  31562. Mesh.prototype._checkDelayState = function () {
  31563. var scene = this.getScene();
  31564. if (this._geometry) {
  31565. this._geometry.load(scene);
  31566. }
  31567. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31568. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31569. this._queueLoad(scene);
  31570. }
  31571. return this;
  31572. };
  31573. Mesh.prototype._queueLoad = function (scene) {
  31574. var _this = this;
  31575. scene._addPendingData(this);
  31576. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31577. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31578. if (data instanceof ArrayBuffer) {
  31579. _this._delayLoadingFunction(data, _this);
  31580. }
  31581. else {
  31582. _this._delayLoadingFunction(JSON.parse(data), _this);
  31583. }
  31584. _this.instances.forEach(function (instance) {
  31585. instance._syncSubMeshes();
  31586. });
  31587. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31588. scene._removePendingData(_this);
  31589. }, function () { }, scene.database, getBinaryData);
  31590. return this;
  31591. };
  31592. /**
  31593. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31594. */
  31595. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31596. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31597. return false;
  31598. }
  31599. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31600. return false;
  31601. }
  31602. this._checkDelayState();
  31603. return true;
  31604. };
  31605. /**
  31606. * Sets the mesh material by the material or multiMaterial `id` property.
  31607. * The material `id` is a string identifying the material or the multiMaterial.
  31608. * This method returns the Mesh.
  31609. */
  31610. Mesh.prototype.setMaterialByID = function (id) {
  31611. var materials = this.getScene().materials;
  31612. var index;
  31613. for (index = materials.length - 1; index > -1; index--) {
  31614. if (materials[index].id === id) {
  31615. this.material = materials[index];
  31616. return this;
  31617. }
  31618. }
  31619. // Multi
  31620. var multiMaterials = this.getScene().multiMaterials;
  31621. for (index = multiMaterials.length - 1; index > -1; index--) {
  31622. if (multiMaterials[index].id === id) {
  31623. this.material = multiMaterials[index];
  31624. return this;
  31625. }
  31626. }
  31627. return this;
  31628. };
  31629. /**
  31630. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31631. */
  31632. Mesh.prototype.getAnimatables = function () {
  31633. var results = new Array();
  31634. if (this.material) {
  31635. results.push(this.material);
  31636. }
  31637. if (this.skeleton) {
  31638. results.push(this.skeleton);
  31639. }
  31640. return results;
  31641. };
  31642. /**
  31643. * Modifies the mesh geometry according to the passed transformation matrix.
  31644. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31645. * The mesh normals are modified accordingly the same transformation.
  31646. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31647. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31648. * Returns the Mesh.
  31649. */
  31650. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31651. // Position
  31652. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31653. return this;
  31654. }
  31655. var submeshes = this.subMeshes.splice(0);
  31656. this._resetPointsArrayCache();
  31657. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31658. var temp = new Array();
  31659. var index;
  31660. for (index = 0; index < data.length; index += 3) {
  31661. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31662. }
  31663. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31664. // Normals
  31665. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31666. return this;
  31667. }
  31668. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31669. temp = [];
  31670. for (index = 0; index < data.length; index += 3) {
  31671. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31672. }
  31673. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31674. // flip faces?
  31675. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31676. this.flipFaces();
  31677. }
  31678. // Restore submeshes
  31679. this.releaseSubMeshes();
  31680. this.subMeshes = submeshes;
  31681. return this;
  31682. };
  31683. /**
  31684. * Modifies the mesh geometry according to its own current World Matrix.
  31685. * The mesh World Matrix is then reset.
  31686. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31687. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31688. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31689. * Returns the Mesh.
  31690. */
  31691. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  31692. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  31693. this.scaling.copyFromFloats(1, 1, 1);
  31694. this.position.copyFromFloats(0, 0, 0);
  31695. this.rotation.copyFromFloats(0, 0, 0);
  31696. //only if quaternion is already set
  31697. if (this.rotationQuaternion) {
  31698. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  31699. }
  31700. this._worldMatrix = BABYLON.Matrix.Identity();
  31701. return this;
  31702. };
  31703. Object.defineProperty(Mesh.prototype, "_positions", {
  31704. // Cache
  31705. get: function () {
  31706. if (this._geometry) {
  31707. return this._geometry._positions;
  31708. }
  31709. return null;
  31710. },
  31711. enumerable: true,
  31712. configurable: true
  31713. });
  31714. Mesh.prototype._resetPointsArrayCache = function () {
  31715. if (this._geometry) {
  31716. this._geometry._resetPointsArrayCache();
  31717. }
  31718. return this;
  31719. };
  31720. Mesh.prototype._generatePointsArray = function () {
  31721. if (this._geometry) {
  31722. return this._geometry._generatePointsArray();
  31723. }
  31724. return false;
  31725. };
  31726. /**
  31727. * Returns a new Mesh object generated from the current mesh properties.
  31728. * This method must not get confused with createInstance().
  31729. * The parameter `name` is a string, the name given to the new mesh.
  31730. * The optional parameter `newParent` can be any Node object (default `null`).
  31731. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  31732. * 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.
  31733. */
  31734. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  31735. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31736. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  31737. };
  31738. /**
  31739. * Releases resources associated with this mesh.
  31740. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  31741. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  31742. */
  31743. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  31744. var _this = this;
  31745. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  31746. this.morphTargetManager = null;
  31747. if (this._geometry) {
  31748. this._geometry.releaseForMesh(this, true);
  31749. }
  31750. // Sources
  31751. var meshes = this.getScene().meshes;
  31752. meshes.forEach(function (abstractMesh) {
  31753. var mesh = abstractMesh;
  31754. if (mesh._source && mesh._source === _this) {
  31755. mesh._source = null;
  31756. }
  31757. });
  31758. this._source = null;
  31759. // Instances
  31760. if (this._instancesBuffer) {
  31761. this._instancesBuffer.dispose();
  31762. this._instancesBuffer = null;
  31763. }
  31764. while (this.instances.length) {
  31765. this.instances[0].dispose();
  31766. }
  31767. // Effect layers.
  31768. var effectLayers = this.getScene().effectLayers;
  31769. for (var i = 0; i < effectLayers.length; i++) {
  31770. var effectLayer = effectLayers[i];
  31771. if (effectLayer) {
  31772. effectLayer._disposeMesh(this);
  31773. }
  31774. }
  31775. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  31776. };
  31777. /**
  31778. * Modifies the mesh geometry according to a displacement map.
  31779. * 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.
  31780. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31781. * This method returns nothing.
  31782. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  31783. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31784. * 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.
  31785. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31786. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31787. *
  31788. * Returns the Mesh.
  31789. */
  31790. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  31791. var _this = this;
  31792. var scene = this.getScene();
  31793. var onload = function (img) {
  31794. // Getting height map data
  31795. var canvas = document.createElement("canvas");
  31796. var context = canvas.getContext("2d");
  31797. var heightMapWidth = img.width;
  31798. var heightMapHeight = img.height;
  31799. canvas.width = heightMapWidth;
  31800. canvas.height = heightMapHeight;
  31801. context.drawImage(img, 0, 0);
  31802. // Create VertexData from map data
  31803. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  31804. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  31805. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  31806. //execute success callback, if set
  31807. if (onSuccess) {
  31808. onSuccess(_this);
  31809. }
  31810. };
  31811. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  31812. return this;
  31813. };
  31814. /**
  31815. * Modifies the mesh geometry according to a displacementMap buffer.
  31816. * 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.
  31817. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  31818. * This method returns nothing.
  31819. * 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.
  31820. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  31821. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  31822. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  31823. * The parameter `uvScale` is an optional vector2 used to scale UV.
  31824. *
  31825. * Returns the Mesh.
  31826. */
  31827. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  31828. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  31829. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  31830. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31831. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  31832. return this;
  31833. }
  31834. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31835. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31836. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31837. var position = BABYLON.Vector3.Zero();
  31838. var normal = BABYLON.Vector3.Zero();
  31839. var uv = BABYLON.Vector2.Zero();
  31840. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  31841. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  31842. for (var index = 0; index < positions.length; index += 3) {
  31843. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  31844. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  31845. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  31846. // Compute height
  31847. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  31848. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  31849. var pos = (u + v * heightMapWidth) * 4;
  31850. var r = buffer[pos] / 255.0;
  31851. var g = buffer[pos + 1] / 255.0;
  31852. var b = buffer[pos + 2] / 255.0;
  31853. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31854. normal.normalize();
  31855. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  31856. position = position.add(normal);
  31857. position.toArray(positions, index);
  31858. }
  31859. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  31860. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  31861. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  31862. return this;
  31863. };
  31864. /**
  31865. * Modify the mesh to get a flat shading rendering.
  31866. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  31867. * This method returns the Mesh.
  31868. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  31869. */
  31870. Mesh.prototype.convertToFlatShadedMesh = function () {
  31871. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  31872. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31873. var kinds = this.getVerticesDataKinds();
  31874. var vbs = {};
  31875. var data = {};
  31876. var newdata = {};
  31877. var updatableNormals = false;
  31878. var kindIndex;
  31879. var kind;
  31880. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31881. kind = kinds[kindIndex];
  31882. var vertexBuffer = this.getVertexBuffer(kind);
  31883. if (kind === BABYLON.VertexBuffer.NormalKind) {
  31884. updatableNormals = vertexBuffer.isUpdatable();
  31885. kinds.splice(kindIndex, 1);
  31886. kindIndex--;
  31887. continue;
  31888. }
  31889. vbs[kind] = vertexBuffer;
  31890. data[kind] = vbs[kind].getData();
  31891. newdata[kind] = [];
  31892. }
  31893. // Save previous submeshes
  31894. var previousSubmeshes = this.subMeshes.slice(0);
  31895. var indices = this.getIndices();
  31896. var totalIndices = this.getTotalIndices();
  31897. // Generating unique vertices per face
  31898. var index;
  31899. for (index = 0; index < totalIndices; index++) {
  31900. var vertexIndex = indices[index];
  31901. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31902. kind = kinds[kindIndex];
  31903. var stride = vbs[kind].getStrideSize();
  31904. for (var offset = 0; offset < stride; offset++) {
  31905. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31906. }
  31907. }
  31908. }
  31909. // Updating faces & normal
  31910. var normals = [];
  31911. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  31912. for (index = 0; index < totalIndices; index += 3) {
  31913. indices[index] = index;
  31914. indices[index + 1] = index + 1;
  31915. indices[index + 2] = index + 2;
  31916. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  31917. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  31918. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  31919. var p1p2 = p1.subtract(p2);
  31920. var p3p2 = p3.subtract(p2);
  31921. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  31922. // Store same normals for every vertex
  31923. for (var localIndex = 0; localIndex < 3; localIndex++) {
  31924. normals.push(normal.x);
  31925. normals.push(normal.y);
  31926. normals.push(normal.z);
  31927. }
  31928. }
  31929. this.setIndices(indices);
  31930. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  31931. // Updating vertex buffers
  31932. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31933. kind = kinds[kindIndex];
  31934. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  31935. }
  31936. // Updating submeshes
  31937. this.releaseSubMeshes();
  31938. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  31939. var previousOne = previousSubmeshes[submeshIndex];
  31940. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  31941. }
  31942. this.synchronizeInstances();
  31943. return this;
  31944. };
  31945. /**
  31946. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  31947. * In other words, more vertices, no more indices and a single bigger VBO.
  31948. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  31949. * Returns the Mesh.
  31950. */
  31951. Mesh.prototype.convertToUnIndexedMesh = function () {
  31952. /// <summary>Remove indices by unfolding faces into buffers</summary>
  31953. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  31954. var kinds = this.getVerticesDataKinds();
  31955. var vbs = {};
  31956. var data = {};
  31957. var newdata = {};
  31958. var kindIndex;
  31959. var kind;
  31960. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31961. kind = kinds[kindIndex];
  31962. var vertexBuffer = this.getVertexBuffer(kind);
  31963. vbs[kind] = vertexBuffer;
  31964. data[kind] = vbs[kind].getData();
  31965. newdata[kind] = [];
  31966. }
  31967. // Save previous submeshes
  31968. var previousSubmeshes = this.subMeshes.slice(0);
  31969. var indices = this.getIndices();
  31970. var totalIndices = this.getTotalIndices();
  31971. // Generating unique vertices per face
  31972. var index;
  31973. for (index = 0; index < totalIndices; index++) {
  31974. var vertexIndex = indices[index];
  31975. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31976. kind = kinds[kindIndex];
  31977. var stride = vbs[kind].getStrideSize();
  31978. for (var offset = 0; offset < stride; offset++) {
  31979. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  31980. }
  31981. }
  31982. }
  31983. // Updating indices
  31984. for (index = 0; index < totalIndices; index += 3) {
  31985. indices[index] = index;
  31986. indices[index + 1] = index + 1;
  31987. indices[index + 2] = index + 2;
  31988. }
  31989. this.setIndices(indices);
  31990. // Updating vertex buffers
  31991. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  31992. kind = kinds[kindIndex];
  31993. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  31994. }
  31995. // Updating submeshes
  31996. this.releaseSubMeshes();
  31997. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  31998. var previousOne = previousSubmeshes[submeshIndex];
  31999. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32000. }
  32001. this._unIndexed = true;
  32002. this.synchronizeInstances();
  32003. return this;
  32004. };
  32005. /**
  32006. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32007. * This method returns the Mesh.
  32008. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32009. */
  32010. Mesh.prototype.flipFaces = function (flipNormals) {
  32011. if (flipNormals === void 0) { flipNormals = false; }
  32012. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32013. var i;
  32014. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32015. for (i = 0; i < vertex_data.normals.length; i++) {
  32016. vertex_data.normals[i] *= -1;
  32017. }
  32018. }
  32019. if (vertex_data.indices) {
  32020. var temp;
  32021. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32022. // reassign indices
  32023. temp = vertex_data.indices[i + 1];
  32024. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32025. vertex_data.indices[i + 2] = temp;
  32026. }
  32027. }
  32028. vertex_data.applyToMesh(this);
  32029. return this;
  32030. };
  32031. // Instances
  32032. /**
  32033. * Creates a new InstancedMesh object from the mesh model.
  32034. * An instance shares the same properties and the same material than its model.
  32035. * Only these properties of each instance can then be set individually :
  32036. * - position
  32037. * - rotation
  32038. * - rotationQuaternion
  32039. * - setPivotMatrix
  32040. * - scaling
  32041. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32042. * Warning : this method is not supported for Line mesh and LineSystem
  32043. */
  32044. Mesh.prototype.createInstance = function (name) {
  32045. return new BABYLON.InstancedMesh(name, this);
  32046. };
  32047. /**
  32048. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32049. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32050. * This method returns the Mesh.
  32051. */
  32052. Mesh.prototype.synchronizeInstances = function () {
  32053. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32054. var instance = this.instances[instanceIndex];
  32055. instance._syncSubMeshes();
  32056. }
  32057. return this;
  32058. };
  32059. /**
  32060. * Simplify the mesh according to the given array of settings.
  32061. * Function will return immediately and will simplify async. It returns the Mesh.
  32062. * @param settings a collection of simplification settings.
  32063. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32064. * @param type the type of simplification to run.
  32065. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32066. */
  32067. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32068. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32069. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32070. this.getScene().simplificationQueue.addTask({
  32071. settings: settings,
  32072. parallelProcessing: parallelProcessing,
  32073. mesh: this,
  32074. simplificationType: simplificationType,
  32075. successCallback: successCallback
  32076. });
  32077. return this;
  32078. };
  32079. /**
  32080. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32081. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32082. * This should be used together with the simplification to avoid disappearing triangles.
  32083. * Returns the Mesh.
  32084. * @param successCallback an optional success callback to be called after the optimization finished.
  32085. */
  32086. Mesh.prototype.optimizeIndices = function (successCallback) {
  32087. var _this = this;
  32088. var indices = this.getIndices();
  32089. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32090. if (!positions || !indices) {
  32091. return this;
  32092. }
  32093. var vectorPositions = new Array();
  32094. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32095. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32096. }
  32097. var dupes = new Array();
  32098. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32099. var realPos = vectorPositions.length - 1 - iteration;
  32100. var testedPosition = vectorPositions[realPos];
  32101. for (var j = 0; j < realPos; ++j) {
  32102. var againstPosition = vectorPositions[j];
  32103. if (testedPosition.equals(againstPosition)) {
  32104. dupes[realPos] = j;
  32105. break;
  32106. }
  32107. }
  32108. }, function () {
  32109. for (var i = 0; i < indices.length; ++i) {
  32110. indices[i] = dupes[indices[i]] || indices[i];
  32111. }
  32112. //indices are now reordered
  32113. var originalSubMeshes = _this.subMeshes.slice(0);
  32114. _this.setIndices(indices);
  32115. _this.subMeshes = originalSubMeshes;
  32116. if (successCallback) {
  32117. successCallback(_this);
  32118. }
  32119. });
  32120. return this;
  32121. };
  32122. Mesh.prototype.serialize = function (serializationObject) {
  32123. serializationObject.name = this.name;
  32124. serializationObject.id = this.id;
  32125. serializationObject.type = this.getClassName();
  32126. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32127. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32128. }
  32129. serializationObject.position = this.position.asArray();
  32130. if (this.rotationQuaternion) {
  32131. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32132. }
  32133. else if (this.rotation) {
  32134. serializationObject.rotation = this.rotation.asArray();
  32135. }
  32136. serializationObject.scaling = this.scaling.asArray();
  32137. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32138. serializationObject.isEnabled = this.isEnabled(false);
  32139. serializationObject.isVisible = this.isVisible;
  32140. serializationObject.infiniteDistance = this.infiniteDistance;
  32141. serializationObject.pickable = this.isPickable;
  32142. serializationObject.receiveShadows = this.receiveShadows;
  32143. serializationObject.billboardMode = this.billboardMode;
  32144. serializationObject.visibility = this.visibility;
  32145. serializationObject.checkCollisions = this.checkCollisions;
  32146. serializationObject.isBlocker = this.isBlocker;
  32147. // Parent
  32148. if (this.parent) {
  32149. serializationObject.parentId = this.parent.id;
  32150. }
  32151. // Geometry
  32152. serializationObject.isUnIndexed = this.isUnIndexed;
  32153. var geometry = this._geometry;
  32154. if (geometry) {
  32155. var geometryId = geometry.id;
  32156. serializationObject.geometryId = geometryId;
  32157. // SubMeshes
  32158. serializationObject.subMeshes = [];
  32159. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32160. var subMesh = this.subMeshes[subIndex];
  32161. serializationObject.subMeshes.push({
  32162. materialIndex: subMesh.materialIndex,
  32163. verticesStart: subMesh.verticesStart,
  32164. verticesCount: subMesh.verticesCount,
  32165. indexStart: subMesh.indexStart,
  32166. indexCount: subMesh.indexCount
  32167. });
  32168. }
  32169. }
  32170. // Material
  32171. if (this.material) {
  32172. serializationObject.materialId = this.material.id;
  32173. }
  32174. else {
  32175. this.material = null;
  32176. }
  32177. // Morph targets
  32178. if (this.morphTargetManager) {
  32179. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32180. }
  32181. // Skeleton
  32182. if (this.skeleton) {
  32183. serializationObject.skeletonId = this.skeleton.id;
  32184. }
  32185. // Physics
  32186. //TODO implement correct serialization for physics impostors.
  32187. var impostor = this.getPhysicsImpostor();
  32188. if (impostor) {
  32189. serializationObject.physicsMass = impostor.getParam("mass");
  32190. serializationObject.physicsFriction = impostor.getParam("friction");
  32191. serializationObject.physicsRestitution = impostor.getParam("mass");
  32192. serializationObject.physicsImpostor = impostor.type;
  32193. }
  32194. // Metadata
  32195. if (this.metadata) {
  32196. serializationObject.metadata = this.metadata;
  32197. }
  32198. // Instances
  32199. serializationObject.instances = [];
  32200. for (var index = 0; index < this.instances.length; index++) {
  32201. var instance = this.instances[index];
  32202. var serializationInstance = {
  32203. name: instance.name,
  32204. id: instance.id,
  32205. position: instance.position.asArray(),
  32206. scaling: instance.scaling.asArray()
  32207. };
  32208. if (instance.rotationQuaternion) {
  32209. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32210. }
  32211. else if (instance.rotation) {
  32212. serializationInstance.rotation = instance.rotation.asArray();
  32213. }
  32214. serializationObject.instances.push(serializationInstance);
  32215. // Animations
  32216. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32217. serializationInstance.ranges = instance.serializeAnimationRanges();
  32218. }
  32219. //
  32220. // Animations
  32221. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32222. serializationObject.ranges = this.serializeAnimationRanges();
  32223. // Layer mask
  32224. serializationObject.layerMask = this.layerMask;
  32225. // Alpha
  32226. serializationObject.alphaIndex = this.alphaIndex;
  32227. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32228. // Overlay
  32229. serializationObject.overlayAlpha = this.overlayAlpha;
  32230. serializationObject.overlayColor = this.overlayColor.asArray();
  32231. serializationObject.renderOverlay = this.renderOverlay;
  32232. // Fog
  32233. serializationObject.applyFog = this.applyFog;
  32234. // Action Manager
  32235. if (this.actionManager) {
  32236. serializationObject.actions = this.actionManager.serialize(this.name);
  32237. }
  32238. };
  32239. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32240. if (!this.geometry) {
  32241. return;
  32242. }
  32243. this._markSubMeshesAsAttributesDirty();
  32244. var morphTargetManager = this._morphTargetManager;
  32245. if (morphTargetManager && morphTargetManager.vertexCount) {
  32246. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32247. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32248. this.morphTargetManager = null;
  32249. return;
  32250. }
  32251. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32252. var morphTarget = morphTargetManager.getActiveTarget(index);
  32253. var positions = morphTarget.getPositions();
  32254. if (!positions) {
  32255. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32256. return;
  32257. }
  32258. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32259. var normals = morphTarget.getNormals();
  32260. if (normals) {
  32261. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32262. }
  32263. var tangents = morphTarget.getTangents();
  32264. if (tangents) {
  32265. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32266. }
  32267. }
  32268. }
  32269. else {
  32270. var index = 0;
  32271. // Positions
  32272. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32273. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32274. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32275. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32276. }
  32277. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32278. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32279. }
  32280. index++;
  32281. }
  32282. }
  32283. };
  32284. // Statics
  32285. /**
  32286. * Returns a new Mesh object parsed from the source provided.
  32287. * The parameter `parsedMesh` is the source.
  32288. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32289. */
  32290. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32291. var mesh;
  32292. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32293. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32294. }
  32295. else {
  32296. mesh = new Mesh(parsedMesh.name, scene);
  32297. }
  32298. mesh.id = parsedMesh.id;
  32299. if (BABYLON.Tags) {
  32300. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32301. }
  32302. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32303. if (parsedMesh.metadata !== undefined) {
  32304. mesh.metadata = parsedMesh.metadata;
  32305. }
  32306. if (parsedMesh.rotationQuaternion) {
  32307. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32308. }
  32309. else if (parsedMesh.rotation) {
  32310. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32311. }
  32312. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32313. if (parsedMesh.localMatrix) {
  32314. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32315. }
  32316. else if (parsedMesh.pivotMatrix) {
  32317. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32318. }
  32319. mesh.setEnabled(parsedMesh.isEnabled);
  32320. mesh.isVisible = parsedMesh.isVisible;
  32321. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32322. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32323. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32324. if (parsedMesh.applyFog !== undefined) {
  32325. mesh.applyFog = parsedMesh.applyFog;
  32326. }
  32327. if (parsedMesh.pickable !== undefined) {
  32328. mesh.isPickable = parsedMesh.pickable;
  32329. }
  32330. if (parsedMesh.alphaIndex !== undefined) {
  32331. mesh.alphaIndex = parsedMesh.alphaIndex;
  32332. }
  32333. mesh.receiveShadows = parsedMesh.receiveShadows;
  32334. mesh.billboardMode = parsedMesh.billboardMode;
  32335. if (parsedMesh.visibility !== undefined) {
  32336. mesh.visibility = parsedMesh.visibility;
  32337. }
  32338. mesh.checkCollisions = parsedMesh.checkCollisions;
  32339. if (parsedMesh.isBlocker !== undefined) {
  32340. mesh.isBlocker = parsedMesh.isBlocker;
  32341. }
  32342. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32343. // freezeWorldMatrix
  32344. if (parsedMesh.freezeWorldMatrix) {
  32345. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32346. }
  32347. // Parent
  32348. if (parsedMesh.parentId) {
  32349. mesh._waitingParentId = parsedMesh.parentId;
  32350. }
  32351. // Actions
  32352. if (parsedMesh.actions !== undefined) {
  32353. mesh._waitingActions = parsedMesh.actions;
  32354. }
  32355. // Overlay
  32356. if (parsedMesh.overlayAlpha !== undefined) {
  32357. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32358. }
  32359. if (parsedMesh.overlayColor !== undefined) {
  32360. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32361. }
  32362. if (parsedMesh.renderOverlay !== undefined) {
  32363. mesh.renderOverlay = parsedMesh.renderOverlay;
  32364. }
  32365. // Geometry
  32366. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32367. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32368. if (parsedMesh.delayLoadingFile) {
  32369. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32370. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32371. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32372. if (parsedMesh._binaryInfo) {
  32373. mesh._binaryInfo = parsedMesh._binaryInfo;
  32374. }
  32375. mesh._delayInfo = [];
  32376. if (parsedMesh.hasUVs) {
  32377. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32378. }
  32379. if (parsedMesh.hasUVs2) {
  32380. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32381. }
  32382. if (parsedMesh.hasUVs3) {
  32383. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32384. }
  32385. if (parsedMesh.hasUVs4) {
  32386. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32387. }
  32388. if (parsedMesh.hasUVs5) {
  32389. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32390. }
  32391. if (parsedMesh.hasUVs6) {
  32392. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32393. }
  32394. if (parsedMesh.hasColors) {
  32395. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32396. }
  32397. if (parsedMesh.hasMatricesIndices) {
  32398. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32399. }
  32400. if (parsedMesh.hasMatricesWeights) {
  32401. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32402. }
  32403. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32404. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32405. mesh._checkDelayState();
  32406. }
  32407. }
  32408. else {
  32409. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32410. }
  32411. // Material
  32412. if (parsedMesh.materialId) {
  32413. mesh.setMaterialByID(parsedMesh.materialId);
  32414. }
  32415. else {
  32416. mesh.material = null;
  32417. }
  32418. // Morph targets
  32419. if (parsedMesh.morphTargetManagerId > -1) {
  32420. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32421. }
  32422. // Skeleton
  32423. if (parsedMesh.skeletonId > -1) {
  32424. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32425. if (parsedMesh.numBoneInfluencers) {
  32426. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32427. }
  32428. }
  32429. // Animations
  32430. if (parsedMesh.animations) {
  32431. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32432. var parsedAnimation = parsedMesh.animations[animationIndex];
  32433. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32434. }
  32435. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32436. }
  32437. if (parsedMesh.autoAnimate) {
  32438. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32439. }
  32440. // Layer Mask
  32441. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32442. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32443. }
  32444. else {
  32445. mesh.layerMask = 0x0FFFFFFF;
  32446. }
  32447. // Physics
  32448. if (parsedMesh.physicsImpostor) {
  32449. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32450. mass: parsedMesh.physicsMass,
  32451. friction: parsedMesh.physicsFriction,
  32452. restitution: parsedMesh.physicsRestitution
  32453. }, scene);
  32454. }
  32455. // Instances
  32456. if (parsedMesh.instances) {
  32457. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32458. var parsedInstance = parsedMesh.instances[index];
  32459. var instance = mesh.createInstance(parsedInstance.name);
  32460. if (parsedInstance.id) {
  32461. instance.id = parsedInstance.id;
  32462. }
  32463. if (BABYLON.Tags) {
  32464. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32465. }
  32466. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32467. if (parsedInstance.parentId) {
  32468. instance._waitingParentId = parsedInstance.parentId;
  32469. }
  32470. if (parsedInstance.rotationQuaternion) {
  32471. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32472. }
  32473. else if (parsedInstance.rotation) {
  32474. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32475. }
  32476. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32477. instance.checkCollisions = mesh.checkCollisions;
  32478. if (parsedMesh.animations) {
  32479. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32480. parsedAnimation = parsedMesh.animations[animationIndex];
  32481. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32482. }
  32483. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32484. }
  32485. }
  32486. }
  32487. return mesh;
  32488. };
  32489. /**
  32490. * Creates a ribbon mesh.
  32491. * Please consider using the same method from the MeshBuilder class instead.
  32492. * 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.
  32493. *
  32494. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32495. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32496. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32497. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32498. * 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.
  32499. * 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.
  32500. * 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
  32501. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32502. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32503. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32504. */
  32505. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32506. if (closeArray === void 0) { closeArray = false; }
  32507. if (updatable === void 0) { updatable = false; }
  32508. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32509. pathArray: pathArray,
  32510. closeArray: closeArray,
  32511. closePath: closePath,
  32512. offset: offset,
  32513. updatable: updatable,
  32514. sideOrientation: sideOrientation,
  32515. instance: instance
  32516. }, scene);
  32517. };
  32518. /**
  32519. * Creates a plane polygonal mesh. By default, this is a disc.
  32520. * Please consider using the same method from the MeshBuilder class instead.
  32521. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32522. * 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.
  32523. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32524. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32526. */
  32527. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32528. if (scene === void 0) { scene = null; }
  32529. var options = {
  32530. radius: radius,
  32531. tessellation: tessellation,
  32532. sideOrientation: sideOrientation,
  32533. updatable: updatable
  32534. };
  32535. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32536. };
  32537. /**
  32538. * Creates a box mesh.
  32539. * Please consider using the same method from the MeshBuilder class instead.
  32540. * The parameter `size` sets the size (float) of each box side (default 1).
  32541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32542. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32544. */
  32545. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32546. if (scene === void 0) { scene = null; }
  32547. var options = {
  32548. size: size,
  32549. sideOrientation: sideOrientation,
  32550. updatable: updatable
  32551. };
  32552. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32553. };
  32554. /**
  32555. * Creates a sphere mesh.
  32556. * Please consider using the same method from the MeshBuilder class instead.
  32557. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32558. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32562. */
  32563. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32564. var options = {
  32565. segments: segments,
  32566. diameterX: diameter,
  32567. diameterY: diameter,
  32568. diameterZ: diameter,
  32569. sideOrientation: sideOrientation,
  32570. updatable: updatable
  32571. };
  32572. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32573. };
  32574. /**
  32575. * Creates a cylinder or a cone mesh.
  32576. * Please consider using the same method from the MeshBuilder class instead.
  32577. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32578. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32579. * 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.
  32580. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32581. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32583. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32585. */
  32586. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32587. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32588. if (scene !== undefined) {
  32589. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32590. updatable = scene;
  32591. }
  32592. scene = subdivisions;
  32593. subdivisions = 1;
  32594. }
  32595. var options = {
  32596. height: height,
  32597. diameterTop: diameterTop,
  32598. diameterBottom: diameterBottom,
  32599. tessellation: tessellation,
  32600. subdivisions: subdivisions,
  32601. sideOrientation: sideOrientation,
  32602. updatable: updatable
  32603. };
  32604. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32605. };
  32606. // Torus (Code from SharpDX.org)
  32607. /**
  32608. * Creates a torus mesh.
  32609. * Please consider using the same method from the MeshBuilder class instead.
  32610. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32611. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32612. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32613. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32614. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32616. */
  32617. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32618. var options = {
  32619. diameter: diameter,
  32620. thickness: thickness,
  32621. tessellation: tessellation,
  32622. sideOrientation: sideOrientation,
  32623. updatable: updatable
  32624. };
  32625. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32626. };
  32627. /**
  32628. * Creates a torus knot mesh.
  32629. * Please consider using the same method from the MeshBuilder class instead.
  32630. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32631. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32632. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32633. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32634. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32635. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32637. */
  32638. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32639. var options = {
  32640. radius: radius,
  32641. tube: tube,
  32642. radialSegments: radialSegments,
  32643. tubularSegments: tubularSegments,
  32644. p: p,
  32645. q: q,
  32646. sideOrientation: sideOrientation,
  32647. updatable: updatable
  32648. };
  32649. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32650. };
  32651. /**
  32652. * Creates a line mesh.
  32653. * Please consider using the same method from the MeshBuilder class instead.
  32654. * 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.
  32655. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32656. * The parameter `points` is an array successive Vector3.
  32657. * 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
  32658. * When updating an instance, remember that only point positions can change, not the number of points.
  32659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32660. */
  32661. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32662. if (scene === void 0) { scene = null; }
  32663. if (updatable === void 0) { updatable = false; }
  32664. if (instance === void 0) { instance = null; }
  32665. var options = {
  32666. points: points,
  32667. updatable: updatable,
  32668. instance: instance
  32669. };
  32670. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32671. };
  32672. /**
  32673. * Creates a dashed line mesh.
  32674. * Please consider using the same method from the MeshBuilder class instead.
  32675. * 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.
  32676. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32677. * The parameter `points` is an array successive Vector3.
  32678. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32679. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32680. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32681. * 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
  32682. * When updating an instance, remember that only point positions can change, not the number of points.
  32683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32684. */
  32685. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32686. if (scene === void 0) { scene = null; }
  32687. var options = {
  32688. points: points,
  32689. dashSize: dashSize,
  32690. gapSize: gapSize,
  32691. dashNb: dashNb,
  32692. updatable: updatable,
  32693. instance: instance
  32694. };
  32695. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  32696. };
  32697. /**
  32698. * Creates a polygon mesh.
  32699. * Please consider using the same method from the MeshBuilder class instead.
  32700. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  32701. * 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.
  32702. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32703. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32704. * Remember you can only change the shape positions, not their number when updating a polygon.
  32705. */
  32706. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  32707. var options = {
  32708. shape: shape,
  32709. holes: holes,
  32710. updatable: updatable,
  32711. sideOrientation: sideOrientation
  32712. };
  32713. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  32714. };
  32715. /**
  32716. * Creates an extruded polygon mesh, with depth in the Y direction.
  32717. * Please consider using the same method from the MeshBuilder class instead.
  32718. */
  32719. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  32720. var options = {
  32721. shape: shape,
  32722. holes: holes,
  32723. depth: depth,
  32724. updatable: updatable,
  32725. sideOrientation: sideOrientation
  32726. };
  32727. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  32728. };
  32729. /**
  32730. * Creates an extruded shape mesh.
  32731. * 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.
  32732. * Please consider using the same method from the MeshBuilder class instead.
  32733. *
  32734. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32735. * 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
  32736. * extruded along the Z axis.
  32737. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32738. * 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.
  32739. * The parameter `scale` (float, default 1) is the value to scale the shape.
  32740. * 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
  32741. * 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
  32742. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32743. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32744. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32745. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32746. */
  32747. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  32748. if (scene === void 0) { scene = null; }
  32749. var options = {
  32750. shape: shape,
  32751. path: path,
  32752. scale: scale,
  32753. rotation: rotation,
  32754. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32755. sideOrientation: sideOrientation,
  32756. instance: instance,
  32757. updatable: updatable
  32758. };
  32759. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  32760. };
  32761. /**
  32762. * Creates an custom extruded shape mesh.
  32763. * 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.
  32764. * Please consider using the same method from the MeshBuilder class instead.
  32765. *
  32766. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  32767. * 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
  32768. * extruded along the Z axis.
  32769. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  32770. * 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
  32771. * and the distance of this point from the begining of the path :
  32772. * ```javascript
  32773. * var rotationFunction = function(i, distance) {
  32774. * // do things
  32775. * return rotationValue; }
  32776. * ```
  32777. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  32778. * 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
  32779. * and the distance of this point from the begining of the path :
  32780. * ```javascript
  32781. * var scaleFunction = function(i, distance) {
  32782. * // do things
  32783. * return scaleValue;}
  32784. * ```
  32785. * It must returns a float value that will be the scale value applied to the shape on each path point.
  32786. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  32787. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  32788. * 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
  32789. * 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
  32790. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  32791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32794. */
  32795. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  32796. var options = {
  32797. shape: shape,
  32798. path: path,
  32799. scaleFunction: scaleFunction,
  32800. rotationFunction: rotationFunction,
  32801. ribbonCloseArray: ribbonCloseArray,
  32802. ribbonClosePath: ribbonClosePath,
  32803. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  32804. sideOrientation: sideOrientation,
  32805. instance: instance,
  32806. updatable: updatable
  32807. };
  32808. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  32809. };
  32810. /**
  32811. * Creates lathe mesh.
  32812. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  32813. * Please consider using the same method from the MeshBuilder class instead.
  32814. * 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
  32815. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  32816. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  32817. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  32818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32819. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32821. */
  32822. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  32823. var options = {
  32824. shape: shape,
  32825. radius: radius,
  32826. tessellation: tessellation,
  32827. sideOrientation: sideOrientation,
  32828. updatable: updatable
  32829. };
  32830. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  32831. };
  32832. /**
  32833. * Creates a plane mesh.
  32834. * Please consider using the same method from the MeshBuilder class instead.
  32835. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  32836. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32837. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32839. */
  32840. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  32841. var options = {
  32842. size: size,
  32843. width: size,
  32844. height: size,
  32845. sideOrientation: sideOrientation,
  32846. updatable: updatable
  32847. };
  32848. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  32849. };
  32850. /**
  32851. * Creates a ground mesh.
  32852. * Please consider using the same method from the MeshBuilder class instead.
  32853. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  32854. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  32855. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32856. */
  32857. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  32858. var options = {
  32859. width: width,
  32860. height: height,
  32861. subdivisions: subdivisions,
  32862. updatable: updatable
  32863. };
  32864. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  32865. };
  32866. /**
  32867. * Creates a tiled ground mesh.
  32868. * Please consider using the same method from the MeshBuilder class instead.
  32869. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  32870. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  32871. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  32872. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  32873. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  32874. * numbers of subdivisions on the ground width and height of each tile.
  32875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32876. */
  32877. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  32878. var options = {
  32879. xmin: xmin,
  32880. zmin: zmin,
  32881. xmax: xmax,
  32882. zmax: zmax,
  32883. subdivisions: subdivisions,
  32884. precision: precision,
  32885. updatable: updatable
  32886. };
  32887. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  32888. };
  32889. /**
  32890. * Creates a ground mesh from a height map.
  32891. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  32892. * Please consider using the same method from the MeshBuilder class instead.
  32893. * The parameter `url` sets the URL of the height map image resource.
  32894. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  32895. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  32896. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  32897. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  32898. * 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).
  32899. * This function is passed the newly built mesh :
  32900. * ```javascript
  32901. * function(mesh) { // do things
  32902. * return; }
  32903. * ```
  32904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32905. */
  32906. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  32907. var options = {
  32908. width: width,
  32909. height: height,
  32910. subdivisions: subdivisions,
  32911. minHeight: minHeight,
  32912. maxHeight: maxHeight,
  32913. updatable: updatable,
  32914. onReady: onReady
  32915. };
  32916. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  32917. };
  32918. /**
  32919. * Creates a tube mesh.
  32920. * 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.
  32921. * Please consider using the same method from the MeshBuilder class instead.
  32922. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  32923. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  32924. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  32925. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  32926. * 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.
  32927. * It must return a radius value (positive float) :
  32928. * ```javascript
  32929. * var radiusFunction = function(i, distance) {
  32930. * // do things
  32931. * return radius; }
  32932. * ```
  32933. * 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
  32934. * 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
  32935. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32936. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32938. */
  32939. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  32940. var options = {
  32941. path: path,
  32942. radius: radius,
  32943. tessellation: tessellation,
  32944. radiusFunction: radiusFunction,
  32945. arc: 1,
  32946. cap: cap,
  32947. updatable: updatable,
  32948. sideOrientation: sideOrientation,
  32949. instance: instance
  32950. };
  32951. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  32952. };
  32953. /**
  32954. * Creates a polyhedron mesh.
  32955. * Please consider using the same method from the MeshBuilder class instead.
  32956. * 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
  32957. * to choose the wanted type.
  32958. * The parameter `size` (positive float, default 1) sets the polygon size.
  32959. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  32960. * 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`.
  32961. * 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
  32962. * 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)`).
  32963. * 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
  32964. * 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.
  32965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32966. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32968. */
  32969. Mesh.CreatePolyhedron = function (name, options, scene) {
  32970. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  32971. };
  32972. /**
  32973. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  32974. * Please consider using the same method from the MeshBuilder class instead.
  32975. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  32976. * 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`).
  32977. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  32978. * 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.
  32979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32980. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32982. */
  32983. Mesh.CreateIcoSphere = function (name, options, scene) {
  32984. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  32985. };
  32986. /**
  32987. * Creates a decal mesh.
  32988. * Please consider using the same method from the MeshBuilder class instead.
  32989. * 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.
  32990. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  32991. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  32992. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  32993. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  32994. */
  32995. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  32996. var options = {
  32997. position: position,
  32998. normal: normal,
  32999. size: size,
  33000. angle: angle
  33001. };
  33002. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33003. };
  33004. // Skeletons
  33005. /**
  33006. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33007. */
  33008. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33009. if (!this._sourcePositions) {
  33010. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33011. if (!source) {
  33012. return this._sourcePositions;
  33013. }
  33014. this._sourcePositions = new Float32Array(source);
  33015. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33016. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33017. }
  33018. }
  33019. return this._sourcePositions;
  33020. };
  33021. /**
  33022. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33023. */
  33024. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33025. if (!this._sourceNormals) {
  33026. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33027. if (!source) {
  33028. return this._sourceNormals;
  33029. }
  33030. this._sourceNormals = new Float32Array(source);
  33031. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33032. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33033. }
  33034. }
  33035. return this._sourceNormals;
  33036. };
  33037. /**
  33038. * Updates the vertex buffer by applying transformation from the bones.
  33039. * Returns the Mesh.
  33040. *
  33041. * @param {skeleton} skeleton to apply
  33042. */
  33043. Mesh.prototype.applySkeleton = function (skeleton) {
  33044. if (!this.geometry) {
  33045. return this;
  33046. }
  33047. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33048. return this;
  33049. }
  33050. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33051. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33052. return this;
  33053. }
  33054. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33055. return this;
  33056. }
  33057. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33058. return this;
  33059. }
  33060. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33061. return this;
  33062. }
  33063. if (!this._sourcePositions) {
  33064. var submeshes = this.subMeshes.slice();
  33065. this.setPositionsForCPUSkinning();
  33066. this.subMeshes = submeshes;
  33067. }
  33068. if (!this._sourceNormals) {
  33069. this.setNormalsForCPUSkinning();
  33070. }
  33071. // positionsData checks for not being Float32Array will only pass at most once
  33072. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33073. if (!positionsData) {
  33074. return this;
  33075. }
  33076. if (!(positionsData instanceof Float32Array)) {
  33077. positionsData = new Float32Array(positionsData);
  33078. }
  33079. // normalsData checks for not being Float32Array will only pass at most once
  33080. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33081. if (!normalsData) {
  33082. return this;
  33083. }
  33084. if (!(normalsData instanceof Float32Array)) {
  33085. normalsData = new Float32Array(normalsData);
  33086. }
  33087. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33088. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33089. if (!matricesWeightsData || !matricesIndicesData) {
  33090. return this;
  33091. }
  33092. var needExtras = this.numBoneInfluencers > 4;
  33093. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33094. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33095. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33096. var tempVector3 = BABYLON.Vector3.Zero();
  33097. var finalMatrix = new BABYLON.Matrix();
  33098. var tempMatrix = new BABYLON.Matrix();
  33099. var matWeightIdx = 0;
  33100. var inf;
  33101. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33102. var weight;
  33103. for (inf = 0; inf < 4; inf++) {
  33104. weight = matricesWeightsData[matWeightIdx + inf];
  33105. if (weight > 0) {
  33106. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33107. finalMatrix.addToSelf(tempMatrix);
  33108. }
  33109. else
  33110. break;
  33111. }
  33112. if (needExtras) {
  33113. for (inf = 0; inf < 4; inf++) {
  33114. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33115. if (weight > 0) {
  33116. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33117. finalMatrix.addToSelf(tempMatrix);
  33118. }
  33119. else
  33120. break;
  33121. }
  33122. }
  33123. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33124. tempVector3.toArray(positionsData, index);
  33125. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33126. tempVector3.toArray(normalsData, index);
  33127. finalMatrix.reset();
  33128. }
  33129. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33130. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33131. return this;
  33132. };
  33133. // Tools
  33134. /**
  33135. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33136. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33137. */
  33138. Mesh.MinMax = function (meshes) {
  33139. var minVector = null;
  33140. var maxVector = null;
  33141. meshes.forEach(function (mesh, index, array) {
  33142. var boundingInfo = mesh.getBoundingInfo();
  33143. var boundingBox = boundingInfo.boundingBox;
  33144. if (!minVector || !maxVector) {
  33145. minVector = boundingBox.minimumWorld;
  33146. maxVector = boundingBox.maximumWorld;
  33147. }
  33148. else {
  33149. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33150. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33151. }
  33152. });
  33153. if (!minVector || !maxVector) {
  33154. return {
  33155. min: BABYLON.Vector3.Zero(),
  33156. max: BABYLON.Vector3.Zero()
  33157. };
  33158. }
  33159. return {
  33160. min: minVector,
  33161. max: maxVector
  33162. };
  33163. };
  33164. /**
  33165. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33166. */
  33167. Mesh.Center = function (meshesOrMinMaxVector) {
  33168. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33169. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33170. };
  33171. /**
  33172. * Merge the array of meshes into a single mesh for performance reasons.
  33173. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33174. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33175. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33176. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33177. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33178. */
  33179. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33180. if (disposeSource === void 0) { disposeSource = true; }
  33181. var index;
  33182. if (!allow32BitsIndices) {
  33183. var totalVertices = 0;
  33184. // Counting vertices
  33185. for (index = 0; index < meshes.length; index++) {
  33186. if (meshes[index]) {
  33187. totalVertices += meshes[index].getTotalVertices();
  33188. if (totalVertices > 65536) {
  33189. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33190. return null;
  33191. }
  33192. }
  33193. }
  33194. }
  33195. // Merge
  33196. var vertexData = null;
  33197. var otherVertexData;
  33198. var indiceArray = new Array();
  33199. var source = null;
  33200. for (index = 0; index < meshes.length; index++) {
  33201. if (meshes[index]) {
  33202. meshes[index].computeWorldMatrix(true);
  33203. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33204. otherVertexData.transform(meshes[index].getWorldMatrix());
  33205. if (vertexData) {
  33206. vertexData.merge(otherVertexData);
  33207. }
  33208. else {
  33209. vertexData = otherVertexData;
  33210. source = meshes[index];
  33211. }
  33212. if (subdivideWithSubMeshes) {
  33213. indiceArray.push(meshes[index].getTotalIndices());
  33214. }
  33215. }
  33216. }
  33217. source = source;
  33218. if (!meshSubclass) {
  33219. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33220. }
  33221. vertexData.applyToMesh(meshSubclass);
  33222. // Setting properties
  33223. meshSubclass.material = source.material;
  33224. meshSubclass.checkCollisions = source.checkCollisions;
  33225. // Cleaning
  33226. if (disposeSource) {
  33227. for (index = 0; index < meshes.length; index++) {
  33228. if (meshes[index]) {
  33229. meshes[index].dispose();
  33230. }
  33231. }
  33232. }
  33233. // Subdivide
  33234. if (subdivideWithSubMeshes) {
  33235. //-- Suppresions du submesh global
  33236. meshSubclass.releaseSubMeshes();
  33237. index = 0;
  33238. var offset = 0;
  33239. //-- aplique la subdivision en fonction du tableau d'indices
  33240. while (index < indiceArray.length) {
  33241. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33242. offset += indiceArray[index];
  33243. index++;
  33244. }
  33245. }
  33246. return meshSubclass;
  33247. };
  33248. // Consts
  33249. Mesh._FRONTSIDE = 0;
  33250. Mesh._BACKSIDE = 1;
  33251. Mesh._DOUBLESIDE = 2;
  33252. Mesh._DEFAULTSIDE = 0;
  33253. Mesh._NO_CAP = 0;
  33254. Mesh._CAP_START = 1;
  33255. Mesh._CAP_END = 2;
  33256. Mesh._CAP_ALL = 3;
  33257. return Mesh;
  33258. }(BABYLON.AbstractMesh));
  33259. BABYLON.Mesh = Mesh;
  33260. })(BABYLON || (BABYLON = {}));
  33261. //# sourceMappingURL=babylon.mesh.js.map
  33262. "use strict";
  33263. var BABYLON;
  33264. (function (BABYLON) {
  33265. var BaseSubMesh = /** @class */ (function () {
  33266. function BaseSubMesh() {
  33267. }
  33268. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33269. get: function () {
  33270. return this._materialEffect;
  33271. },
  33272. enumerable: true,
  33273. configurable: true
  33274. });
  33275. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33276. if (defines === void 0) { defines = null; }
  33277. if (this._materialEffect === effect) {
  33278. if (!effect) {
  33279. this._materialDefines = null;
  33280. }
  33281. return;
  33282. }
  33283. this._materialDefines = defines;
  33284. this._materialEffect = effect;
  33285. };
  33286. return BaseSubMesh;
  33287. }());
  33288. BABYLON.BaseSubMesh = BaseSubMesh;
  33289. var SubMesh = /** @class */ (function (_super) {
  33290. __extends(SubMesh, _super);
  33291. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33292. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33293. var _this = _super.call(this) || this;
  33294. _this.materialIndex = materialIndex;
  33295. _this.verticesStart = verticesStart;
  33296. _this.verticesCount = verticesCount;
  33297. _this.indexStart = indexStart;
  33298. _this.indexCount = indexCount;
  33299. _this._renderId = 0;
  33300. _this._mesh = mesh;
  33301. _this._renderingMesh = renderingMesh || mesh;
  33302. mesh.subMeshes.push(_this);
  33303. _this._trianglePlanes = [];
  33304. _this._id = mesh.subMeshes.length - 1;
  33305. if (createBoundingBox) {
  33306. _this.refreshBoundingInfo();
  33307. mesh.computeWorldMatrix(true);
  33308. }
  33309. return _this;
  33310. }
  33311. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33312. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33313. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33314. };
  33315. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33316. get: function () {
  33317. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33318. },
  33319. enumerable: true,
  33320. configurable: true
  33321. });
  33322. /**
  33323. * Returns the submesh BoudingInfo object.
  33324. */
  33325. SubMesh.prototype.getBoundingInfo = function () {
  33326. if (this.IsGlobal) {
  33327. return this._mesh.getBoundingInfo();
  33328. }
  33329. return this._boundingInfo;
  33330. };
  33331. /**
  33332. * Sets the submesh BoundingInfo.
  33333. * Return the SubMesh.
  33334. */
  33335. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33336. this._boundingInfo = boundingInfo;
  33337. return this;
  33338. };
  33339. /**
  33340. * Returns the mesh of the current submesh.
  33341. */
  33342. SubMesh.prototype.getMesh = function () {
  33343. return this._mesh;
  33344. };
  33345. /**
  33346. * Returns the rendering mesh of the submesh.
  33347. */
  33348. SubMesh.prototype.getRenderingMesh = function () {
  33349. return this._renderingMesh;
  33350. };
  33351. /**
  33352. * Returns the submesh material.
  33353. */
  33354. SubMesh.prototype.getMaterial = function () {
  33355. var rootMaterial = this._renderingMesh.material;
  33356. if (rootMaterial === null || rootMaterial === undefined) {
  33357. return this._mesh.getScene().defaultMaterial;
  33358. }
  33359. else if (rootMaterial.getSubMaterial) {
  33360. var multiMaterial = rootMaterial;
  33361. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33362. if (this._currentMaterial !== effectiveMaterial) {
  33363. this._currentMaterial = effectiveMaterial;
  33364. this._materialDefines = null;
  33365. }
  33366. return effectiveMaterial;
  33367. }
  33368. return rootMaterial;
  33369. };
  33370. // Methods
  33371. /**
  33372. * Sets a new updated BoundingInfo object to the submesh.
  33373. * Returns the SubMesh.
  33374. */
  33375. SubMesh.prototype.refreshBoundingInfo = function () {
  33376. this._lastColliderWorldVertices = null;
  33377. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33378. return this;
  33379. }
  33380. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33381. if (!data) {
  33382. this._boundingInfo = this._mesh.getBoundingInfo();
  33383. return this;
  33384. }
  33385. var indices = this._renderingMesh.getIndices();
  33386. var extend;
  33387. //is this the only submesh?
  33388. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33389. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33390. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33391. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33392. }
  33393. else {
  33394. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33395. }
  33396. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33397. return this;
  33398. };
  33399. SubMesh.prototype._checkCollision = function (collider) {
  33400. var boundingInfo = this.getBoundingInfo();
  33401. return boundingInfo._checkCollision(collider);
  33402. };
  33403. /**
  33404. * Updates the submesh BoundingInfo.
  33405. * Returns the Submesh.
  33406. */
  33407. SubMesh.prototype.updateBoundingInfo = function (world) {
  33408. var boundingInfo = this.getBoundingInfo();
  33409. if (!boundingInfo) {
  33410. this.refreshBoundingInfo();
  33411. boundingInfo = this.getBoundingInfo();
  33412. }
  33413. boundingInfo.update(world);
  33414. return this;
  33415. };
  33416. /**
  33417. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33418. * Boolean returned.
  33419. */
  33420. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33421. var boundingInfo = this.getBoundingInfo();
  33422. if (!boundingInfo) {
  33423. return false;
  33424. }
  33425. return boundingInfo.isInFrustum(frustumPlanes);
  33426. };
  33427. /**
  33428. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33429. * Boolean returned.
  33430. */
  33431. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33432. var boundingInfo = this.getBoundingInfo();
  33433. if (!boundingInfo) {
  33434. return false;
  33435. }
  33436. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33437. };
  33438. /**
  33439. * Renders the submesh.
  33440. * Returns it.
  33441. */
  33442. SubMesh.prototype.render = function (enableAlphaMode) {
  33443. this._renderingMesh.render(this, enableAlphaMode);
  33444. return this;
  33445. };
  33446. /**
  33447. * Returns a new Index Buffer.
  33448. * Type returned : WebGLBuffer.
  33449. */
  33450. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33451. if (!this._linesIndexBuffer) {
  33452. var linesIndices = [];
  33453. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33454. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33455. }
  33456. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33457. this.linesIndexCount = linesIndices.length;
  33458. }
  33459. return this._linesIndexBuffer;
  33460. };
  33461. /**
  33462. * True is the passed Ray intersects the submesh bounding box.
  33463. * Boolean returned.
  33464. */
  33465. SubMesh.prototype.canIntersects = function (ray) {
  33466. var boundingInfo = this.getBoundingInfo();
  33467. if (!boundingInfo) {
  33468. return false;
  33469. }
  33470. return ray.intersectsBox(boundingInfo.boundingBox);
  33471. };
  33472. /**
  33473. * Returns an object IntersectionInfo.
  33474. */
  33475. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33476. var intersectInfo = null;
  33477. var material = this.getMaterial();
  33478. if (!material) {
  33479. return null;
  33480. }
  33481. switch (material.fillMode) {
  33482. case BABYLON.Material.PointListDrawMode:
  33483. case BABYLON.Material.LineListDrawMode:
  33484. case BABYLON.Material.LineLoopDrawMode:
  33485. case BABYLON.Material.LineStripDrawMode:
  33486. case BABYLON.Material.TriangleFanDrawMode:
  33487. case BABYLON.Material.TriangleStripDrawMode:
  33488. return null;
  33489. }
  33490. // LineMesh first as it's also a Mesh...
  33491. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33492. var lineMesh = this._mesh;
  33493. // Line test
  33494. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33495. var p0 = positions[indices[index]];
  33496. var p1 = positions[indices[index + 1]];
  33497. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33498. if (length < 0) {
  33499. continue;
  33500. }
  33501. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33502. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33503. if (fastCheck) {
  33504. break;
  33505. }
  33506. }
  33507. }
  33508. }
  33509. else {
  33510. // Triangles test
  33511. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33512. var p0 = positions[indices[index]];
  33513. var p1 = positions[indices[index + 1]];
  33514. var p2 = positions[indices[index + 2]];
  33515. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33516. if (currentIntersectInfo) {
  33517. if (currentIntersectInfo.distance < 0) {
  33518. continue;
  33519. }
  33520. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33521. intersectInfo = currentIntersectInfo;
  33522. intersectInfo.faceId = index / 3;
  33523. if (fastCheck) {
  33524. break;
  33525. }
  33526. }
  33527. }
  33528. }
  33529. }
  33530. return intersectInfo;
  33531. };
  33532. SubMesh.prototype._rebuild = function () {
  33533. if (this._linesIndexBuffer) {
  33534. this._linesIndexBuffer = null;
  33535. }
  33536. };
  33537. // Clone
  33538. /**
  33539. * Creates a new Submesh from the passed Mesh.
  33540. */
  33541. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33542. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33543. if (!this.IsGlobal) {
  33544. var boundingInfo = this.getBoundingInfo();
  33545. if (!boundingInfo) {
  33546. return result;
  33547. }
  33548. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33549. }
  33550. return result;
  33551. };
  33552. // Dispose
  33553. /**
  33554. * Disposes the Submesh.
  33555. * Returns nothing.
  33556. */
  33557. SubMesh.prototype.dispose = function () {
  33558. if (this._linesIndexBuffer) {
  33559. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33560. this._linesIndexBuffer = null;
  33561. }
  33562. // Remove from mesh
  33563. var index = this._mesh.subMeshes.indexOf(this);
  33564. this._mesh.subMeshes.splice(index, 1);
  33565. };
  33566. // Statics
  33567. /**
  33568. * Creates a new Submesh from the passed parameters :
  33569. * - materialIndex (integer) : the index of the main mesh material.
  33570. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33571. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33572. * - mesh (Mesh) : the main mesh to create the submesh from.
  33573. * - renderingMesh (optional Mesh) : rendering mesh.
  33574. */
  33575. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33576. var minVertexIndex = Number.MAX_VALUE;
  33577. var maxVertexIndex = -Number.MAX_VALUE;
  33578. renderingMesh = (renderingMesh || mesh);
  33579. var indices = renderingMesh.getIndices();
  33580. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33581. var vertexIndex = indices[index];
  33582. if (vertexIndex < minVertexIndex)
  33583. minVertexIndex = vertexIndex;
  33584. if (vertexIndex > maxVertexIndex)
  33585. maxVertexIndex = vertexIndex;
  33586. }
  33587. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33588. };
  33589. return SubMesh;
  33590. }(BaseSubMesh));
  33591. BABYLON.SubMesh = SubMesh;
  33592. })(BABYLON || (BABYLON = {}));
  33593. //# sourceMappingURL=babylon.subMesh.js.map
  33594. "use strict";
  33595. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33596. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33597. s = arguments[i];
  33598. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33599. t[p] = s[p];
  33600. }
  33601. return t;
  33602. };
  33603. var BABYLON;
  33604. (function (BABYLON) {
  33605. /**
  33606. * Manages the defines for the Material
  33607. */
  33608. var MaterialDefines = /** @class */ (function () {
  33609. function MaterialDefines() {
  33610. this._isDirty = true;
  33611. /** @ignore */
  33612. this._areLightsDirty = true;
  33613. /** @ignore */
  33614. this._areAttributesDirty = true;
  33615. /** @ignore */
  33616. this._areTexturesDirty = true;
  33617. /** @ignore */
  33618. this._areFresnelDirty = true;
  33619. /** @ignore */
  33620. this._areMiscDirty = true;
  33621. /** @ignore */
  33622. this._areImageProcessingDirty = true;
  33623. /** @ignore */
  33624. this._normals = false;
  33625. /** @ignore */
  33626. this._uvs = false;
  33627. /** @ignore */
  33628. this._needNormals = false;
  33629. /** @ignore */
  33630. this._needUVs = false;
  33631. }
  33632. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33633. /**
  33634. * Specifies if the material needs to be re-calculated
  33635. */
  33636. get: function () {
  33637. return this._isDirty;
  33638. },
  33639. enumerable: true,
  33640. configurable: true
  33641. });
  33642. /**
  33643. * Marks the material to indicate that it has been re-calculated
  33644. */
  33645. MaterialDefines.prototype.markAsProcessed = function () {
  33646. this._isDirty = false;
  33647. this._areAttributesDirty = false;
  33648. this._areTexturesDirty = false;
  33649. this._areFresnelDirty = false;
  33650. this._areLightsDirty = false;
  33651. this._areMiscDirty = false;
  33652. this._areImageProcessingDirty = false;
  33653. };
  33654. /**
  33655. * Marks the material to indicate that it needs to be re-calculated
  33656. */
  33657. MaterialDefines.prototype.markAsUnprocessed = function () {
  33658. this._isDirty = true;
  33659. };
  33660. /**
  33661. * Marks the material to indicate all of its defines need to be re-calculated
  33662. */
  33663. MaterialDefines.prototype.markAllAsDirty = function () {
  33664. this._areTexturesDirty = true;
  33665. this._areAttributesDirty = true;
  33666. this._areLightsDirty = true;
  33667. this._areFresnelDirty = true;
  33668. this._areMiscDirty = true;
  33669. this._areImageProcessingDirty = true;
  33670. this._isDirty = true;
  33671. };
  33672. /**
  33673. * Marks the material to indicate that image processing needs to be re-calculated
  33674. */
  33675. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33676. this._areImageProcessingDirty = true;
  33677. this._isDirty = true;
  33678. };
  33679. /**
  33680. * Marks the material to indicate the lights need to be re-calculated
  33681. */
  33682. MaterialDefines.prototype.markAsLightDirty = function () {
  33683. this._areLightsDirty = true;
  33684. this._isDirty = true;
  33685. };
  33686. /**
  33687. * Marks the attribute state as changed
  33688. */
  33689. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33690. this._areAttributesDirty = true;
  33691. this._isDirty = true;
  33692. };
  33693. /**
  33694. * Marks the texture state as changed
  33695. */
  33696. MaterialDefines.prototype.markAsTexturesDirty = function () {
  33697. this._areTexturesDirty = true;
  33698. this._isDirty = true;
  33699. };
  33700. /**
  33701. * Marks the fresnel state as changed
  33702. */
  33703. MaterialDefines.prototype.markAsFresnelDirty = function () {
  33704. this._areFresnelDirty = true;
  33705. this._isDirty = true;
  33706. };
  33707. /**
  33708. * Marks the misc state as changed
  33709. */
  33710. MaterialDefines.prototype.markAsMiscDirty = function () {
  33711. this._areMiscDirty = true;
  33712. this._isDirty = true;
  33713. };
  33714. /**
  33715. * Rebuilds the material defines
  33716. */
  33717. MaterialDefines.prototype.rebuild = function () {
  33718. if (this._keys) {
  33719. delete this._keys;
  33720. }
  33721. this._keys = [];
  33722. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  33723. var key = _a[_i];
  33724. if (key[0] === "_") {
  33725. continue;
  33726. }
  33727. this._keys.push(key);
  33728. }
  33729. };
  33730. /**
  33731. * Specifies if two material defines are equal
  33732. * @param other - A material define instance to compare to
  33733. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  33734. */
  33735. MaterialDefines.prototype.isEqual = function (other) {
  33736. if (this._keys.length !== other._keys.length) {
  33737. return false;
  33738. }
  33739. for (var index = 0; index < this._keys.length; index++) {
  33740. var prop = this._keys[index];
  33741. if (this[prop] !== other[prop]) {
  33742. return false;
  33743. }
  33744. }
  33745. return true;
  33746. };
  33747. /**
  33748. * Clones this instance's defines to another instance
  33749. * @param other - material defines to clone values to
  33750. */
  33751. MaterialDefines.prototype.cloneTo = function (other) {
  33752. if (this._keys.length !== other._keys.length) {
  33753. other._keys = this._keys.slice(0);
  33754. }
  33755. for (var index = 0; index < this._keys.length; index++) {
  33756. var prop = this._keys[index];
  33757. other[prop] = this[prop];
  33758. }
  33759. };
  33760. /**
  33761. * Resets the material define values
  33762. */
  33763. MaterialDefines.prototype.reset = function () {
  33764. for (var index = 0; index < this._keys.length; index++) {
  33765. var prop = this._keys[index];
  33766. var type = typeof this[prop];
  33767. switch (type) {
  33768. case "number":
  33769. this[prop] = 0;
  33770. break;
  33771. case "string":
  33772. this[prop] = "";
  33773. break;
  33774. default:
  33775. this[prop] = false;
  33776. break;
  33777. }
  33778. }
  33779. };
  33780. /**
  33781. * Converts the material define values to a string
  33782. * @returns - String of material define information
  33783. */
  33784. MaterialDefines.prototype.toString = function () {
  33785. var result = "";
  33786. for (var index = 0; index < this._keys.length; index++) {
  33787. var prop = this._keys[index];
  33788. var value = this[prop];
  33789. var type = typeof value;
  33790. switch (type) {
  33791. case "number":
  33792. case "string":
  33793. result += "#define " + prop + " " + value + "\n";
  33794. break;
  33795. default:
  33796. if (value) {
  33797. result += "#define " + prop + "\n";
  33798. }
  33799. break;
  33800. }
  33801. }
  33802. return result;
  33803. };
  33804. return MaterialDefines;
  33805. }());
  33806. BABYLON.MaterialDefines = MaterialDefines;
  33807. /**
  33808. * Base class for the main features of a material in Babylon.js
  33809. */
  33810. var Material = /** @class */ (function () {
  33811. /**
  33812. * Creates a material instance
  33813. * @param name defines the name of the material
  33814. * @param scene defines the scene to reference
  33815. * @param doNotAdd specifies if the material should be added to the scene
  33816. */
  33817. function Material(name, scene, doNotAdd) {
  33818. /**
  33819. * Specifies if the ready state should be checked on each call
  33820. */
  33821. this.checkReadyOnEveryCall = false;
  33822. /**
  33823. * Specifies if the ready state should be checked once
  33824. */
  33825. this.checkReadyOnlyOnce = false;
  33826. /**
  33827. * The state of the material
  33828. */
  33829. this.state = "";
  33830. /**
  33831. * The alpha value of the material
  33832. */
  33833. this._alpha = 1.0;
  33834. /**
  33835. * Specifies if back face culling is enabled
  33836. */
  33837. this._backFaceCulling = true;
  33838. /**
  33839. * Specifies if the material should be serialized
  33840. */
  33841. this.doNotSerialize = false;
  33842. /**
  33843. * Specifies if the effect should be stored on sub meshes
  33844. */
  33845. this.storeEffectOnSubMeshes = false;
  33846. /**
  33847. * An event triggered when the material is disposed
  33848. */
  33849. this.onDisposeObservable = new BABYLON.Observable();
  33850. /**
  33851. * An event triggered when the material is bound
  33852. */
  33853. this.onBindObservable = new BABYLON.Observable();
  33854. /**
  33855. * An event triggered when the material is unbound
  33856. */
  33857. this.onUnBindObservable = new BABYLON.Observable();
  33858. /**
  33859. * Stores the value of the alpha mode
  33860. */
  33861. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  33862. /**
  33863. * Stores the state of the need depth pre-pass value
  33864. */
  33865. this._needDepthPrePass = false;
  33866. /**
  33867. * Specifies if depth writing should be disabled
  33868. */
  33869. this.disableDepthWrite = false;
  33870. /**
  33871. * Specifies if depth writing should be forced
  33872. */
  33873. this.forceDepthWrite = false;
  33874. /**
  33875. * Specifies if there should be a separate pass for culling
  33876. */
  33877. this.separateCullingPass = false;
  33878. /**
  33879. * Stores the state specifing if fog should be enabled
  33880. */
  33881. this._fogEnabled = true;
  33882. /**
  33883. * Stores the size of points
  33884. */
  33885. this.pointSize = 1.0;
  33886. /**
  33887. * Stores the z offset value
  33888. */
  33889. this.zOffset = 0;
  33890. /**
  33891. * Specifies if the material was previously ready
  33892. */
  33893. this._wasPreviouslyReady = false;
  33894. /**
  33895. * Stores the fill mode state
  33896. */
  33897. this._fillMode = Material.TriangleFillMode;
  33898. this.name = name;
  33899. this.id = name || BABYLON.Tools.RandomId();
  33900. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  33901. if (this._scene.useRightHandedSystem) {
  33902. this.sideOrientation = Material.ClockWiseSideOrientation;
  33903. }
  33904. else {
  33905. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  33906. }
  33907. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  33908. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  33909. if (!doNotAdd) {
  33910. this._scene.materials.push(this);
  33911. }
  33912. }
  33913. Object.defineProperty(Material, "TriangleFillMode", {
  33914. /**
  33915. * Returns the triangle fill mode
  33916. */
  33917. get: function () {
  33918. return Material._TriangleFillMode;
  33919. },
  33920. enumerable: true,
  33921. configurable: true
  33922. });
  33923. Object.defineProperty(Material, "WireFrameFillMode", {
  33924. /**
  33925. * Returns the wireframe mode
  33926. */
  33927. get: function () {
  33928. return Material._WireFrameFillMode;
  33929. },
  33930. enumerable: true,
  33931. configurable: true
  33932. });
  33933. Object.defineProperty(Material, "PointFillMode", {
  33934. /**
  33935. * Returns the point fill mode
  33936. */
  33937. get: function () {
  33938. return Material._PointFillMode;
  33939. },
  33940. enumerable: true,
  33941. configurable: true
  33942. });
  33943. Object.defineProperty(Material, "PointListDrawMode", {
  33944. /**
  33945. * Returns the point list draw mode
  33946. */
  33947. get: function () {
  33948. return Material._PointListDrawMode;
  33949. },
  33950. enumerable: true,
  33951. configurable: true
  33952. });
  33953. Object.defineProperty(Material, "LineListDrawMode", {
  33954. /**
  33955. * Returns the line list draw mode
  33956. */
  33957. get: function () {
  33958. return Material._LineListDrawMode;
  33959. },
  33960. enumerable: true,
  33961. configurable: true
  33962. });
  33963. Object.defineProperty(Material, "LineLoopDrawMode", {
  33964. /**
  33965. * Returns the line loop draw mode
  33966. */
  33967. get: function () {
  33968. return Material._LineLoopDrawMode;
  33969. },
  33970. enumerable: true,
  33971. configurable: true
  33972. });
  33973. Object.defineProperty(Material, "LineStripDrawMode", {
  33974. /**
  33975. * Returns the line strip draw mode
  33976. */
  33977. get: function () {
  33978. return Material._LineStripDrawMode;
  33979. },
  33980. enumerable: true,
  33981. configurable: true
  33982. });
  33983. Object.defineProperty(Material, "TriangleStripDrawMode", {
  33984. /**
  33985. * Returns the triangle strip draw mode
  33986. */
  33987. get: function () {
  33988. return Material._TriangleStripDrawMode;
  33989. },
  33990. enumerable: true,
  33991. configurable: true
  33992. });
  33993. Object.defineProperty(Material, "TriangleFanDrawMode", {
  33994. /**
  33995. * Returns the triangle fan draw mode
  33996. */
  33997. get: function () {
  33998. return Material._TriangleFanDrawMode;
  33999. },
  34000. enumerable: true,
  34001. configurable: true
  34002. });
  34003. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34004. /**
  34005. * Returns the clock-wise side orientation
  34006. */
  34007. get: function () {
  34008. return Material._ClockWiseSideOrientation;
  34009. },
  34010. enumerable: true,
  34011. configurable: true
  34012. });
  34013. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34014. /**
  34015. * Returns the counter clock-wise side orientation
  34016. */
  34017. get: function () {
  34018. return Material._CounterClockWiseSideOrientation;
  34019. },
  34020. enumerable: true,
  34021. configurable: true
  34022. });
  34023. Object.defineProperty(Material, "TextureDirtyFlag", {
  34024. /**
  34025. * Returns the dirty texture flag value
  34026. */
  34027. get: function () {
  34028. return Material._TextureDirtyFlag;
  34029. },
  34030. enumerable: true,
  34031. configurable: true
  34032. });
  34033. Object.defineProperty(Material, "LightDirtyFlag", {
  34034. /**
  34035. * Returns the dirty light flag value
  34036. */
  34037. get: function () {
  34038. return Material._LightDirtyFlag;
  34039. },
  34040. enumerable: true,
  34041. configurable: true
  34042. });
  34043. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34044. /**
  34045. * Returns the dirty fresnel flag value
  34046. */
  34047. get: function () {
  34048. return Material._FresnelDirtyFlag;
  34049. },
  34050. enumerable: true,
  34051. configurable: true
  34052. });
  34053. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34054. /**
  34055. * Returns the dirty attributes flag value
  34056. */
  34057. get: function () {
  34058. return Material._AttributesDirtyFlag;
  34059. },
  34060. enumerable: true,
  34061. configurable: true
  34062. });
  34063. Object.defineProperty(Material, "MiscDirtyFlag", {
  34064. /**
  34065. * Returns the dirty misc flag value
  34066. */
  34067. get: function () {
  34068. return Material._MiscDirtyFlag;
  34069. },
  34070. enumerable: true,
  34071. configurable: true
  34072. });
  34073. Object.defineProperty(Material.prototype, "alpha", {
  34074. /**
  34075. * Gets the alpha value of the material
  34076. */
  34077. get: function () {
  34078. return this._alpha;
  34079. },
  34080. /**
  34081. * Sets the alpha value of the material
  34082. */
  34083. set: function (value) {
  34084. if (this._alpha === value) {
  34085. return;
  34086. }
  34087. this._alpha = value;
  34088. this.markAsDirty(Material.MiscDirtyFlag);
  34089. },
  34090. enumerable: true,
  34091. configurable: true
  34092. });
  34093. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34094. /**
  34095. * Gets the back-face culling state
  34096. */
  34097. get: function () {
  34098. return this._backFaceCulling;
  34099. },
  34100. /**
  34101. * Sets the back-face culling state
  34102. */
  34103. set: function (value) {
  34104. if (this._backFaceCulling === value) {
  34105. return;
  34106. }
  34107. this._backFaceCulling = value;
  34108. this.markAsDirty(Material.TextureDirtyFlag);
  34109. },
  34110. enumerable: true,
  34111. configurable: true
  34112. });
  34113. Object.defineProperty(Material.prototype, "onDispose", {
  34114. /**
  34115. * Called during a dispose event
  34116. */
  34117. set: function (callback) {
  34118. if (this._onDisposeObserver) {
  34119. this.onDisposeObservable.remove(this._onDisposeObserver);
  34120. }
  34121. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34122. },
  34123. enumerable: true,
  34124. configurable: true
  34125. });
  34126. Object.defineProperty(Material.prototype, "onBind", {
  34127. /**
  34128. * Called during a bind event
  34129. */
  34130. set: function (callback) {
  34131. if (this._onBindObserver) {
  34132. this.onBindObservable.remove(this._onBindObserver);
  34133. }
  34134. this._onBindObserver = this.onBindObservable.add(callback);
  34135. },
  34136. enumerable: true,
  34137. configurable: true
  34138. });
  34139. Object.defineProperty(Material.prototype, "alphaMode", {
  34140. /**
  34141. * Gets the value of the alpha mode
  34142. */
  34143. get: function () {
  34144. return this._alphaMode;
  34145. },
  34146. /**
  34147. * Sets the value of the alpha mode.
  34148. *
  34149. * | Value | Type | Description |
  34150. * | --- | --- | --- |
  34151. * | 0 | ALPHA_DISABLE | |
  34152. * | 1 | ALPHA_ADD | |
  34153. * | 2 | ALPHA_COMBINE | |
  34154. * | 3 | ALPHA_SUBTRACT | |
  34155. * | 4 | ALPHA_MULTIPLY | |
  34156. * | 5 | ALPHA_MAXIMIZED | |
  34157. * | 6 | ALPHA_ONEONE | |
  34158. * | 7 | ALPHA_PREMULTIPLIED | |
  34159. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34160. * | 9 | ALPHA_INTERPOLATE | |
  34161. * | 10 | ALPHA_SCREENMODE | |
  34162. *
  34163. */
  34164. set: function (value) {
  34165. if (this._alphaMode === value) {
  34166. return;
  34167. }
  34168. this._alphaMode = value;
  34169. this.markAsDirty(Material.TextureDirtyFlag);
  34170. },
  34171. enumerable: true,
  34172. configurable: true
  34173. });
  34174. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34175. /**
  34176. * Gets the depth pre-pass value
  34177. */
  34178. get: function () {
  34179. return this._needDepthPrePass;
  34180. },
  34181. /**
  34182. * Sets the need depth pre-pass value
  34183. */
  34184. set: function (value) {
  34185. if (this._needDepthPrePass === value) {
  34186. return;
  34187. }
  34188. this._needDepthPrePass = value;
  34189. if (this._needDepthPrePass) {
  34190. this.checkReadyOnEveryCall = true;
  34191. }
  34192. },
  34193. enumerable: true,
  34194. configurable: true
  34195. });
  34196. Object.defineProperty(Material.prototype, "fogEnabled", {
  34197. /**
  34198. * Gets the value of the fog enabled state
  34199. */
  34200. get: function () {
  34201. return this._fogEnabled;
  34202. },
  34203. /**
  34204. * Sets the state for enabling fog
  34205. */
  34206. set: function (value) {
  34207. if (this._fogEnabled === value) {
  34208. return;
  34209. }
  34210. this._fogEnabled = value;
  34211. this.markAsDirty(Material.MiscDirtyFlag);
  34212. },
  34213. enumerable: true,
  34214. configurable: true
  34215. });
  34216. Object.defineProperty(Material.prototype, "wireframe", {
  34217. /**
  34218. * Gets a value specifying if wireframe mode is enabled
  34219. */
  34220. get: function () {
  34221. switch (this._fillMode) {
  34222. case Material.WireFrameFillMode:
  34223. case Material.LineListDrawMode:
  34224. case Material.LineLoopDrawMode:
  34225. case Material.LineStripDrawMode:
  34226. return true;
  34227. }
  34228. return this._scene.forceWireframe;
  34229. },
  34230. /**
  34231. * Sets the state of wireframe mode
  34232. */
  34233. set: function (value) {
  34234. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34235. },
  34236. enumerable: true,
  34237. configurable: true
  34238. });
  34239. Object.defineProperty(Material.prototype, "pointsCloud", {
  34240. /**
  34241. * Gets the value specifying if point clouds are enabled
  34242. */
  34243. get: function () {
  34244. switch (this._fillMode) {
  34245. case Material.PointFillMode:
  34246. case Material.PointListDrawMode:
  34247. return true;
  34248. }
  34249. return this._scene.forcePointsCloud;
  34250. },
  34251. /**
  34252. * Sets the state of point cloud mode
  34253. */
  34254. set: function (value) {
  34255. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34256. },
  34257. enumerable: true,
  34258. configurable: true
  34259. });
  34260. Object.defineProperty(Material.prototype, "fillMode", {
  34261. /**
  34262. * Gets the material fill mode
  34263. */
  34264. get: function () {
  34265. return this._fillMode;
  34266. },
  34267. /**
  34268. * Sets the material fill mode
  34269. */
  34270. set: function (value) {
  34271. if (this._fillMode === value) {
  34272. return;
  34273. }
  34274. this._fillMode = value;
  34275. this.markAsDirty(Material.MiscDirtyFlag);
  34276. },
  34277. enumerable: true,
  34278. configurable: true
  34279. });
  34280. /**
  34281. * Returns a string representation of the current material
  34282. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34283. * @returns a string with material information
  34284. */
  34285. Material.prototype.toString = function (fullDetails) {
  34286. var ret = "Name: " + this.name;
  34287. if (fullDetails) {
  34288. }
  34289. return ret;
  34290. };
  34291. /**
  34292. * Gets the class name of the material
  34293. * @returns a string with the class name of the material
  34294. */
  34295. Material.prototype.getClassName = function () {
  34296. return "Material";
  34297. };
  34298. Object.defineProperty(Material.prototype, "isFrozen", {
  34299. /**
  34300. * Specifies if updates for the material been locked
  34301. */
  34302. get: function () {
  34303. return this.checkReadyOnlyOnce;
  34304. },
  34305. enumerable: true,
  34306. configurable: true
  34307. });
  34308. /**
  34309. * Locks updates for the material
  34310. */
  34311. Material.prototype.freeze = function () {
  34312. this.checkReadyOnlyOnce = true;
  34313. };
  34314. /**
  34315. * Unlocks updates for the material
  34316. */
  34317. Material.prototype.unfreeze = function () {
  34318. this.checkReadyOnlyOnce = false;
  34319. };
  34320. /**
  34321. * Specifies if the material is ready to be used
  34322. * @param mesh defines the mesh to check
  34323. * @param useInstances specifies if instances should be used
  34324. * @returns a boolean indicating if the material is ready to be used
  34325. */
  34326. Material.prototype.isReady = function (mesh, useInstances) {
  34327. return true;
  34328. };
  34329. /**
  34330. * Specifies that the submesh is ready to be used
  34331. * @param mesh defines the mesh to check
  34332. * @param subMesh defines which submesh to check
  34333. * @param useInstances specifies that instances should be used
  34334. * @returns a boolean indicating that the submesh is ready or not
  34335. */
  34336. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34337. return false;
  34338. };
  34339. /**
  34340. * Returns the material effect
  34341. * @returns the effect associated with the material
  34342. */
  34343. Material.prototype.getEffect = function () {
  34344. return this._effect;
  34345. };
  34346. /**
  34347. * Returns the current scene
  34348. * @returns a Scene
  34349. */
  34350. Material.prototype.getScene = function () {
  34351. return this._scene;
  34352. };
  34353. /**
  34354. * Specifies if the material will require alpha blending
  34355. * @returns a boolean specifying if alpha blending is needed
  34356. */
  34357. Material.prototype.needAlphaBlending = function () {
  34358. return (this.alpha < 1.0);
  34359. };
  34360. /**
  34361. * Specifies if the mesh will require alpha blending
  34362. * @param mesh defines the mesh to check
  34363. * @returns a boolean specifying if alpha blending is needed for the mesh
  34364. */
  34365. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34366. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34367. };
  34368. /**
  34369. * Specifies if this material should be rendered in alpha test mode
  34370. * @returns a boolean specifying if an alpha test is needed.
  34371. */
  34372. Material.prototype.needAlphaTesting = function () {
  34373. return false;
  34374. };
  34375. /**
  34376. * Gets the texture used for the alpha test
  34377. * @returns the texture to use for alpha testing
  34378. */
  34379. Material.prototype.getAlphaTestTexture = function () {
  34380. return null;
  34381. };
  34382. /**
  34383. * Marks the material to indicate that it needs to be re-calculated
  34384. */
  34385. Material.prototype.markDirty = function () {
  34386. this._wasPreviouslyReady = false;
  34387. };
  34388. /** @ignore */
  34389. Material.prototype._preBind = function (effect, overrideOrientation) {
  34390. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34391. var engine = this._scene.getEngine();
  34392. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34393. var reverse = orientation === Material.ClockWiseSideOrientation;
  34394. engine.enableEffect(effect ? effect : this._effect);
  34395. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34396. return reverse;
  34397. };
  34398. /**
  34399. * Binds the material to the mesh
  34400. * @param world defines the world transformation matrix
  34401. * @param mesh defines the mesh to bind the material to
  34402. */
  34403. Material.prototype.bind = function (world, mesh) {
  34404. };
  34405. /**
  34406. * Binds the submesh to the material
  34407. * @param world defines the world transformation matrix
  34408. * @param mesh defines the mesh containing the submesh
  34409. * @param subMesh defines the submesh to bind the material to
  34410. */
  34411. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34412. };
  34413. /**
  34414. * Binds the world matrix to the material
  34415. * @param world defines the world transformation matrix
  34416. */
  34417. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34418. };
  34419. /**
  34420. * Binds the scene's uniform buffer to the effect.
  34421. * @param effect defines the effect to bind to the scene uniform buffer
  34422. * @param sceneUbo defines the uniform buffer storing scene data
  34423. */
  34424. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34425. sceneUbo.bindToEffect(effect, "Scene");
  34426. };
  34427. /**
  34428. * Binds the view matrix to the effect
  34429. * @param effect defines the effect to bind the view matrix to
  34430. */
  34431. Material.prototype.bindView = function (effect) {
  34432. if (!this._useUBO) {
  34433. effect.setMatrix("view", this.getScene().getViewMatrix());
  34434. }
  34435. else {
  34436. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34437. }
  34438. };
  34439. /**
  34440. * Binds the view projection matrix to the effect
  34441. * @param effect defines the effect to bind the view projection matrix to
  34442. */
  34443. Material.prototype.bindViewProjection = function (effect) {
  34444. if (!this._useUBO) {
  34445. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34446. }
  34447. else {
  34448. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34449. }
  34450. };
  34451. /**
  34452. * Specifies if material alpha testing should be turned on for the mesh
  34453. * @param mesh defines the mesh to check
  34454. */
  34455. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34456. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34457. };
  34458. /**
  34459. * Processes to execute after binding the material to a mesh
  34460. * @param mesh defines the rendered mesh
  34461. */
  34462. Material.prototype._afterBind = function (mesh) {
  34463. this._scene._cachedMaterial = this;
  34464. if (mesh) {
  34465. this._scene._cachedVisibility = mesh.visibility;
  34466. }
  34467. else {
  34468. this._scene._cachedVisibility = 1;
  34469. }
  34470. if (mesh) {
  34471. this.onBindObservable.notifyObservers(mesh);
  34472. }
  34473. if (this.disableDepthWrite) {
  34474. var engine = this._scene.getEngine();
  34475. this._cachedDepthWriteState = engine.getDepthWrite();
  34476. engine.setDepthWrite(false);
  34477. }
  34478. };
  34479. /**
  34480. * Unbinds the material from the mesh
  34481. */
  34482. Material.prototype.unbind = function () {
  34483. this.onUnBindObservable.notifyObservers(this);
  34484. if (this.disableDepthWrite) {
  34485. var engine = this._scene.getEngine();
  34486. engine.setDepthWrite(this._cachedDepthWriteState);
  34487. }
  34488. };
  34489. /**
  34490. * Gets the active textures from the material
  34491. * @returns an array of textures
  34492. */
  34493. Material.prototype.getActiveTextures = function () {
  34494. return [];
  34495. };
  34496. /**
  34497. * Specifies if the material uses a texture
  34498. * @param texture defines the texture to check against the material
  34499. * @returns a boolean specifying if the material uses the texture
  34500. */
  34501. Material.prototype.hasTexture = function (texture) {
  34502. return false;
  34503. };
  34504. /**
  34505. * Makes a duplicate of the material, and gives it a new name
  34506. * @param name defines the new name for the duplicated material
  34507. * @returns the cloned material
  34508. */
  34509. Material.prototype.clone = function (name) {
  34510. return null;
  34511. };
  34512. /**
  34513. * Gets the meshes bound to the material
  34514. * @returns an array of meshes bound to the material
  34515. */
  34516. Material.prototype.getBindedMeshes = function () {
  34517. var result = new Array();
  34518. for (var index = 0; index < this._scene.meshes.length; index++) {
  34519. var mesh = this._scene.meshes[index];
  34520. if (mesh.material === this) {
  34521. result.push(mesh);
  34522. }
  34523. }
  34524. return result;
  34525. };
  34526. /**
  34527. * Force shader compilation
  34528. * @param mesh defines the mesh associated with this material
  34529. * @param onCompiled defines a function to execute once the material is compiled
  34530. * @param options defines the options to configure the compilation
  34531. */
  34532. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34533. var _this = this;
  34534. var localOptions = __assign({ clipPlane: false }, options);
  34535. var subMesh = new BABYLON.BaseSubMesh();
  34536. var scene = this.getScene();
  34537. var checkReady = function () {
  34538. if (!_this._scene || !_this._scene.getEngine()) {
  34539. return;
  34540. }
  34541. if (subMesh._materialDefines) {
  34542. subMesh._materialDefines._renderId = -1;
  34543. }
  34544. var clipPlaneState = scene.clipPlane;
  34545. if (localOptions.clipPlane) {
  34546. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34547. }
  34548. if (_this.storeEffectOnSubMeshes) {
  34549. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34550. if (onCompiled) {
  34551. onCompiled(_this);
  34552. }
  34553. }
  34554. else {
  34555. setTimeout(checkReady, 16);
  34556. }
  34557. }
  34558. else {
  34559. if (_this.isReady(mesh)) {
  34560. if (onCompiled) {
  34561. onCompiled(_this);
  34562. }
  34563. }
  34564. else {
  34565. setTimeout(checkReady, 16);
  34566. }
  34567. }
  34568. if (localOptions.clipPlane) {
  34569. scene.clipPlane = clipPlaneState;
  34570. }
  34571. };
  34572. checkReady();
  34573. };
  34574. /**
  34575. * Force shader compilation
  34576. * @param mesh defines the mesh that will use this material
  34577. * @param options defines additional options for compiling the shaders
  34578. * @returns a promise that resolves when the compilation completes
  34579. */
  34580. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34581. var _this = this;
  34582. return new Promise(function (resolve) {
  34583. _this.forceCompilation(mesh, function () {
  34584. resolve();
  34585. }, options);
  34586. });
  34587. };
  34588. /**
  34589. * Marks a define in the material to indicate that it needs to be re-computed
  34590. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34591. */
  34592. Material.prototype.markAsDirty = function (flag) {
  34593. if (flag & Material.TextureDirtyFlag) {
  34594. this._markAllSubMeshesAsTexturesDirty();
  34595. }
  34596. if (flag & Material.LightDirtyFlag) {
  34597. this._markAllSubMeshesAsLightsDirty();
  34598. }
  34599. if (flag & Material.FresnelDirtyFlag) {
  34600. this._markAllSubMeshesAsFresnelDirty();
  34601. }
  34602. if (flag & Material.AttributesDirtyFlag) {
  34603. this._markAllSubMeshesAsAttributesDirty();
  34604. }
  34605. if (flag & Material.MiscDirtyFlag) {
  34606. this._markAllSubMeshesAsMiscDirty();
  34607. }
  34608. this.getScene().resetCachedMaterial();
  34609. };
  34610. /**
  34611. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34612. * @param func defines a function which checks material defines against the submeshes
  34613. */
  34614. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34615. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34616. var mesh = _a[_i];
  34617. if (!mesh.subMeshes) {
  34618. continue;
  34619. }
  34620. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34621. var subMesh = _c[_b];
  34622. if (subMesh.getMaterial() !== this) {
  34623. continue;
  34624. }
  34625. if (!subMesh._materialDefines) {
  34626. continue;
  34627. }
  34628. func(subMesh._materialDefines);
  34629. }
  34630. }
  34631. };
  34632. /**
  34633. * Indicates that image processing needs to be re-calculated for all submeshes
  34634. */
  34635. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34636. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34637. };
  34638. /**
  34639. * Indicates that textures need to be re-calculated for all submeshes
  34640. */
  34641. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34642. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34643. };
  34644. /**
  34645. * Indicates that fresnel needs to be re-calculated for all submeshes
  34646. */
  34647. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34648. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34649. };
  34650. /**
  34651. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34652. */
  34653. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34654. this._markAllSubMeshesAsDirty(function (defines) {
  34655. defines.markAsFresnelDirty();
  34656. defines.markAsMiscDirty();
  34657. });
  34658. };
  34659. /**
  34660. * Indicates that lights need to be re-calculated for all submeshes
  34661. */
  34662. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34663. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34664. };
  34665. /**
  34666. * Indicates that attributes need to be re-calculated for all submeshes
  34667. */
  34668. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34669. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34670. };
  34671. /**
  34672. * Indicates that misc needs to be re-calculated for all submeshes
  34673. */
  34674. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34675. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34676. };
  34677. /**
  34678. * Indicates that textures and misc need to be re-calculated for all submeshes
  34679. */
  34680. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34681. this._markAllSubMeshesAsDirty(function (defines) {
  34682. defines.markAsTexturesDirty();
  34683. defines.markAsMiscDirty();
  34684. });
  34685. };
  34686. /**
  34687. * Disposes the material
  34688. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34689. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34690. */
  34691. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34692. // Animations
  34693. this.getScene().stopAnimation(this);
  34694. this.getScene().freeProcessedMaterials();
  34695. // Remove from scene
  34696. var index = this._scene.materials.indexOf(this);
  34697. if (index >= 0) {
  34698. this._scene.materials.splice(index, 1);
  34699. }
  34700. // Remove from meshes
  34701. for (index = 0; index < this._scene.meshes.length; index++) {
  34702. var mesh = this._scene.meshes[index];
  34703. if (mesh.material === this) {
  34704. mesh.material = null;
  34705. if (mesh.geometry) {
  34706. var geometry = (mesh.geometry);
  34707. if (this.storeEffectOnSubMeshes) {
  34708. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  34709. var subMesh = _a[_i];
  34710. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  34711. if (forceDisposeEffect && subMesh._materialEffect) {
  34712. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  34713. }
  34714. }
  34715. }
  34716. else {
  34717. geometry._releaseVertexArrayObject(this._effect);
  34718. }
  34719. }
  34720. }
  34721. }
  34722. this._uniformBuffer.dispose();
  34723. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  34724. if (forceDisposeEffect && this._effect) {
  34725. if (!this.storeEffectOnSubMeshes) {
  34726. this._scene.getEngine()._releaseEffect(this._effect);
  34727. }
  34728. this._effect = null;
  34729. }
  34730. // Callback
  34731. this.onDisposeObservable.notifyObservers(this);
  34732. this.onDisposeObservable.clear();
  34733. this.onBindObservable.clear();
  34734. this.onUnBindObservable.clear();
  34735. };
  34736. /**
  34737. * Serializes this material
  34738. * @returns the serialized material object
  34739. */
  34740. Material.prototype.serialize = function () {
  34741. return BABYLON.SerializationHelper.Serialize(this);
  34742. };
  34743. /**
  34744. * Creates a MultiMaterial from parsed MultiMaterial data.
  34745. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  34746. * @param scene defines the hosting scene
  34747. * @returns a new MultiMaterial
  34748. */
  34749. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  34750. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  34751. multiMaterial.id = parsedMultiMaterial.id;
  34752. if (BABYLON.Tags) {
  34753. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  34754. }
  34755. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  34756. var subMatId = parsedMultiMaterial.materials[matIndex];
  34757. if (subMatId) {
  34758. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  34759. }
  34760. else {
  34761. multiMaterial.subMaterials.push(null);
  34762. }
  34763. }
  34764. return multiMaterial;
  34765. };
  34766. /**
  34767. * Creates a material from parsed material data
  34768. * @param parsedMaterial defines parsed material data
  34769. * @param scene defines the hosting scene
  34770. * @param rootUrl defines the root URL to use to load textures
  34771. * @returns a new material
  34772. */
  34773. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  34774. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  34775. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  34776. }
  34777. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  34778. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  34779. if (!BABYLON.LegacyPBRMaterial) {
  34780. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  34781. return;
  34782. }
  34783. }
  34784. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  34785. return materialType.Parse(parsedMaterial, scene, rootUrl);
  34786. ;
  34787. };
  34788. // Triangle views
  34789. Material._TriangleFillMode = 0;
  34790. Material._WireFrameFillMode = 1;
  34791. Material._PointFillMode = 2;
  34792. // Draw modes
  34793. Material._PointListDrawMode = 3;
  34794. Material._LineListDrawMode = 4;
  34795. Material._LineLoopDrawMode = 5;
  34796. Material._LineStripDrawMode = 6;
  34797. Material._TriangleStripDrawMode = 7;
  34798. Material._TriangleFanDrawMode = 8;
  34799. /**
  34800. * Stores the clock-wise side orientation
  34801. */
  34802. Material._ClockWiseSideOrientation = 0;
  34803. /**
  34804. * Stores the counter clock-wise side orientation
  34805. */
  34806. Material._CounterClockWiseSideOrientation = 1;
  34807. /**
  34808. * The dirty texture flag value
  34809. */
  34810. Material._TextureDirtyFlag = 1;
  34811. /**
  34812. * The dirty light flag value
  34813. */
  34814. Material._LightDirtyFlag = 2;
  34815. /**
  34816. * The dirty fresnel flag value
  34817. */
  34818. Material._FresnelDirtyFlag = 4;
  34819. /**
  34820. * The dirty attribute flag value
  34821. */
  34822. Material._AttributesDirtyFlag = 8;
  34823. /**
  34824. * The dirty misc flag value
  34825. */
  34826. Material._MiscDirtyFlag = 16;
  34827. __decorate([
  34828. BABYLON.serialize()
  34829. ], Material.prototype, "id", void 0);
  34830. __decorate([
  34831. BABYLON.serialize()
  34832. ], Material.prototype, "name", void 0);
  34833. __decorate([
  34834. BABYLON.serialize()
  34835. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  34836. __decorate([
  34837. BABYLON.serialize()
  34838. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  34839. __decorate([
  34840. BABYLON.serialize()
  34841. ], Material.prototype, "state", void 0);
  34842. __decorate([
  34843. BABYLON.serialize("alpha")
  34844. ], Material.prototype, "_alpha", void 0);
  34845. __decorate([
  34846. BABYLON.serialize("backFaceCulling")
  34847. ], Material.prototype, "_backFaceCulling", void 0);
  34848. __decorate([
  34849. BABYLON.serialize()
  34850. ], Material.prototype, "sideOrientation", void 0);
  34851. __decorate([
  34852. BABYLON.serialize("alphaMode")
  34853. ], Material.prototype, "_alphaMode", void 0);
  34854. __decorate([
  34855. BABYLON.serialize()
  34856. ], Material.prototype, "_needDepthPrePass", void 0);
  34857. __decorate([
  34858. BABYLON.serialize()
  34859. ], Material.prototype, "disableDepthWrite", void 0);
  34860. __decorate([
  34861. BABYLON.serialize()
  34862. ], Material.prototype, "forceDepthWrite", void 0);
  34863. __decorate([
  34864. BABYLON.serialize()
  34865. ], Material.prototype, "separateCullingPass", void 0);
  34866. __decorate([
  34867. BABYLON.serialize("fogEnabled")
  34868. ], Material.prototype, "_fogEnabled", void 0);
  34869. __decorate([
  34870. BABYLON.serialize()
  34871. ], Material.prototype, "pointSize", void 0);
  34872. __decorate([
  34873. BABYLON.serialize()
  34874. ], Material.prototype, "zOffset", void 0);
  34875. __decorate([
  34876. BABYLON.serialize()
  34877. ], Material.prototype, "wireframe", null);
  34878. __decorate([
  34879. BABYLON.serialize()
  34880. ], Material.prototype, "pointsCloud", null);
  34881. __decorate([
  34882. BABYLON.serialize()
  34883. ], Material.prototype, "fillMode", null);
  34884. return Material;
  34885. }());
  34886. BABYLON.Material = Material;
  34887. })(BABYLON || (BABYLON = {}));
  34888. //# sourceMappingURL=babylon.material.js.map
  34889. "use strict";
  34890. var BABYLON;
  34891. (function (BABYLON) {
  34892. var UniformBuffer = /** @class */ (function () {
  34893. /**
  34894. * Uniform buffer objects.
  34895. *
  34896. * Handles blocks of uniform on the GPU.
  34897. *
  34898. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  34899. *
  34900. * For more information, please refer to :
  34901. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  34902. */
  34903. function UniformBuffer(engine, data, dynamic) {
  34904. this._engine = engine;
  34905. this._noUBO = !engine.supportsUniformBuffers;
  34906. this._dynamic = dynamic;
  34907. this._data = data || [];
  34908. this._uniformLocations = {};
  34909. this._uniformSizes = {};
  34910. this._uniformLocationPointer = 0;
  34911. this._needSync = false;
  34912. if (this._noUBO) {
  34913. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  34914. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  34915. this.updateFloat = this._updateFloatForEffect;
  34916. this.updateFloat2 = this._updateFloat2ForEffect;
  34917. this.updateFloat3 = this._updateFloat3ForEffect;
  34918. this.updateFloat4 = this._updateFloat4ForEffect;
  34919. this.updateMatrix = this._updateMatrixForEffect;
  34920. this.updateVector3 = this._updateVector3ForEffect;
  34921. this.updateVector4 = this._updateVector4ForEffect;
  34922. this.updateColor3 = this._updateColor3ForEffect;
  34923. this.updateColor4 = this._updateColor4ForEffect;
  34924. }
  34925. else {
  34926. this._engine._uniformBuffers.push(this);
  34927. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  34928. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  34929. this.updateFloat = this._updateFloatForUniform;
  34930. this.updateFloat2 = this._updateFloat2ForUniform;
  34931. this.updateFloat3 = this._updateFloat3ForUniform;
  34932. this.updateFloat4 = this._updateFloat4ForUniform;
  34933. this.updateMatrix = this._updateMatrixForUniform;
  34934. this.updateVector3 = this._updateVector3ForUniform;
  34935. this.updateVector4 = this._updateVector4ForUniform;
  34936. this.updateColor3 = this._updateColor3ForUniform;
  34937. this.updateColor4 = this._updateColor4ForUniform;
  34938. }
  34939. }
  34940. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  34941. // Properties
  34942. /**
  34943. * Indicates if the buffer is using the WebGL2 UBO implementation,
  34944. * or just falling back on setUniformXXX calls.
  34945. */
  34946. get: function () {
  34947. return !this._noUBO;
  34948. },
  34949. enumerable: true,
  34950. configurable: true
  34951. });
  34952. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  34953. /**
  34954. * Indicates if the WebGL underlying uniform buffer is in sync
  34955. * with the javascript cache data.
  34956. */
  34957. get: function () {
  34958. return !this._needSync;
  34959. },
  34960. enumerable: true,
  34961. configurable: true
  34962. });
  34963. /**
  34964. * Indicates if the WebGL underlying uniform buffer is dynamic.
  34965. * Also, a dynamic UniformBuffer will disable cache verification and always
  34966. * update the underlying WebGL uniform buffer to the GPU.
  34967. */
  34968. UniformBuffer.prototype.isDynamic = function () {
  34969. return this._dynamic !== undefined;
  34970. };
  34971. /**
  34972. * The data cache on JS side.
  34973. */
  34974. UniformBuffer.prototype.getData = function () {
  34975. return this._bufferData;
  34976. };
  34977. /**
  34978. * The underlying WebGL Uniform buffer.
  34979. */
  34980. UniformBuffer.prototype.getBuffer = function () {
  34981. return this._buffer;
  34982. };
  34983. /**
  34984. * std140 layout specifies how to align data within an UBO structure.
  34985. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  34986. * for specs.
  34987. */
  34988. UniformBuffer.prototype._fillAlignment = function (size) {
  34989. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  34990. // and 4x4 matrices
  34991. // TODO : change if other types are used
  34992. var alignment;
  34993. if (size <= 2) {
  34994. alignment = size;
  34995. }
  34996. else {
  34997. alignment = 4;
  34998. }
  34999. if ((this._uniformLocationPointer % alignment) !== 0) {
  35000. var oldPointer = this._uniformLocationPointer;
  35001. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35002. var diff = this._uniformLocationPointer - oldPointer;
  35003. for (var i = 0; i < diff; i++) {
  35004. this._data.push(0);
  35005. }
  35006. }
  35007. };
  35008. /**
  35009. * Adds an uniform in the buffer.
  35010. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35011. * for the layout to be correct !
  35012. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35013. * @param {number|number[]} size Data size, or data directly.
  35014. */
  35015. UniformBuffer.prototype.addUniform = function (name, size) {
  35016. if (this._noUBO) {
  35017. return;
  35018. }
  35019. if (this._uniformLocations[name] !== undefined) {
  35020. // Already existing uniform
  35021. return;
  35022. }
  35023. // This function must be called in the order of the shader layout !
  35024. // size can be the size of the uniform, or data directly
  35025. var data;
  35026. if (size instanceof Array) {
  35027. data = size;
  35028. size = data.length;
  35029. }
  35030. else {
  35031. size = size;
  35032. data = [];
  35033. // Fill with zeros
  35034. for (var i = 0; i < size; i++) {
  35035. data.push(0);
  35036. }
  35037. }
  35038. this._fillAlignment(size);
  35039. this._uniformSizes[name] = size;
  35040. this._uniformLocations[name] = this._uniformLocationPointer;
  35041. this._uniformLocationPointer += size;
  35042. for (var i = 0; i < size; i++) {
  35043. this._data.push(data[i]);
  35044. }
  35045. this._needSync = true;
  35046. };
  35047. /**
  35048. * Wrapper for addUniform.
  35049. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35050. * @param {Matrix} mat A 4x4 matrix.
  35051. */
  35052. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35053. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35054. };
  35055. /**
  35056. * Wrapper for addUniform.
  35057. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35058. * @param {number} x
  35059. * @param {number} y
  35060. */
  35061. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35062. var temp = [x, y];
  35063. this.addUniform(name, temp);
  35064. };
  35065. /**
  35066. * Wrapper for addUniform.
  35067. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35068. * @param {number} x
  35069. * @param {number} y
  35070. * @param {number} z
  35071. */
  35072. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35073. var temp = [x, y, z];
  35074. this.addUniform(name, temp);
  35075. };
  35076. /**
  35077. * Wrapper for addUniform.
  35078. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35079. * @param {Color3} color
  35080. */
  35081. UniformBuffer.prototype.addColor3 = function (name, color) {
  35082. var temp = new Array();
  35083. color.toArray(temp);
  35084. this.addUniform(name, temp);
  35085. };
  35086. /**
  35087. * Wrapper for addUniform.
  35088. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35089. * @param {Color3} color
  35090. * @param {number} alpha
  35091. */
  35092. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35093. var temp = new Array();
  35094. color.toArray(temp);
  35095. temp.push(alpha);
  35096. this.addUniform(name, temp);
  35097. };
  35098. /**
  35099. * Wrapper for addUniform.
  35100. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35101. * @param {Vector3} vector
  35102. */
  35103. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35104. var temp = new Array();
  35105. vector.toArray(temp);
  35106. this.addUniform(name, temp);
  35107. };
  35108. /**
  35109. * Wrapper for addUniform.
  35110. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35111. */
  35112. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35113. this.addUniform(name, 12);
  35114. };
  35115. /**
  35116. * Wrapper for addUniform.
  35117. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35118. */
  35119. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35120. this.addUniform(name, 8);
  35121. };
  35122. /**
  35123. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35124. */
  35125. UniformBuffer.prototype.create = function () {
  35126. if (this._noUBO) {
  35127. return;
  35128. }
  35129. if (this._buffer) {
  35130. return; // nothing to do
  35131. }
  35132. // See spec, alignment must be filled as a vec4
  35133. this._fillAlignment(4);
  35134. this._bufferData = new Float32Array(this._data);
  35135. this._rebuild();
  35136. this._needSync = true;
  35137. };
  35138. UniformBuffer.prototype._rebuild = function () {
  35139. if (this._noUBO) {
  35140. return;
  35141. }
  35142. if (this._dynamic) {
  35143. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35144. }
  35145. else {
  35146. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35147. }
  35148. };
  35149. /**
  35150. * Updates the WebGL Uniform Buffer on the GPU.
  35151. * If the `dynamic` flag is set to true, no cache comparison is done.
  35152. * Otherwise, the buffer will be updated only if the cache differs.
  35153. */
  35154. UniformBuffer.prototype.update = function () {
  35155. if (!this._buffer) {
  35156. this.create();
  35157. return;
  35158. }
  35159. if (!this._dynamic && !this._needSync) {
  35160. return;
  35161. }
  35162. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35163. this._needSync = false;
  35164. };
  35165. /**
  35166. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35167. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35168. * @param {number[]|Float32Array} data Flattened data
  35169. * @param {number} size Size of the data.
  35170. */
  35171. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35172. var location = this._uniformLocations[uniformName];
  35173. if (location === undefined) {
  35174. if (this._buffer) {
  35175. // Cannot add an uniform if the buffer is already created
  35176. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35177. return;
  35178. }
  35179. this.addUniform(uniformName, size);
  35180. location = this._uniformLocations[uniformName];
  35181. }
  35182. if (!this._buffer) {
  35183. this.create();
  35184. }
  35185. if (!this._dynamic) {
  35186. // Cache for static uniform buffers
  35187. var changed = false;
  35188. for (var i = 0; i < size; i++) {
  35189. if (this._bufferData[location + i] !== data[i]) {
  35190. changed = true;
  35191. this._bufferData[location + i] = data[i];
  35192. }
  35193. }
  35194. this._needSync = this._needSync || changed;
  35195. }
  35196. else {
  35197. // No cache for dynamic
  35198. for (var i = 0; i < size; i++) {
  35199. this._bufferData[location + i] = data[i];
  35200. }
  35201. }
  35202. };
  35203. // Update methods
  35204. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35205. // To match std140, matrix must be realigned
  35206. for (var i = 0; i < 3; i++) {
  35207. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35208. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35209. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35210. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35211. }
  35212. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35213. };
  35214. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35215. this._currentEffect.setMatrix3x3(name, matrix);
  35216. };
  35217. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35218. this._currentEffect.setMatrix2x2(name, matrix);
  35219. };
  35220. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35221. // To match std140, matrix must be realigned
  35222. for (var i = 0; i < 2; i++) {
  35223. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35224. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35225. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35226. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35227. }
  35228. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35229. };
  35230. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35231. this._currentEffect.setFloat(name, x);
  35232. };
  35233. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35234. UniformBuffer._tempBuffer[0] = x;
  35235. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35236. };
  35237. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35238. if (suffix === void 0) { suffix = ""; }
  35239. this._currentEffect.setFloat2(name + suffix, x, y);
  35240. };
  35241. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35242. if (suffix === void 0) { suffix = ""; }
  35243. UniformBuffer._tempBuffer[0] = x;
  35244. UniformBuffer._tempBuffer[1] = y;
  35245. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35246. };
  35247. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35248. if (suffix === void 0) { suffix = ""; }
  35249. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35250. };
  35251. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35252. if (suffix === void 0) { suffix = ""; }
  35253. UniformBuffer._tempBuffer[0] = x;
  35254. UniformBuffer._tempBuffer[1] = y;
  35255. UniformBuffer._tempBuffer[2] = z;
  35256. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35257. };
  35258. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35259. if (suffix === void 0) { suffix = ""; }
  35260. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35261. };
  35262. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35263. if (suffix === void 0) { suffix = ""; }
  35264. UniformBuffer._tempBuffer[0] = x;
  35265. UniformBuffer._tempBuffer[1] = y;
  35266. UniformBuffer._tempBuffer[2] = z;
  35267. UniformBuffer._tempBuffer[3] = w;
  35268. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35269. };
  35270. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35271. this._currentEffect.setMatrix(name, mat);
  35272. };
  35273. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35274. this.updateUniform(name, mat.toArray(), 16);
  35275. };
  35276. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35277. this._currentEffect.setVector3(name, vector);
  35278. };
  35279. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35280. vector.toArray(UniformBuffer._tempBuffer);
  35281. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35282. };
  35283. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35284. this._currentEffect.setVector4(name, vector);
  35285. };
  35286. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35287. vector.toArray(UniformBuffer._tempBuffer);
  35288. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35289. };
  35290. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35291. if (suffix === void 0) { suffix = ""; }
  35292. this._currentEffect.setColor3(name + suffix, color);
  35293. };
  35294. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35295. if (suffix === void 0) { suffix = ""; }
  35296. color.toArray(UniformBuffer._tempBuffer);
  35297. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35298. };
  35299. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35300. if (suffix === void 0) { suffix = ""; }
  35301. this._currentEffect.setColor4(name + suffix, color, alpha);
  35302. };
  35303. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35304. if (suffix === void 0) { suffix = ""; }
  35305. color.toArray(UniformBuffer._tempBuffer);
  35306. UniformBuffer._tempBuffer[3] = alpha;
  35307. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35308. };
  35309. /**
  35310. * Sets a sampler uniform on the effect.
  35311. * @param {string} name Name of the sampler.
  35312. * @param {Texture} texture
  35313. */
  35314. UniformBuffer.prototype.setTexture = function (name, texture) {
  35315. this._currentEffect.setTexture(name, texture);
  35316. };
  35317. /**
  35318. * Directly updates the value of the uniform in the cache AND on the GPU.
  35319. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35320. * @param {number[]|Float32Array} data Flattened data
  35321. */
  35322. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35323. this.updateUniform(uniformName, data, data.length);
  35324. this.update();
  35325. };
  35326. /**
  35327. * Binds this uniform buffer to an effect.
  35328. * @param {Effect} effect
  35329. * @param {string} name Name of the uniform block in the shader.
  35330. */
  35331. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35332. this._currentEffect = effect;
  35333. if (this._noUBO || !this._buffer) {
  35334. return;
  35335. }
  35336. effect.bindUniformBuffer(this._buffer, name);
  35337. };
  35338. /**
  35339. * Disposes the uniform buffer.
  35340. */
  35341. UniformBuffer.prototype.dispose = function () {
  35342. if (this._noUBO) {
  35343. return;
  35344. }
  35345. var index = this._engine._uniformBuffers.indexOf(this);
  35346. if (index !== -1) {
  35347. this._engine._uniformBuffers.splice(index, 1);
  35348. }
  35349. if (!this._buffer) {
  35350. return;
  35351. }
  35352. if (this._engine._releaseBuffer(this._buffer)) {
  35353. this._buffer = null;
  35354. }
  35355. };
  35356. // Pool for avoiding memory leaks
  35357. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35358. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35359. return UniformBuffer;
  35360. }());
  35361. BABYLON.UniformBuffer = UniformBuffer;
  35362. })(BABYLON || (BABYLON = {}));
  35363. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35364. "use strict";
  35365. var BABYLON;
  35366. (function (BABYLON) {
  35367. var VertexData = /** @class */ (function () {
  35368. function VertexData() {
  35369. }
  35370. VertexData.prototype.set = function (data, kind) {
  35371. switch (kind) {
  35372. case BABYLON.VertexBuffer.PositionKind:
  35373. this.positions = data;
  35374. break;
  35375. case BABYLON.VertexBuffer.NormalKind:
  35376. this.normals = data;
  35377. break;
  35378. case BABYLON.VertexBuffer.TangentKind:
  35379. this.tangents = data;
  35380. break;
  35381. case BABYLON.VertexBuffer.UVKind:
  35382. this.uvs = data;
  35383. break;
  35384. case BABYLON.VertexBuffer.UV2Kind:
  35385. this.uvs2 = data;
  35386. break;
  35387. case BABYLON.VertexBuffer.UV3Kind:
  35388. this.uvs3 = data;
  35389. break;
  35390. case BABYLON.VertexBuffer.UV4Kind:
  35391. this.uvs4 = data;
  35392. break;
  35393. case BABYLON.VertexBuffer.UV5Kind:
  35394. this.uvs5 = data;
  35395. break;
  35396. case BABYLON.VertexBuffer.UV6Kind:
  35397. this.uvs6 = data;
  35398. break;
  35399. case BABYLON.VertexBuffer.ColorKind:
  35400. this.colors = data;
  35401. break;
  35402. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35403. this.matricesIndices = data;
  35404. break;
  35405. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35406. this.matricesWeights = data;
  35407. break;
  35408. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35409. this.matricesIndicesExtra = data;
  35410. break;
  35411. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35412. this.matricesWeightsExtra = data;
  35413. break;
  35414. }
  35415. };
  35416. /**
  35417. * Associates the vertexData to the passed Mesh.
  35418. * Sets it as updatable or not (default `false`).
  35419. * Returns the VertexData.
  35420. */
  35421. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35422. this._applyTo(mesh, updatable);
  35423. return this;
  35424. };
  35425. /**
  35426. * Associates the vertexData to the passed Geometry.
  35427. * Sets it as updatable or not (default `false`).
  35428. * Returns the VertexData.
  35429. */
  35430. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35431. this._applyTo(geometry, updatable);
  35432. return this;
  35433. };
  35434. /**
  35435. * Updates the associated mesh.
  35436. * Returns the VertexData.
  35437. */
  35438. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35439. this._update(mesh);
  35440. return this;
  35441. };
  35442. /**
  35443. * Updates the associated geometry.
  35444. * Returns the VertexData.
  35445. */
  35446. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35447. this._update(geometry);
  35448. return this;
  35449. };
  35450. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35451. if (updatable === void 0) { updatable = false; }
  35452. if (this.positions) {
  35453. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35454. }
  35455. if (this.normals) {
  35456. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35457. }
  35458. if (this.tangents) {
  35459. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35460. }
  35461. if (this.uvs) {
  35462. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35463. }
  35464. if (this.uvs2) {
  35465. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35466. }
  35467. if (this.uvs3) {
  35468. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35469. }
  35470. if (this.uvs4) {
  35471. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35472. }
  35473. if (this.uvs5) {
  35474. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35475. }
  35476. if (this.uvs6) {
  35477. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35478. }
  35479. if (this.colors) {
  35480. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35481. }
  35482. if (this.matricesIndices) {
  35483. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35484. }
  35485. if (this.matricesWeights) {
  35486. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35487. }
  35488. if (this.matricesIndicesExtra) {
  35489. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35490. }
  35491. if (this.matricesWeightsExtra) {
  35492. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35493. }
  35494. if (this.indices) {
  35495. meshOrGeometry.setIndices(this.indices, null, updatable);
  35496. }
  35497. return this;
  35498. };
  35499. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35500. if (this.positions) {
  35501. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35502. }
  35503. if (this.normals) {
  35504. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35505. }
  35506. if (this.tangents) {
  35507. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35508. }
  35509. if (this.uvs) {
  35510. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35511. }
  35512. if (this.uvs2) {
  35513. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35514. }
  35515. if (this.uvs3) {
  35516. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35517. }
  35518. if (this.uvs4) {
  35519. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35520. }
  35521. if (this.uvs5) {
  35522. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35523. }
  35524. if (this.uvs6) {
  35525. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35526. }
  35527. if (this.colors) {
  35528. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35529. }
  35530. if (this.matricesIndices) {
  35531. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35532. }
  35533. if (this.matricesWeights) {
  35534. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35535. }
  35536. if (this.matricesIndicesExtra) {
  35537. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35538. }
  35539. if (this.matricesWeightsExtra) {
  35540. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35541. }
  35542. if (this.indices) {
  35543. meshOrGeometry.setIndices(this.indices, null);
  35544. }
  35545. return this;
  35546. };
  35547. /**
  35548. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  35549. * Returns the VertexData.
  35550. */
  35551. VertexData.prototype.transform = function (matrix) {
  35552. var transformed = BABYLON.Vector3.Zero();
  35553. var index;
  35554. if (this.positions) {
  35555. var position = BABYLON.Vector3.Zero();
  35556. for (index = 0; index < this.positions.length; index += 3) {
  35557. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35558. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35559. this.positions[index] = transformed.x;
  35560. this.positions[index + 1] = transformed.y;
  35561. this.positions[index + 2] = transformed.z;
  35562. }
  35563. }
  35564. if (this.normals) {
  35565. var normal = BABYLON.Vector3.Zero();
  35566. for (index = 0; index < this.normals.length; index += 3) {
  35567. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35568. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35569. this.normals[index] = transformed.x;
  35570. this.normals[index + 1] = transformed.y;
  35571. this.normals[index + 2] = transformed.z;
  35572. }
  35573. }
  35574. if (this.tangents) {
  35575. var tangent = BABYLON.Vector4.Zero();
  35576. var tangentTransformed = BABYLON.Vector4.Zero();
  35577. for (index = 0; index < this.tangents.length; index += 4) {
  35578. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35579. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35580. this.tangents[index] = tangentTransformed.x;
  35581. this.tangents[index + 1] = tangentTransformed.y;
  35582. this.tangents[index + 2] = tangentTransformed.z;
  35583. this.tangents[index + 3] = tangentTransformed.w;
  35584. }
  35585. }
  35586. return this;
  35587. };
  35588. /**
  35589. * Merges the passed VertexData into the current one.
  35590. * Returns the modified VertexData.
  35591. */
  35592. VertexData.prototype.merge = function (other) {
  35593. this._validate();
  35594. other._validate();
  35595. if (!this.normals !== !other.normals ||
  35596. !this.tangents !== !other.tangents ||
  35597. !this.uvs !== !other.uvs ||
  35598. !this.uvs2 !== !other.uvs2 ||
  35599. !this.uvs3 !== !other.uvs3 ||
  35600. !this.uvs4 !== !other.uvs4 ||
  35601. !this.uvs5 !== !other.uvs5 ||
  35602. !this.uvs6 !== !other.uvs6 ||
  35603. !this.colors !== !other.colors ||
  35604. !this.matricesIndices !== !other.matricesIndices ||
  35605. !this.matricesWeights !== !other.matricesWeights ||
  35606. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35607. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35608. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35609. }
  35610. if (other.indices) {
  35611. if (!this.indices) {
  35612. this.indices = [];
  35613. }
  35614. var offset = this.positions ? this.positions.length / 3 : 0;
  35615. for (var index = 0; index < other.indices.length; index++) {
  35616. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35617. this.indices.push(other.indices[index] + offset);
  35618. }
  35619. }
  35620. this.positions = this._mergeElement(this.positions, other.positions);
  35621. this.normals = this._mergeElement(this.normals, other.normals);
  35622. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35623. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35624. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35625. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35626. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35627. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35628. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35629. this.colors = this._mergeElement(this.colors, other.colors);
  35630. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35631. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35632. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35633. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35634. return this;
  35635. };
  35636. VertexData.prototype._mergeElement = function (source, other) {
  35637. if (!source) {
  35638. return other;
  35639. }
  35640. if (!other) {
  35641. return source;
  35642. }
  35643. var len = other.length + source.length;
  35644. var isSrcTypedArray = source instanceof Float32Array;
  35645. var isOthTypedArray = other instanceof Float32Array;
  35646. // use non-loop method when the source is Float32Array
  35647. if (isSrcTypedArray) {
  35648. var ret32 = new Float32Array(len);
  35649. ret32.set(source);
  35650. ret32.set(other, source.length);
  35651. return ret32;
  35652. // source is number[], when other is also use concat
  35653. }
  35654. else if (!isOthTypedArray) {
  35655. return source.concat(other);
  35656. // source is a number[], but other is a Float32Array, loop required
  35657. }
  35658. else {
  35659. var ret = source.slice(0); // copy source to a separate array
  35660. for (var i = 0, len = other.length; i < len; i++) {
  35661. ret.push(other[i]);
  35662. }
  35663. return ret;
  35664. }
  35665. };
  35666. VertexData.prototype._validate = function () {
  35667. if (!this.positions) {
  35668. throw new Error("Positions are required");
  35669. }
  35670. var getElementCount = function (kind, values) {
  35671. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35672. if ((values.length % stride) !== 0) {
  35673. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  35674. }
  35675. return values.length / stride;
  35676. };
  35677. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  35678. var validateElementCount = function (kind, values) {
  35679. var elementCount = getElementCount(kind, values);
  35680. if (elementCount !== positionsElementCount) {
  35681. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  35682. }
  35683. };
  35684. if (this.normals)
  35685. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  35686. if (this.tangents)
  35687. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  35688. if (this.uvs)
  35689. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  35690. if (this.uvs2)
  35691. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  35692. if (this.uvs3)
  35693. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  35694. if (this.uvs4)
  35695. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  35696. if (this.uvs5)
  35697. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  35698. if (this.uvs6)
  35699. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  35700. if (this.colors)
  35701. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  35702. if (this.matricesIndices)
  35703. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  35704. if (this.matricesWeights)
  35705. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  35706. if (this.matricesIndicesExtra)
  35707. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  35708. if (this.matricesWeightsExtra)
  35709. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  35710. };
  35711. /**
  35712. * Serializes the VertexData.
  35713. * Returns a serialized object.
  35714. */
  35715. VertexData.prototype.serialize = function () {
  35716. var serializationObject = this.serialize();
  35717. if (this.positions) {
  35718. serializationObject.positions = this.positions;
  35719. }
  35720. if (this.normals) {
  35721. serializationObject.normals = this.normals;
  35722. }
  35723. if (this.tangents) {
  35724. serializationObject.tangents = this.tangents;
  35725. }
  35726. if (this.uvs) {
  35727. serializationObject.uvs = this.uvs;
  35728. }
  35729. if (this.uvs2) {
  35730. serializationObject.uvs2 = this.uvs2;
  35731. }
  35732. if (this.uvs3) {
  35733. serializationObject.uvs3 = this.uvs3;
  35734. }
  35735. if (this.uvs4) {
  35736. serializationObject.uvs4 = this.uvs4;
  35737. }
  35738. if (this.uvs5) {
  35739. serializationObject.uvs5 = this.uvs5;
  35740. }
  35741. if (this.uvs6) {
  35742. serializationObject.uvs6 = this.uvs6;
  35743. }
  35744. if (this.colors) {
  35745. serializationObject.colors = this.colors;
  35746. }
  35747. if (this.matricesIndices) {
  35748. serializationObject.matricesIndices = this.matricesIndices;
  35749. serializationObject.matricesIndices._isExpanded = true;
  35750. }
  35751. if (this.matricesWeights) {
  35752. serializationObject.matricesWeights = this.matricesWeights;
  35753. }
  35754. if (this.matricesIndicesExtra) {
  35755. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  35756. serializationObject.matricesIndicesExtra._isExpanded = true;
  35757. }
  35758. if (this.matricesWeightsExtra) {
  35759. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  35760. }
  35761. serializationObject.indices = this.indices;
  35762. return serializationObject;
  35763. };
  35764. // Statics
  35765. /**
  35766. * Returns the object VertexData associated to the passed mesh.
  35767. */
  35768. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  35769. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  35770. };
  35771. /**
  35772. * Returns the object VertexData associated to the passed geometry.
  35773. */
  35774. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  35775. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  35776. };
  35777. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  35778. var result = new VertexData();
  35779. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35780. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  35781. }
  35782. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35783. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  35784. }
  35785. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35786. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  35787. }
  35788. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35789. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  35790. }
  35791. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35792. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  35793. }
  35794. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35795. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  35796. }
  35797. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35798. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  35799. }
  35800. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35801. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  35802. }
  35803. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35804. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  35805. }
  35806. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35807. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  35808. }
  35809. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35810. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  35811. }
  35812. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35813. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  35814. }
  35815. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  35816. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  35817. }
  35818. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  35819. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  35820. }
  35821. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  35822. return result;
  35823. };
  35824. /**
  35825. * Creates the vertexData of the Ribbon.
  35826. */
  35827. VertexData.CreateRibbon = function (options) {
  35828. var pathArray = options.pathArray;
  35829. var closeArray = options.closeArray || false;
  35830. var closePath = options.closePath || false;
  35831. var invertUV = options.invertUV || false;
  35832. var defaultOffset = Math.floor(pathArray[0].length / 2);
  35833. var offset = options.offset || defaultOffset;
  35834. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  35835. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35836. var customUV = options.uvs;
  35837. var customColors = options.colors;
  35838. var positions = [];
  35839. var indices = [];
  35840. var normals = [];
  35841. var uvs = [];
  35842. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  35843. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  35844. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  35845. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  35846. var minlg; // minimal length among all paths from pathArray
  35847. var lg = []; // array of path lengths : nb of vertex per path
  35848. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  35849. var p; // path iterator
  35850. var i; // point iterator
  35851. var j; // point iterator
  35852. // if single path in pathArray
  35853. if (pathArray.length < 2) {
  35854. var ar1 = [];
  35855. var ar2 = [];
  35856. for (i = 0; i < pathArray[0].length - offset; i++) {
  35857. ar1.push(pathArray[0][i]);
  35858. ar2.push(pathArray[0][i + offset]);
  35859. }
  35860. pathArray = [ar1, ar2];
  35861. }
  35862. // positions and horizontal distances (u)
  35863. var idc = 0;
  35864. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  35865. var path;
  35866. var l;
  35867. minlg = pathArray[0].length;
  35868. var vectlg;
  35869. var dist;
  35870. for (p = 0; p < pathArray.length; p++) {
  35871. uTotalDistance[p] = 0;
  35872. us[p] = [0];
  35873. path = pathArray[p];
  35874. l = path.length;
  35875. minlg = (minlg < l) ? minlg : l;
  35876. j = 0;
  35877. while (j < l) {
  35878. positions.push(path[j].x, path[j].y, path[j].z);
  35879. if (j > 0) {
  35880. vectlg = path[j].subtract(path[j - 1]).length();
  35881. dist = vectlg + uTotalDistance[p];
  35882. us[p].push(dist);
  35883. uTotalDistance[p] = dist;
  35884. }
  35885. j++;
  35886. }
  35887. if (closePath) {
  35888. j--;
  35889. positions.push(path[0].x, path[0].y, path[0].z);
  35890. vectlg = path[j].subtract(path[0]).length();
  35891. dist = vectlg + uTotalDistance[p];
  35892. us[p].push(dist);
  35893. uTotalDistance[p] = dist;
  35894. }
  35895. lg[p] = l + closePathCorr;
  35896. idx[p] = idc;
  35897. idc += (l + closePathCorr);
  35898. }
  35899. // vertical distances (v)
  35900. var path1;
  35901. var path2;
  35902. var vertex1 = null;
  35903. var vertex2 = null;
  35904. for (i = 0; i < minlg + closePathCorr; i++) {
  35905. vTotalDistance[i] = 0;
  35906. vs[i] = [0];
  35907. for (p = 0; p < pathArray.length - 1; p++) {
  35908. path1 = pathArray[p];
  35909. path2 = pathArray[p + 1];
  35910. if (i === minlg) {
  35911. vertex1 = path1[0];
  35912. vertex2 = path2[0];
  35913. }
  35914. else {
  35915. vertex1 = path1[i];
  35916. vertex2 = path2[i];
  35917. }
  35918. vectlg = vertex2.subtract(vertex1).length();
  35919. dist = vectlg + vTotalDistance[i];
  35920. vs[i].push(dist);
  35921. vTotalDistance[i] = dist;
  35922. }
  35923. if (closeArray && vertex2 && vertex1) {
  35924. path1 = pathArray[p];
  35925. path2 = pathArray[0];
  35926. if (i === minlg) {
  35927. vertex2 = path2[0];
  35928. }
  35929. vectlg = vertex2.subtract(vertex1).length();
  35930. dist = vectlg + vTotalDistance[i];
  35931. vTotalDistance[i] = dist;
  35932. }
  35933. }
  35934. // uvs
  35935. var u;
  35936. var v;
  35937. if (customUV) {
  35938. for (p = 0; p < customUV.length; p++) {
  35939. uvs.push(customUV[p].x, customUV[p].y);
  35940. }
  35941. }
  35942. else {
  35943. for (p = 0; p < pathArray.length; p++) {
  35944. for (i = 0; i < minlg + closePathCorr; i++) {
  35945. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  35946. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  35947. if (invertUV) {
  35948. uvs.push(v, u);
  35949. }
  35950. else {
  35951. uvs.push(u, v);
  35952. }
  35953. }
  35954. }
  35955. }
  35956. // indices
  35957. p = 0; // path index
  35958. var pi = 0; // positions array index
  35959. var l1 = lg[p] - 1; // path1 length
  35960. var l2 = lg[p + 1] - 1; // path2 length
  35961. var min = (l1 < l2) ? l1 : l2; // current path stop index
  35962. var shft = idx[1] - idx[0]; // shift
  35963. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  35964. while (pi <= min && p < path1nb) {
  35965. // 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
  35966. indices.push(pi, pi + shft, pi + 1);
  35967. indices.push(pi + shft + 1, pi + 1, pi + shft);
  35968. pi += 1;
  35969. if (pi === min) {
  35970. p++;
  35971. if (p === lg.length - 1) {
  35972. shft = idx[0] - idx[p];
  35973. l1 = lg[p] - 1;
  35974. l2 = lg[0] - 1;
  35975. }
  35976. else {
  35977. shft = idx[p + 1] - idx[p];
  35978. l1 = lg[p] - 1;
  35979. l2 = lg[p + 1] - 1;
  35980. }
  35981. pi = idx[p];
  35982. min = (l1 < l2) ? l1 + pi : l2 + pi;
  35983. }
  35984. }
  35985. // normals
  35986. VertexData.ComputeNormals(positions, indices, normals);
  35987. if (closePath) {
  35988. var indexFirst = 0;
  35989. var indexLast = 0;
  35990. for (p = 0; p < pathArray.length; p++) {
  35991. indexFirst = idx[p] * 3;
  35992. if (p + 1 < pathArray.length) {
  35993. indexLast = (idx[p + 1] - 1) * 3;
  35994. }
  35995. else {
  35996. indexLast = normals.length - 3;
  35997. }
  35998. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  35999. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36000. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36001. normals[indexLast] = normals[indexFirst];
  36002. normals[indexLast + 1] = normals[indexFirst + 1];
  36003. normals[indexLast + 2] = normals[indexFirst + 2];
  36004. }
  36005. }
  36006. // sides
  36007. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36008. // Colors
  36009. var colors = null;
  36010. if (customColors) {
  36011. colors = new Float32Array(customColors.length * 4);
  36012. for (var c = 0; c < customColors.length; c++) {
  36013. colors[c * 4] = customColors[c].r;
  36014. colors[c * 4 + 1] = customColors[c].g;
  36015. colors[c * 4 + 2] = customColors[c].b;
  36016. colors[c * 4 + 3] = customColors[c].a;
  36017. }
  36018. }
  36019. // Result
  36020. var vertexData = new VertexData();
  36021. var positions32 = new Float32Array(positions);
  36022. var normals32 = new Float32Array(normals);
  36023. var uvs32 = new Float32Array(uvs);
  36024. vertexData.indices = indices;
  36025. vertexData.positions = positions32;
  36026. vertexData.normals = normals32;
  36027. vertexData.uvs = uvs32;
  36028. if (colors) {
  36029. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36030. }
  36031. if (closePath) {
  36032. vertexData._idx = idx;
  36033. }
  36034. return vertexData;
  36035. };
  36036. /**
  36037. * Creates the VertexData of the Box.
  36038. */
  36039. VertexData.CreateBox = function (options) {
  36040. var normalsSource = [
  36041. new BABYLON.Vector3(0, 0, 1),
  36042. new BABYLON.Vector3(0, 0, -1),
  36043. new BABYLON.Vector3(1, 0, 0),
  36044. new BABYLON.Vector3(-1, 0, 0),
  36045. new BABYLON.Vector3(0, 1, 0),
  36046. new BABYLON.Vector3(0, -1, 0)
  36047. ];
  36048. var indices = [];
  36049. var positions = [];
  36050. var normals = [];
  36051. var uvs = [];
  36052. var width = options.width || options.size || 1;
  36053. var height = options.height || options.size || 1;
  36054. var depth = options.depth || options.size || 1;
  36055. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36056. var faceUV = options.faceUV || new Array(6);
  36057. var faceColors = options.faceColors;
  36058. var colors = [];
  36059. // default face colors and UV if undefined
  36060. for (var f = 0; f < 6; f++) {
  36061. if (faceUV[f] === undefined) {
  36062. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36063. }
  36064. if (faceColors && faceColors[f] === undefined) {
  36065. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36066. }
  36067. }
  36068. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36069. // Create each face in turn.
  36070. for (var index = 0; index < normalsSource.length; index++) {
  36071. var normal = normalsSource[index];
  36072. // Get two vectors perpendicular to the face normal and to each other.
  36073. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36074. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36075. // Six indices (two triangles) per face.
  36076. var verticesLength = positions.length / 3;
  36077. indices.push(verticesLength);
  36078. indices.push(verticesLength + 1);
  36079. indices.push(verticesLength + 2);
  36080. indices.push(verticesLength);
  36081. indices.push(verticesLength + 2);
  36082. indices.push(verticesLength + 3);
  36083. // Four vertices per face.
  36084. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36085. positions.push(vertex.x, vertex.y, vertex.z);
  36086. normals.push(normal.x, normal.y, normal.z);
  36087. uvs.push(faceUV[index].z, faceUV[index].w);
  36088. if (faceColors) {
  36089. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36090. }
  36091. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36092. positions.push(vertex.x, vertex.y, vertex.z);
  36093. normals.push(normal.x, normal.y, normal.z);
  36094. uvs.push(faceUV[index].x, faceUV[index].w);
  36095. if (faceColors) {
  36096. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36097. }
  36098. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36099. positions.push(vertex.x, vertex.y, vertex.z);
  36100. normals.push(normal.x, normal.y, normal.z);
  36101. uvs.push(faceUV[index].x, faceUV[index].y);
  36102. if (faceColors) {
  36103. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36104. }
  36105. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36106. positions.push(vertex.x, vertex.y, vertex.z);
  36107. normals.push(normal.x, normal.y, normal.z);
  36108. uvs.push(faceUV[index].z, faceUV[index].y);
  36109. if (faceColors) {
  36110. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36111. }
  36112. }
  36113. // sides
  36114. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36115. // Result
  36116. var vertexData = new VertexData();
  36117. vertexData.indices = indices;
  36118. vertexData.positions = positions;
  36119. vertexData.normals = normals;
  36120. vertexData.uvs = uvs;
  36121. if (faceColors) {
  36122. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36123. vertexData.colors = totalColors;
  36124. }
  36125. return vertexData;
  36126. };
  36127. /**
  36128. * Creates the VertexData of the Sphere.
  36129. */
  36130. VertexData.CreateSphere = function (options) {
  36131. var segments = options.segments || 32;
  36132. var diameterX = options.diameterX || options.diameter || 1;
  36133. var diameterY = options.diameterY || options.diameter || 1;
  36134. var diameterZ = options.diameterZ || options.diameter || 1;
  36135. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36136. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36137. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36138. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36139. var totalZRotationSteps = 2 + segments;
  36140. var totalYRotationSteps = 2 * totalZRotationSteps;
  36141. var indices = [];
  36142. var positions = [];
  36143. var normals = [];
  36144. var uvs = [];
  36145. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36146. var normalizedZ = zRotationStep / totalZRotationSteps;
  36147. var angleZ = normalizedZ * Math.PI * slice;
  36148. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36149. var normalizedY = yRotationStep / totalYRotationSteps;
  36150. var angleY = normalizedY * Math.PI * 2 * arc;
  36151. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36152. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36153. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36154. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36155. var vertex = complete.multiply(radius);
  36156. var normal = complete.divide(radius).normalize();
  36157. positions.push(vertex.x, vertex.y, vertex.z);
  36158. normals.push(normal.x, normal.y, normal.z);
  36159. uvs.push(normalizedY, normalizedZ);
  36160. }
  36161. if (zRotationStep > 0) {
  36162. var verticesCount = positions.length / 3;
  36163. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36164. indices.push((firstIndex));
  36165. indices.push((firstIndex + 1));
  36166. indices.push(firstIndex + totalYRotationSteps + 1);
  36167. indices.push((firstIndex + totalYRotationSteps + 1));
  36168. indices.push((firstIndex + 1));
  36169. indices.push((firstIndex + totalYRotationSteps + 2));
  36170. }
  36171. }
  36172. }
  36173. // Sides
  36174. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36175. // Result
  36176. var vertexData = new VertexData();
  36177. vertexData.indices = indices;
  36178. vertexData.positions = positions;
  36179. vertexData.normals = normals;
  36180. vertexData.uvs = uvs;
  36181. return vertexData;
  36182. };
  36183. /**
  36184. * Creates the VertexData of the Cylinder or Cone.
  36185. */
  36186. VertexData.CreateCylinder = function (options) {
  36187. var height = options.height || 2;
  36188. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36189. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36190. var tessellation = options.tessellation || 24;
  36191. var subdivisions = options.subdivisions || 1;
  36192. var hasRings = options.hasRings ? true : false;
  36193. var enclose = options.enclose ? true : false;
  36194. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36195. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36196. var faceUV = options.faceUV || new Array(3);
  36197. var faceColors = options.faceColors;
  36198. // default face colors and UV if undefined
  36199. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36200. var ringNb = (hasRings) ? subdivisions : 1;
  36201. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36202. var f;
  36203. for (f = 0; f < surfaceNb; f++) {
  36204. if (faceColors && faceColors[f] === undefined) {
  36205. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36206. }
  36207. }
  36208. for (f = 0; f < surfaceNb; f++) {
  36209. if (faceUV && faceUV[f] === undefined) {
  36210. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36211. }
  36212. }
  36213. var indices = new Array();
  36214. var positions = new Array();
  36215. var normals = new Array();
  36216. var uvs = new Array();
  36217. var colors = new Array();
  36218. var angle_step = Math.PI * 2 * arc / tessellation;
  36219. var angle;
  36220. var h;
  36221. var radius;
  36222. var tan = (diameterBottom - diameterTop) / 2 / height;
  36223. var ringVertex = BABYLON.Vector3.Zero();
  36224. var ringNormal = BABYLON.Vector3.Zero();
  36225. var ringFirstVertex = BABYLON.Vector3.Zero();
  36226. var ringFirstNormal = BABYLON.Vector3.Zero();
  36227. var quadNormal = BABYLON.Vector3.Zero();
  36228. var Y = BABYLON.Axis.Y;
  36229. // positions, normals, uvs
  36230. var i;
  36231. var j;
  36232. var r;
  36233. var ringIdx = 1;
  36234. var s = 1; // surface index
  36235. var cs = 0;
  36236. var v = 0;
  36237. for (i = 0; i <= subdivisions; i++) {
  36238. h = i / subdivisions;
  36239. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36240. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36241. for (r = 0; r < ringIdx; r++) {
  36242. if (hasRings) {
  36243. s += r;
  36244. }
  36245. if (enclose) {
  36246. s += 2 * r;
  36247. }
  36248. for (j = 0; j <= tessellation; j++) {
  36249. angle = j * angle_step;
  36250. // position
  36251. ringVertex.x = Math.cos(-angle) * radius;
  36252. ringVertex.y = -height / 2 + h * height;
  36253. ringVertex.z = Math.sin(-angle) * radius;
  36254. // normal
  36255. if (diameterTop === 0 && i === subdivisions) {
  36256. // if no top cap, reuse former normals
  36257. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36258. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36259. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36260. }
  36261. else {
  36262. ringNormal.x = ringVertex.x;
  36263. ringNormal.z = ringVertex.z;
  36264. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36265. ringNormal.normalize();
  36266. }
  36267. // keep first ring vertex values for enclose
  36268. if (j === 0) {
  36269. ringFirstVertex.copyFrom(ringVertex);
  36270. ringFirstNormal.copyFrom(ringNormal);
  36271. }
  36272. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36273. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36274. if (hasRings) {
  36275. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36276. }
  36277. else {
  36278. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36279. }
  36280. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36281. if (faceColors) {
  36282. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36283. }
  36284. }
  36285. // if enclose, add four vertices and their dedicated normals
  36286. if (arc !== 1 && enclose) {
  36287. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36288. positions.push(0, ringVertex.y, 0);
  36289. positions.push(0, ringVertex.y, 0);
  36290. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36291. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36292. quadNormal.normalize();
  36293. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36294. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36295. quadNormal.normalize();
  36296. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36297. if (hasRings) {
  36298. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36299. }
  36300. else {
  36301. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36302. }
  36303. uvs.push(faceUV[s + 1].x, v);
  36304. uvs.push(faceUV[s + 1].z, v);
  36305. if (hasRings) {
  36306. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36307. }
  36308. else {
  36309. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36310. }
  36311. uvs.push(faceUV[s + 2].x, v);
  36312. uvs.push(faceUV[s + 2].z, v);
  36313. if (faceColors) {
  36314. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36315. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36316. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36317. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36318. }
  36319. }
  36320. if (cs !== s) {
  36321. cs = s;
  36322. }
  36323. }
  36324. }
  36325. // indices
  36326. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36327. var s;
  36328. i = 0;
  36329. for (s = 0; s < subdivisions; s++) {
  36330. var i0 = 0;
  36331. var i1 = 0;
  36332. var i2 = 0;
  36333. var i3 = 0;
  36334. for (j = 0; j < tessellation; j++) {
  36335. i0 = i * (e + 1) + j;
  36336. i1 = (i + 1) * (e + 1) + j;
  36337. i2 = i * (e + 1) + (j + 1);
  36338. i3 = (i + 1) * (e + 1) + (j + 1);
  36339. indices.push(i0, i1, i2);
  36340. indices.push(i3, i2, i1);
  36341. }
  36342. if (arc !== 1 && enclose) {
  36343. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36344. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36345. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36346. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36347. }
  36348. i = (hasRings) ? (i + 2) : (i + 1);
  36349. }
  36350. // Caps
  36351. var createCylinderCap = function (isTop) {
  36352. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36353. if (radius === 0) {
  36354. return;
  36355. }
  36356. // Cap positions, normals & uvs
  36357. var angle;
  36358. var circleVector;
  36359. var i;
  36360. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36361. var c = null;
  36362. if (faceColors) {
  36363. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36364. }
  36365. // cap center
  36366. var vbase = positions.length / 3;
  36367. var offset = isTop ? height / 2 : -height / 2;
  36368. var center = new BABYLON.Vector3(0, offset, 0);
  36369. positions.push(center.x, center.y, center.z);
  36370. normals.push(0, isTop ? 1 : -1, 0);
  36371. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36372. if (c) {
  36373. colors.push(c.r, c.g, c.b, c.a);
  36374. }
  36375. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36376. for (i = 0; i <= tessellation; i++) {
  36377. angle = Math.PI * 2 * i * arc / tessellation;
  36378. var cos = Math.cos(-angle);
  36379. var sin = Math.sin(-angle);
  36380. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36381. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36382. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36383. normals.push(0, isTop ? 1 : -1, 0);
  36384. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36385. if (c) {
  36386. colors.push(c.r, c.g, c.b, c.a);
  36387. }
  36388. }
  36389. // Cap indices
  36390. for (i = 0; i < tessellation; i++) {
  36391. if (!isTop) {
  36392. indices.push(vbase);
  36393. indices.push(vbase + (i + 1));
  36394. indices.push(vbase + (i + 2));
  36395. }
  36396. else {
  36397. indices.push(vbase);
  36398. indices.push(vbase + (i + 2));
  36399. indices.push(vbase + (i + 1));
  36400. }
  36401. }
  36402. };
  36403. // add caps to geometry
  36404. createCylinderCap(false);
  36405. createCylinderCap(true);
  36406. // Sides
  36407. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36408. var vertexData = new VertexData();
  36409. vertexData.indices = indices;
  36410. vertexData.positions = positions;
  36411. vertexData.normals = normals;
  36412. vertexData.uvs = uvs;
  36413. if (faceColors) {
  36414. vertexData.colors = colors;
  36415. }
  36416. return vertexData;
  36417. };
  36418. /**
  36419. * Creates the VertexData of the Torus.
  36420. */
  36421. VertexData.CreateTorus = function (options) {
  36422. var indices = [];
  36423. var positions = [];
  36424. var normals = [];
  36425. var uvs = [];
  36426. var diameter = options.diameter || 1;
  36427. var thickness = options.thickness || 0.5;
  36428. var tessellation = options.tessellation || 16;
  36429. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36430. var stride = tessellation + 1;
  36431. for (var i = 0; i <= tessellation; i++) {
  36432. var u = i / tessellation;
  36433. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36434. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36435. for (var j = 0; j <= tessellation; j++) {
  36436. var v = 1 - j / tessellation;
  36437. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36438. var dx = Math.cos(innerAngle);
  36439. var dy = Math.sin(innerAngle);
  36440. // Create a vertex.
  36441. var normal = new BABYLON.Vector3(dx, dy, 0);
  36442. var position = normal.scale(thickness / 2);
  36443. var textureCoordinate = new BABYLON.Vector2(u, v);
  36444. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36445. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36446. positions.push(position.x, position.y, position.z);
  36447. normals.push(normal.x, normal.y, normal.z);
  36448. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36449. // And create indices for two triangles.
  36450. var nextI = (i + 1) % stride;
  36451. var nextJ = (j + 1) % stride;
  36452. indices.push(i * stride + j);
  36453. indices.push(i * stride + nextJ);
  36454. indices.push(nextI * stride + j);
  36455. indices.push(i * stride + nextJ);
  36456. indices.push(nextI * stride + nextJ);
  36457. indices.push(nextI * stride + j);
  36458. }
  36459. }
  36460. // Sides
  36461. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36462. // Result
  36463. var vertexData = new VertexData();
  36464. vertexData.indices = indices;
  36465. vertexData.positions = positions;
  36466. vertexData.normals = normals;
  36467. vertexData.uvs = uvs;
  36468. return vertexData;
  36469. };
  36470. /**
  36471. * Creates the VertexData of the LineSystem.
  36472. */
  36473. VertexData.CreateLineSystem = function (options) {
  36474. var indices = [];
  36475. var positions = [];
  36476. var lines = options.lines;
  36477. var colors = options.colors;
  36478. var vertexColors = [];
  36479. var idx = 0;
  36480. for (var l = 0; l < lines.length; l++) {
  36481. var points = lines[l];
  36482. for (var index = 0; index < points.length; index++) {
  36483. positions.push(points[index].x, points[index].y, points[index].z);
  36484. if (colors) {
  36485. var color = colors[l];
  36486. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36487. }
  36488. if (index > 0) {
  36489. indices.push(idx - 1);
  36490. indices.push(idx);
  36491. }
  36492. idx++;
  36493. }
  36494. }
  36495. var vertexData = new VertexData();
  36496. vertexData.indices = indices;
  36497. vertexData.positions = positions;
  36498. if (colors) {
  36499. vertexData.colors = vertexColors;
  36500. }
  36501. return vertexData;
  36502. };
  36503. /**
  36504. * Create the VertexData of the DashedLines.
  36505. */
  36506. VertexData.CreateDashedLines = function (options) {
  36507. var dashSize = options.dashSize || 3;
  36508. var gapSize = options.gapSize || 1;
  36509. var dashNb = options.dashNb || 200;
  36510. var points = options.points;
  36511. var positions = new Array();
  36512. var indices = new Array();
  36513. var curvect = BABYLON.Vector3.Zero();
  36514. var lg = 0;
  36515. var nb = 0;
  36516. var shft = 0;
  36517. var dashshft = 0;
  36518. var curshft = 0;
  36519. var idx = 0;
  36520. var i = 0;
  36521. for (i = 0; i < points.length - 1; i++) {
  36522. points[i + 1].subtractToRef(points[i], curvect);
  36523. lg += curvect.length();
  36524. }
  36525. shft = lg / dashNb;
  36526. dashshft = dashSize * shft / (dashSize + gapSize);
  36527. for (i = 0; i < points.length - 1; i++) {
  36528. points[i + 1].subtractToRef(points[i], curvect);
  36529. nb = Math.floor(curvect.length() / shft);
  36530. curvect.normalize();
  36531. for (var j = 0; j < nb; j++) {
  36532. curshft = shft * j;
  36533. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36534. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36535. indices.push(idx, idx + 1);
  36536. idx += 2;
  36537. }
  36538. }
  36539. // Result
  36540. var vertexData = new VertexData();
  36541. vertexData.positions = positions;
  36542. vertexData.indices = indices;
  36543. return vertexData;
  36544. };
  36545. /**
  36546. * Creates the VertexData of the Ground.
  36547. */
  36548. VertexData.CreateGround = function (options) {
  36549. var indices = [];
  36550. var positions = [];
  36551. var normals = [];
  36552. var uvs = [];
  36553. var row, col;
  36554. var width = options.width || 1;
  36555. var height = options.height || 1;
  36556. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36557. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36558. for (row = 0; row <= subdivisionsY; row++) {
  36559. for (col = 0; col <= subdivisionsX; col++) {
  36560. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36561. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36562. positions.push(position.x, position.y, position.z);
  36563. normals.push(normal.x, normal.y, normal.z);
  36564. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36565. }
  36566. }
  36567. for (row = 0; row < subdivisionsY; row++) {
  36568. for (col = 0; col < subdivisionsX; col++) {
  36569. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36570. indices.push(col + 1 + row * (subdivisionsX + 1));
  36571. indices.push(col + row * (subdivisionsX + 1));
  36572. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36573. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36574. indices.push(col + row * (subdivisionsX + 1));
  36575. }
  36576. }
  36577. // Result
  36578. var vertexData = new VertexData();
  36579. vertexData.indices = indices;
  36580. vertexData.positions = positions;
  36581. vertexData.normals = normals;
  36582. vertexData.uvs = uvs;
  36583. return vertexData;
  36584. };
  36585. /**
  36586. * Creates the VertexData of the TiledGround.
  36587. */
  36588. VertexData.CreateTiledGround = function (options) {
  36589. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  36590. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  36591. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  36592. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  36593. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  36594. var precision = options.precision || { w: 1, h: 1 };
  36595. var indices = new Array();
  36596. var positions = new Array();
  36597. var normals = new Array();
  36598. var uvs = new Array();
  36599. var row, col, tileRow, tileCol;
  36600. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  36601. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  36602. precision.w = (precision.w < 1) ? 1 : precision.w;
  36603. precision.h = (precision.h < 1) ? 1 : precision.h;
  36604. var tileSize = {
  36605. 'w': (xmax - xmin) / subdivisions.w,
  36606. 'h': (zmax - zmin) / subdivisions.h
  36607. };
  36608. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  36609. // Indices
  36610. var base = positions.length / 3;
  36611. var rowLength = precision.w + 1;
  36612. for (row = 0; row < precision.h; row++) {
  36613. for (col = 0; col < precision.w; col++) {
  36614. var square = [
  36615. base + col + row * rowLength,
  36616. base + (col + 1) + row * rowLength,
  36617. base + (col + 1) + (row + 1) * rowLength,
  36618. base + col + (row + 1) * rowLength
  36619. ];
  36620. indices.push(square[1]);
  36621. indices.push(square[2]);
  36622. indices.push(square[3]);
  36623. indices.push(square[0]);
  36624. indices.push(square[1]);
  36625. indices.push(square[3]);
  36626. }
  36627. }
  36628. // Position, normals and uvs
  36629. var position = BABYLON.Vector3.Zero();
  36630. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36631. for (row = 0; row <= precision.h; row++) {
  36632. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  36633. for (col = 0; col <= precision.w; col++) {
  36634. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  36635. position.y = 0;
  36636. positions.push(position.x, position.y, position.z);
  36637. normals.push(normal.x, normal.y, normal.z);
  36638. uvs.push(col / precision.w, row / precision.h);
  36639. }
  36640. }
  36641. }
  36642. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  36643. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  36644. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  36645. }
  36646. }
  36647. // Result
  36648. var vertexData = new VertexData();
  36649. vertexData.indices = indices;
  36650. vertexData.positions = positions;
  36651. vertexData.normals = normals;
  36652. vertexData.uvs = uvs;
  36653. return vertexData;
  36654. };
  36655. /**
  36656. * Creates the VertexData of the Ground designed from a heightmap.
  36657. */
  36658. VertexData.CreateGroundFromHeightMap = function (options) {
  36659. var indices = [];
  36660. var positions = [];
  36661. var normals = [];
  36662. var uvs = [];
  36663. var row, col;
  36664. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  36665. // Vertices
  36666. for (row = 0; row <= options.subdivisions; row++) {
  36667. for (col = 0; col <= options.subdivisions; col++) {
  36668. 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));
  36669. // Compute height
  36670. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  36671. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  36672. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  36673. var r = options.buffer[pos] / 255.0;
  36674. var g = options.buffer[pos + 1] / 255.0;
  36675. var b = options.buffer[pos + 2] / 255.0;
  36676. var gradient = r * filter.r + g * filter.g + b * filter.b;
  36677. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  36678. // Add vertex
  36679. positions.push(position.x, position.y, position.z);
  36680. normals.push(0, 0, 0);
  36681. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  36682. }
  36683. }
  36684. // Indices
  36685. for (row = 0; row < options.subdivisions; row++) {
  36686. for (col = 0; col < options.subdivisions; col++) {
  36687. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36688. indices.push(col + 1 + row * (options.subdivisions + 1));
  36689. indices.push(col + row * (options.subdivisions + 1));
  36690. indices.push(col + (row + 1) * (options.subdivisions + 1));
  36691. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  36692. indices.push(col + row * (options.subdivisions + 1));
  36693. }
  36694. }
  36695. // Normals
  36696. VertexData.ComputeNormals(positions, indices, normals);
  36697. // Result
  36698. var vertexData = new VertexData();
  36699. vertexData.indices = indices;
  36700. vertexData.positions = positions;
  36701. vertexData.normals = normals;
  36702. vertexData.uvs = uvs;
  36703. return vertexData;
  36704. };
  36705. /**
  36706. * Creates the VertexData of the Plane.
  36707. */
  36708. VertexData.CreatePlane = function (options) {
  36709. var indices = [];
  36710. var positions = [];
  36711. var normals = [];
  36712. var uvs = [];
  36713. var width = options.width || options.size || 1;
  36714. var height = options.height || options.size || 1;
  36715. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36716. // Vertices
  36717. var halfWidth = width / 2.0;
  36718. var halfHeight = height / 2.0;
  36719. positions.push(-halfWidth, -halfHeight, 0);
  36720. normals.push(0, 0, -1.0);
  36721. uvs.push(0.0, 0.0);
  36722. positions.push(halfWidth, -halfHeight, 0);
  36723. normals.push(0, 0, -1.0);
  36724. uvs.push(1.0, 0.0);
  36725. positions.push(halfWidth, halfHeight, 0);
  36726. normals.push(0, 0, -1.0);
  36727. uvs.push(1.0, 1.0);
  36728. positions.push(-halfWidth, halfHeight, 0);
  36729. normals.push(0, 0, -1.0);
  36730. uvs.push(0.0, 1.0);
  36731. // Indices
  36732. indices.push(0);
  36733. indices.push(1);
  36734. indices.push(2);
  36735. indices.push(0);
  36736. indices.push(2);
  36737. indices.push(3);
  36738. // Sides
  36739. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36740. // Result
  36741. var vertexData = new VertexData();
  36742. vertexData.indices = indices;
  36743. vertexData.positions = positions;
  36744. vertexData.normals = normals;
  36745. vertexData.uvs = uvs;
  36746. return vertexData;
  36747. };
  36748. /**
  36749. * Creates the VertexData of the Disc or regular Polygon.
  36750. */
  36751. VertexData.CreateDisc = function (options) {
  36752. var positions = new Array();
  36753. var indices = new Array();
  36754. var normals = new Array();
  36755. var uvs = new Array();
  36756. var radius = options.radius || 0.5;
  36757. var tessellation = options.tessellation || 64;
  36758. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36759. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36760. // positions and uvs
  36761. positions.push(0, 0, 0); // disc center first
  36762. uvs.push(0.5, 0.5);
  36763. var theta = Math.PI * 2 * arc;
  36764. var step = theta / tessellation;
  36765. for (var a = 0; a < theta; a += step) {
  36766. var x = Math.cos(a);
  36767. var y = Math.sin(a);
  36768. var u = (x + 1) / 2;
  36769. var v = (1 - y) / 2;
  36770. positions.push(radius * x, radius * y, 0);
  36771. uvs.push(u, v);
  36772. }
  36773. if (arc === 1) {
  36774. positions.push(positions[3], positions[4], positions[5]); // close the circle
  36775. uvs.push(uvs[2], uvs[3]);
  36776. }
  36777. //indices
  36778. var vertexNb = positions.length / 3;
  36779. for (var i = 1; i < vertexNb - 1; i++) {
  36780. indices.push(i + 1, 0, i);
  36781. }
  36782. // result
  36783. VertexData.ComputeNormals(positions, indices, normals);
  36784. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36785. var vertexData = new VertexData();
  36786. vertexData.indices = indices;
  36787. vertexData.positions = positions;
  36788. vertexData.normals = normals;
  36789. vertexData.uvs = uvs;
  36790. return vertexData;
  36791. };
  36792. /**
  36793. * Re-creates the VertexData of the Polygon for sideOrientation.
  36794. */
  36795. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  36796. var faceUV = fUV || new Array(3);
  36797. var faceColors = fColors;
  36798. var colors = [];
  36799. // default face colors and UV if undefined
  36800. for (var f = 0; f < 3; f++) {
  36801. if (faceUV[f] === undefined) {
  36802. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36803. }
  36804. if (faceColors && faceColors[f] === undefined) {
  36805. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36806. }
  36807. }
  36808. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36809. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36810. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36811. var indices = polygon.getIndices();
  36812. // set face colours and textures
  36813. var idx = 0;
  36814. var face = 0;
  36815. for (var index = 0; index < normals.length; index += 3) {
  36816. //Edge Face no. 1
  36817. if (Math.abs(normals[index + 1]) < 0.001) {
  36818. face = 1;
  36819. }
  36820. //Top Face no. 0
  36821. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  36822. face = 0;
  36823. }
  36824. //Bottom Face no. 2
  36825. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  36826. face = 2;
  36827. }
  36828. idx = index / 3;
  36829. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  36830. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  36831. if (faceColors) {
  36832. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  36833. }
  36834. }
  36835. // sides
  36836. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  36837. // Result
  36838. var vertexData = new VertexData();
  36839. vertexData.indices = indices;
  36840. vertexData.positions = positions;
  36841. vertexData.normals = normals;
  36842. vertexData.uvs = uvs;
  36843. if (faceColors) {
  36844. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36845. vertexData.colors = totalColors;
  36846. }
  36847. return vertexData;
  36848. };
  36849. /**
  36850. * Creates the VertexData of the IcoSphere.
  36851. */
  36852. VertexData.CreateIcoSphere = function (options) {
  36853. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36854. var radius = options.radius || 1;
  36855. var flat = (options.flat === undefined) ? true : options.flat;
  36856. var subdivisions = options.subdivisions || 4;
  36857. var radiusX = options.radiusX || radius;
  36858. var radiusY = options.radiusY || radius;
  36859. var radiusZ = options.radiusZ || radius;
  36860. var t = (1 + Math.sqrt(5)) / 2;
  36861. // 12 vertex x,y,z
  36862. var ico_vertices = [
  36863. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  36864. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  36865. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  36866. ];
  36867. // index of 3 vertex makes a face of icopshere
  36868. var ico_indices = [
  36869. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  36870. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  36871. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  36872. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  36873. ];
  36874. // vertex for uv have aliased position, not for UV
  36875. var vertices_unalias_id = [
  36876. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  36877. // vertex alias
  36878. 0,
  36879. 2,
  36880. 3,
  36881. 3,
  36882. 3,
  36883. 4,
  36884. 7,
  36885. 8,
  36886. 9,
  36887. 9,
  36888. 10,
  36889. 11 // 23: B + 12
  36890. ];
  36891. // uv as integer step (not pixels !)
  36892. var ico_vertexuv = [
  36893. 5, 1, 3, 1, 6, 4, 0, 0,
  36894. 5, 3, 4, 2, 2, 2, 4, 0,
  36895. 2, 0, 1, 1, 6, 0, 6, 2,
  36896. // vertex alias (for same vertex on different faces)
  36897. 0, 4,
  36898. 3, 3,
  36899. 4, 4,
  36900. 3, 1,
  36901. 4, 2,
  36902. 4, 4,
  36903. 0, 2,
  36904. 1, 1,
  36905. 2, 2,
  36906. 3, 3,
  36907. 1, 3,
  36908. 2, 4 // 23: B + 12
  36909. ];
  36910. // Vertices[0, 1, ...9, A, B] : position on UV plane
  36911. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  36912. // First island of uv mapping
  36913. // v = 4h 3+ 2
  36914. // v = 3h 9+ 4
  36915. // v = 2h 9+ 5 B
  36916. // v = 1h 9 1 0
  36917. // v = 0h 3 8 7 A
  36918. // u = 0 1 2 3 4 5 6 *a
  36919. // Second island of uv mapping
  36920. // v = 4h 0+ B+ 4+
  36921. // v = 3h A+ 2+
  36922. // v = 2h 7+ 6 3+
  36923. // v = 1h 8+ 3+
  36924. // v = 0h
  36925. // u = 0 1 2 3 4 5 6 *a
  36926. // Face layout on texture UV mapping
  36927. // ============
  36928. // \ 4 /\ 16 / ======
  36929. // \ / \ / /\ 11 /
  36930. // \/ 7 \/ / \ /
  36931. // ======= / 10 \/
  36932. // /\ 17 /\ =======
  36933. // / \ / \ \ 15 /\
  36934. // / 8 \/ 12 \ \ / \
  36935. // ============ \/ 6 \
  36936. // \ 18 /\ ============
  36937. // \ / \ \ 5 /\ 0 /
  36938. // \/ 13 \ \ / \ /
  36939. // ======= \/ 1 \/
  36940. // =============
  36941. // /\ 19 /\ 2 /\
  36942. // / \ / \ / \
  36943. // / 14 \/ 9 \/ 3 \
  36944. // ===================
  36945. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  36946. var ustep = 138 / 1024;
  36947. var vstep = 239 / 1024;
  36948. var uoffset = 60 / 1024;
  36949. var voffset = 26 / 1024;
  36950. // Second island should have margin, not to touch the first island
  36951. // avoid any borderline artefact in pixel rounding
  36952. var island_u_offset = -40 / 1024;
  36953. var island_v_offset = +20 / 1024;
  36954. // face is either island 0 or 1 :
  36955. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  36956. var island = [
  36957. 0, 0, 0, 0, 1,
  36958. 0, 0, 1, 1, 0,
  36959. 0, 0, 1, 1, 0,
  36960. 0, 1, 1, 1, 0 // 15 - 19
  36961. ];
  36962. var indices = new Array();
  36963. var positions = new Array();
  36964. var normals = new Array();
  36965. var uvs = new Array();
  36966. var current_indice = 0;
  36967. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  36968. var face_vertex_pos = new Array(3);
  36969. var face_vertex_uv = new Array(3);
  36970. var v012;
  36971. for (v012 = 0; v012 < 3; v012++) {
  36972. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  36973. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  36974. }
  36975. // create all with normals
  36976. for (var face = 0; face < 20; face++) {
  36977. // 3 vertex per face
  36978. for (v012 = 0; v012 < 3; v012++) {
  36979. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  36980. var v_id = ico_indices[3 * face + v012];
  36981. // vertex have 3D position (x,y,z)
  36982. 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]);
  36983. // Normalize to get normal, then scale to radius
  36984. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  36985. // uv Coordinates from vertex ID
  36986. 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);
  36987. }
  36988. // Subdivide the face (interpolate pos, norm, uv)
  36989. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  36990. // - norm is linear interpolation of vertex corner normal
  36991. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  36992. // - uv is linear interpolation
  36993. //
  36994. // Topology is as below for sub-divide by 2
  36995. // vertex shown as v0,v1,v2
  36996. // interp index is i1 to progress in range [v0,v1[
  36997. // interp index is i2 to progress in range [v0,v2[
  36998. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  36999. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37000. //
  37001. //
  37002. // i2 v2
  37003. // ^ ^
  37004. // / / \
  37005. // / / \
  37006. // / / \
  37007. // / / (0,1) \
  37008. // / #---------\
  37009. // / / \ (0,0)'/ \
  37010. // / / \ / \
  37011. // / / \ / \
  37012. // / / (0,0) \ / (1,0) \
  37013. // / #---------#---------\
  37014. // v0 v1
  37015. //
  37016. // --------------------> i1
  37017. //
  37018. // interp of (i1,i2):
  37019. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37020. // along i1 : lerp(x0,x1, i1/(S-i2))
  37021. //
  37022. // centroid of triangle is needed to get help normal computation
  37023. // (c1,c2) are used for centroid location
  37024. var interp_vertex = function (i1, i2, c1, c2) {
  37025. // vertex is interpolated from
  37026. // - face_vertex_pos[0..2]
  37027. // - face_vertex_uv[0..2]
  37028. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37029. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37030. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37031. pos_interp.normalize();
  37032. var vertex_normal;
  37033. if (flat) {
  37034. // in flat mode, recalculate normal as face centroid normal
  37035. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37036. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37037. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37038. }
  37039. else {
  37040. // in smooth mode, recalculate normal from each single vertex position
  37041. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37042. }
  37043. // Vertex normal need correction due to X,Y,Z radius scaling
  37044. vertex_normal.x /= radiusX;
  37045. vertex_normal.y /= radiusY;
  37046. vertex_normal.z /= radiusZ;
  37047. vertex_normal.normalize();
  37048. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37049. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37050. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37051. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37052. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37053. uvs.push(uv_interp.x, uv_interp.y);
  37054. // push each vertex has member of a face
  37055. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37056. indices.push(current_indice);
  37057. current_indice++;
  37058. };
  37059. for (var i2 = 0; i2 < subdivisions; i2++) {
  37060. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37061. // face : (i1,i2) for /\ :
  37062. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37063. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37064. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37065. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37066. if (i1 + i2 + 1 < subdivisions) {
  37067. // face : (i1,i2)' for \/ :
  37068. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37069. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37070. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37071. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37072. }
  37073. }
  37074. }
  37075. }
  37076. // Sides
  37077. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37078. // Result
  37079. var vertexData = new VertexData();
  37080. vertexData.indices = indices;
  37081. vertexData.positions = positions;
  37082. vertexData.normals = normals;
  37083. vertexData.uvs = uvs;
  37084. return vertexData;
  37085. };
  37086. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37087. /**
  37088. * Creates the VertexData of the Polyhedron.
  37089. */
  37090. VertexData.CreatePolyhedron = function (options) {
  37091. // provided polyhedron types :
  37092. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37093. // 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)
  37094. var polyhedra = [];
  37095. 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]] };
  37096. 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]] };
  37097. polyhedra[2] = {
  37098. 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]],
  37099. 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]]
  37100. };
  37101. polyhedra[3] = {
  37102. 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]],
  37103. 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]]
  37104. };
  37105. polyhedra[4] = {
  37106. 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]],
  37107. 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]]
  37108. };
  37109. 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]] };
  37110. 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]] };
  37111. 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]] };
  37112. 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]] };
  37113. 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]] };
  37114. 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]] };
  37115. 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]] };
  37116. 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]] };
  37117. 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]] };
  37118. polyhedra[14] = {
  37119. 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]],
  37120. 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]]
  37121. };
  37122. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37123. var size = options.size;
  37124. var sizeX = options.sizeX || size || 1;
  37125. var sizeY = options.sizeY || size || 1;
  37126. var sizeZ = options.sizeZ || size || 1;
  37127. var data = options.custom || polyhedra[type];
  37128. var nbfaces = data.face.length;
  37129. var faceUV = options.faceUV || new Array(nbfaces);
  37130. var faceColors = options.faceColors;
  37131. var flat = (options.flat === undefined) ? true : options.flat;
  37132. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37133. var positions = new Array();
  37134. var indices = new Array();
  37135. var normals = new Array();
  37136. var uvs = new Array();
  37137. var colors = new Array();
  37138. var index = 0;
  37139. var faceIdx = 0; // face cursor in the array "indexes"
  37140. var indexes = new Array();
  37141. var i = 0;
  37142. var f = 0;
  37143. var u, v, ang, x, y, tmp;
  37144. // default face colors and UV if undefined
  37145. if (flat) {
  37146. for (f = 0; f < nbfaces; f++) {
  37147. if (faceColors && faceColors[f] === undefined) {
  37148. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37149. }
  37150. if (faceUV && faceUV[f] === undefined) {
  37151. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37152. }
  37153. }
  37154. }
  37155. if (!flat) {
  37156. for (i = 0; i < data.vertex.length; i++) {
  37157. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37158. uvs.push(0, 0);
  37159. }
  37160. for (f = 0; f < nbfaces; f++) {
  37161. for (i = 0; i < data.face[f].length - 2; i++) {
  37162. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37163. }
  37164. }
  37165. }
  37166. else {
  37167. for (f = 0; f < nbfaces; f++) {
  37168. var fl = data.face[f].length; // number of vertices of the current face
  37169. ang = 2 * Math.PI / fl;
  37170. x = 0.5 * Math.tan(ang / 2);
  37171. y = 0.5;
  37172. // positions, uvs, colors
  37173. for (i = 0; i < fl; i++) {
  37174. // positions
  37175. 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);
  37176. indexes.push(index);
  37177. index++;
  37178. // uvs
  37179. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37180. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37181. uvs.push(u, v);
  37182. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37183. y = x * Math.sin(ang) + y * Math.cos(ang);
  37184. x = tmp;
  37185. // colors
  37186. if (faceColors) {
  37187. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37188. }
  37189. }
  37190. // indices from indexes
  37191. for (i = 0; i < fl - 2; i++) {
  37192. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37193. }
  37194. faceIdx += fl;
  37195. }
  37196. }
  37197. VertexData.ComputeNormals(positions, indices, normals);
  37198. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37199. var vertexData = new VertexData();
  37200. vertexData.positions = positions;
  37201. vertexData.indices = indices;
  37202. vertexData.normals = normals;
  37203. vertexData.uvs = uvs;
  37204. if (faceColors && flat) {
  37205. vertexData.colors = colors;
  37206. }
  37207. return vertexData;
  37208. };
  37209. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37210. /**
  37211. * Creates the VertexData of the Torus Knot.
  37212. */
  37213. VertexData.CreateTorusKnot = function (options) {
  37214. var indices = new Array();
  37215. var positions = new Array();
  37216. var normals = new Array();
  37217. var uvs = new Array();
  37218. var radius = options.radius || 2;
  37219. var tube = options.tube || 0.5;
  37220. var radialSegments = options.radialSegments || 32;
  37221. var tubularSegments = options.tubularSegments || 32;
  37222. var p = options.p || 2;
  37223. var q = options.q || 3;
  37224. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37225. // Helper
  37226. var getPos = function (angle) {
  37227. var cu = Math.cos(angle);
  37228. var su = Math.sin(angle);
  37229. var quOverP = q / p * angle;
  37230. var cs = Math.cos(quOverP);
  37231. var tx = radius * (2 + cs) * 0.5 * cu;
  37232. var ty = radius * (2 + cs) * su * 0.5;
  37233. var tz = radius * Math.sin(quOverP) * 0.5;
  37234. return new BABYLON.Vector3(tx, ty, tz);
  37235. };
  37236. // Vertices
  37237. var i;
  37238. var j;
  37239. for (i = 0; i <= radialSegments; i++) {
  37240. var modI = i % radialSegments;
  37241. var u = modI / radialSegments * 2 * p * Math.PI;
  37242. var p1 = getPos(u);
  37243. var p2 = getPos(u + 0.01);
  37244. var tang = p2.subtract(p1);
  37245. var n = p2.add(p1);
  37246. var bitan = BABYLON.Vector3.Cross(tang, n);
  37247. n = BABYLON.Vector3.Cross(bitan, tang);
  37248. bitan.normalize();
  37249. n.normalize();
  37250. for (j = 0; j < tubularSegments; j++) {
  37251. var modJ = j % tubularSegments;
  37252. var v = modJ / tubularSegments * 2 * Math.PI;
  37253. var cx = -tube * Math.cos(v);
  37254. var cy = tube * Math.sin(v);
  37255. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37256. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37257. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37258. uvs.push(i / radialSegments);
  37259. uvs.push(j / tubularSegments);
  37260. }
  37261. }
  37262. for (i = 0; i < radialSegments; i++) {
  37263. for (j = 0; j < tubularSegments; j++) {
  37264. var jNext = (j + 1) % tubularSegments;
  37265. var a = i * tubularSegments + j;
  37266. var b = (i + 1) * tubularSegments + j;
  37267. var c = (i + 1) * tubularSegments + jNext;
  37268. var d = i * tubularSegments + jNext;
  37269. indices.push(d);
  37270. indices.push(b);
  37271. indices.push(a);
  37272. indices.push(d);
  37273. indices.push(c);
  37274. indices.push(b);
  37275. }
  37276. }
  37277. // Normals
  37278. VertexData.ComputeNormals(positions, indices, normals);
  37279. // Sides
  37280. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37281. // Result
  37282. var vertexData = new VertexData();
  37283. vertexData.indices = indices;
  37284. vertexData.positions = positions;
  37285. vertexData.normals = normals;
  37286. vertexData.uvs = uvs;
  37287. return vertexData;
  37288. };
  37289. // Tools
  37290. /**
  37291. * @param {any} - positions (number[] or Float32Array)
  37292. * @param {any} - indices (number[] or Uint16Array)
  37293. * @param {any} - normals (number[] or Float32Array)
  37294. * options (optional) :
  37295. * facetPositions : optional array of facet positions (vector3)
  37296. * facetNormals : optional array of facet normals (vector3)
  37297. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37298. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37299. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37300. * bbSize : optional bounding box size data, required for facetPartitioning computation
  37301. * bInfo : optional bounding info, required for facetPartitioning computation
  37302. * useRightHandedSystem: optional boolean to for right handed system computation
  37303. * depthSort : optional boolean to enable the facet depth sort computation
  37304. * distanceTo : optional Vector3 to compute the facet depth from this location
  37305. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37306. */
  37307. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37308. // temporary scalar variables
  37309. var index = 0; // facet index
  37310. var p1p2x = 0.0; // p1p2 vector x coordinate
  37311. var p1p2y = 0.0; // p1p2 vector y coordinate
  37312. var p1p2z = 0.0; // p1p2 vector z coordinate
  37313. var p3p2x = 0.0; // p3p2 vector x coordinate
  37314. var p3p2y = 0.0; // p3p2 vector y coordinate
  37315. var p3p2z = 0.0; // p3p2 vector z coordinate
  37316. var faceNormalx = 0.0; // facet normal x coordinate
  37317. var faceNormaly = 0.0; // facet normal y coordinate
  37318. var faceNormalz = 0.0; // facet normal z coordinate
  37319. var length = 0.0; // facet normal length before normalization
  37320. var v1x = 0; // vector1 x index in the positions array
  37321. var v1y = 0; // vector1 y index in the positions array
  37322. var v1z = 0; // vector1 z index in the positions array
  37323. var v2x = 0; // vector2 x index in the positions array
  37324. var v2y = 0; // vector2 y index in the positions array
  37325. var v2z = 0; // vector2 z index in the positions array
  37326. var v3x = 0; // vector3 x index in the positions array
  37327. var v3y = 0; // vector3 y index in the positions array
  37328. var v3z = 0; // vector3 z index in the positions array
  37329. var computeFacetNormals = false;
  37330. var computeFacetPositions = false;
  37331. var computeFacetPartitioning = false;
  37332. var computeDepthSort = false;
  37333. var faceNormalSign = 1;
  37334. var ratio = 0;
  37335. var distanceTo = null;
  37336. if (options) {
  37337. computeFacetNormals = (options.facetNormals) ? true : false;
  37338. computeFacetPositions = (options.facetPositions) ? true : false;
  37339. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37340. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37341. ratio = options.ratio || 0;
  37342. computeDepthSort = (options.depthSort) ? true : false;
  37343. distanceTo = (options.distanceTo);
  37344. if (computeDepthSort) {
  37345. if (distanceTo === undefined) {
  37346. distanceTo = BABYLON.Vector3.Zero();
  37347. }
  37348. var depthSortedFacets = options.depthSortedFacets;
  37349. }
  37350. }
  37351. // facetPartitioning reinit if needed
  37352. var xSubRatio = 0;
  37353. var ySubRatio = 0;
  37354. var zSubRatio = 0;
  37355. var subSq = 0;
  37356. if (computeFacetPartitioning && options && options.bbSize) {
  37357. var ox = 0; // X partitioning index for facet position
  37358. var oy = 0; // Y partinioning index for facet position
  37359. var oz = 0; // Z partinioning index for facet position
  37360. var b1x = 0; // X partitioning index for facet v1 vertex
  37361. var b1y = 0; // Y partitioning index for facet v1 vertex
  37362. var b1z = 0; // z partitioning index for facet v1 vertex
  37363. var b2x = 0; // X partitioning index for facet v2 vertex
  37364. var b2y = 0; // Y partitioning index for facet v2 vertex
  37365. var b2z = 0; // Z partitioning index for facet v2 vertex
  37366. var b3x = 0; // X partitioning index for facet v3 vertex
  37367. var b3y = 0; // Y partitioning index for facet v3 vertex
  37368. var b3z = 0; // Z partitioning index for facet v3 vertex
  37369. var block_idx_o = 0; // facet barycenter block index
  37370. var block_idx_v1 = 0; // v1 vertex block index
  37371. var block_idx_v2 = 0; // v2 vertex block index
  37372. var block_idx_v3 = 0; // v3 vertex block index
  37373. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37374. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37375. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37376. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37377. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37378. subSq = options.subDiv.max * options.subDiv.max;
  37379. options.facetPartitioning.length = 0;
  37380. }
  37381. // reset the normals
  37382. for (index = 0; index < positions.length; index++) {
  37383. normals[index] = 0.0;
  37384. }
  37385. // Loop : 1 indice triplet = 1 facet
  37386. var nbFaces = (indices.length / 3) | 0;
  37387. for (index = 0; index < nbFaces; index++) {
  37388. // get the indexes of the coordinates of each vertex of the facet
  37389. v1x = indices[index * 3] * 3;
  37390. v1y = v1x + 1;
  37391. v1z = v1x + 2;
  37392. v2x = indices[index * 3 + 1] * 3;
  37393. v2y = v2x + 1;
  37394. v2z = v2x + 2;
  37395. v3x = indices[index * 3 + 2] * 3;
  37396. v3y = v3x + 1;
  37397. v3z = v3x + 2;
  37398. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37399. p1p2y = positions[v1y] - positions[v2y];
  37400. p1p2z = positions[v1z] - positions[v2z];
  37401. p3p2x = positions[v3x] - positions[v2x];
  37402. p3p2y = positions[v3y] - positions[v2y];
  37403. p3p2z = positions[v3z] - positions[v2z];
  37404. // compute the face normal with the cross product
  37405. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37406. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37407. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37408. // normalize this normal and store it in the array facetData
  37409. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37410. length = (length === 0) ? 1.0 : length;
  37411. faceNormalx /= length;
  37412. faceNormaly /= length;
  37413. faceNormalz /= length;
  37414. if (computeFacetNormals && options) {
  37415. options.facetNormals[index].x = faceNormalx;
  37416. options.facetNormals[index].y = faceNormaly;
  37417. options.facetNormals[index].z = faceNormalz;
  37418. }
  37419. if (computeFacetPositions && options) {
  37420. // compute and the facet barycenter coordinates in the array facetPositions
  37421. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37422. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37423. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37424. }
  37425. if (computeFacetPartitioning && options) {
  37426. // store the facet indexes in arrays in the main facetPartitioning array :
  37427. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37428. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37429. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37430. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37431. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37432. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37433. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37434. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37435. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37436. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37437. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37438. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37439. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37440. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37441. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37442. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37443. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37444. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37445. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37446. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37447. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37448. // push each facet index in each block containing the vertex
  37449. options.facetPartitioning[block_idx_v1].push(index);
  37450. if (block_idx_v2 != block_idx_v1) {
  37451. options.facetPartitioning[block_idx_v2].push(index);
  37452. }
  37453. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37454. options.facetPartitioning[block_idx_v3].push(index);
  37455. }
  37456. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37457. options.facetPartitioning[block_idx_o].push(index);
  37458. }
  37459. }
  37460. if (computeDepthSort && options && options.facetPositions) {
  37461. var dsf = depthSortedFacets[index];
  37462. dsf.ind = index * 3;
  37463. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37464. }
  37465. // compute the normals anyway
  37466. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37467. normals[v1y] += faceNormaly;
  37468. normals[v1z] += faceNormalz;
  37469. normals[v2x] += faceNormalx;
  37470. normals[v2y] += faceNormaly;
  37471. normals[v2z] += faceNormalz;
  37472. normals[v3x] += faceNormalx;
  37473. normals[v3y] += faceNormaly;
  37474. normals[v3z] += faceNormalz;
  37475. }
  37476. // last normalization of each normal
  37477. for (index = 0; index < normals.length / 3; index++) {
  37478. faceNormalx = normals[index * 3];
  37479. faceNormaly = normals[index * 3 + 1];
  37480. faceNormalz = normals[index * 3 + 2];
  37481. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37482. length = (length === 0) ? 1.0 : length;
  37483. faceNormalx /= length;
  37484. faceNormaly /= length;
  37485. faceNormalz /= length;
  37486. normals[index * 3] = faceNormalx;
  37487. normals[index * 3 + 1] = faceNormaly;
  37488. normals[index * 3 + 2] = faceNormalz;
  37489. }
  37490. };
  37491. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37492. var li = indices.length;
  37493. var ln = normals.length;
  37494. var i;
  37495. var n;
  37496. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37497. switch (sideOrientation) {
  37498. case BABYLON.Mesh.FRONTSIDE:
  37499. // nothing changed
  37500. break;
  37501. case BABYLON.Mesh.BACKSIDE:
  37502. var tmp;
  37503. // indices
  37504. for (i = 0; i < li; i += 3) {
  37505. tmp = indices[i];
  37506. indices[i] = indices[i + 2];
  37507. indices[i + 2] = tmp;
  37508. }
  37509. // normals
  37510. for (n = 0; n < ln; n++) {
  37511. normals[n] = -normals[n];
  37512. }
  37513. break;
  37514. case BABYLON.Mesh.DOUBLESIDE:
  37515. // positions
  37516. var lp = positions.length;
  37517. var l = lp / 3;
  37518. for (var p = 0; p < lp; p++) {
  37519. positions[lp + p] = positions[p];
  37520. }
  37521. // indices
  37522. for (i = 0; i < li; i += 3) {
  37523. indices[i + li] = indices[i + 2] + l;
  37524. indices[i + 1 + li] = indices[i + 1] + l;
  37525. indices[i + 2 + li] = indices[i] + l;
  37526. }
  37527. // normals
  37528. for (n = 0; n < ln; n++) {
  37529. normals[ln + n] = -normals[n];
  37530. }
  37531. // uvs
  37532. var lu = uvs.length;
  37533. var u = 0;
  37534. for (u = 0; u < lu; u++) {
  37535. uvs[u + lu] = uvs[u];
  37536. }
  37537. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37538. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  37539. u = 0;
  37540. for (i = 0; i < lu / 2; i++) {
  37541. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  37542. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  37543. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  37544. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  37545. u += 2;
  37546. }
  37547. break;
  37548. }
  37549. };
  37550. /**
  37551. * Creates a new VertexData from the imported parameters.
  37552. */
  37553. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  37554. var vertexData = new VertexData();
  37555. // positions
  37556. var positions = parsedVertexData.positions;
  37557. if (positions) {
  37558. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  37559. }
  37560. // normals
  37561. var normals = parsedVertexData.normals;
  37562. if (normals) {
  37563. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  37564. }
  37565. // tangents
  37566. var tangents = parsedVertexData.tangents;
  37567. if (tangents) {
  37568. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  37569. }
  37570. // uvs
  37571. var uvs = parsedVertexData.uvs;
  37572. if (uvs) {
  37573. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  37574. }
  37575. // uv2s
  37576. var uv2s = parsedVertexData.uv2s;
  37577. if (uv2s) {
  37578. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  37579. }
  37580. // uv3s
  37581. var uv3s = parsedVertexData.uv3s;
  37582. if (uv3s) {
  37583. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  37584. }
  37585. // uv4s
  37586. var uv4s = parsedVertexData.uv4s;
  37587. if (uv4s) {
  37588. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  37589. }
  37590. // uv5s
  37591. var uv5s = parsedVertexData.uv5s;
  37592. if (uv5s) {
  37593. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  37594. }
  37595. // uv6s
  37596. var uv6s = parsedVertexData.uv6s;
  37597. if (uv6s) {
  37598. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  37599. }
  37600. // colors
  37601. var colors = parsedVertexData.colors;
  37602. if (colors) {
  37603. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  37604. }
  37605. // matricesIndices
  37606. var matricesIndices = parsedVertexData.matricesIndices;
  37607. if (matricesIndices) {
  37608. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  37609. }
  37610. // matricesWeights
  37611. var matricesWeights = parsedVertexData.matricesWeights;
  37612. if (matricesWeights) {
  37613. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  37614. }
  37615. // indices
  37616. var indices = parsedVertexData.indices;
  37617. if (indices) {
  37618. vertexData.indices = indices;
  37619. }
  37620. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  37621. };
  37622. return VertexData;
  37623. }());
  37624. BABYLON.VertexData = VertexData;
  37625. })(BABYLON || (BABYLON = {}));
  37626. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  37627. "use strict";
  37628. var BABYLON;
  37629. (function (BABYLON) {
  37630. /**
  37631. * Class used to store geometry data (vertex buffers + index buffer)
  37632. */
  37633. var Geometry = /** @class */ (function () {
  37634. /**
  37635. * Creates a new geometry
  37636. * @param id defines the unique ID
  37637. * @param scene defines the hosting scene
  37638. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  37639. * @param updatable defines if geometry must be updatable (false by default)
  37640. * @param mesh defines the mesh that will be associated with the geometry
  37641. */
  37642. function Geometry(id, scene, vertexData, updatable, mesh) {
  37643. if (updatable === void 0) { updatable = false; }
  37644. if (mesh === void 0) { mesh = null; }
  37645. /**
  37646. * Gets the delay loading state of the geometry (none by default which means not delayed)
  37647. */
  37648. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37649. this._totalVertices = 0;
  37650. this._isDisposed = false;
  37651. this._indexBufferIsUpdatable = false;
  37652. this.id = id;
  37653. this._engine = scene.getEngine();
  37654. this._meshes = [];
  37655. this._scene = scene;
  37656. //Init vertex buffer cache
  37657. this._vertexBuffers = {};
  37658. this._indices = [];
  37659. this._updatable = updatable;
  37660. // vertexData
  37661. if (vertexData) {
  37662. this.setAllVerticesData(vertexData, updatable);
  37663. }
  37664. else {
  37665. this._totalVertices = 0;
  37666. this._indices = [];
  37667. }
  37668. if (this._engine.getCaps().vertexArrayObject) {
  37669. this._vertexArrayObjects = {};
  37670. }
  37671. // applyToMesh
  37672. if (mesh) {
  37673. if (mesh.getClassName() === "LinesMesh") {
  37674. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37675. this._updateExtend();
  37676. }
  37677. this.applyToMesh(mesh);
  37678. mesh.computeWorldMatrix(true);
  37679. }
  37680. }
  37681. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37682. /**
  37683. * 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
  37684. */
  37685. get: function () {
  37686. return this._boundingBias;
  37687. },
  37688. /**
  37689. * 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
  37690. */
  37691. set: function (value) {
  37692. if (this._boundingBias && this._boundingBias.equals(value)) {
  37693. return;
  37694. }
  37695. this._boundingBias = value.clone();
  37696. this._updateBoundingInfo(true, null);
  37697. },
  37698. enumerable: true,
  37699. configurable: true
  37700. });
  37701. /**
  37702. * Static function used to attach a new empty geometry to a mesh
  37703. * @param mesh defines the mesh to attach the geometry to
  37704. * @returns the new {BABYLON.Geometry}
  37705. */
  37706. Geometry.CreateGeometryForMesh = function (mesh) {
  37707. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  37708. geometry.applyToMesh(mesh);
  37709. return geometry;
  37710. };
  37711. Object.defineProperty(Geometry.prototype, "extend", {
  37712. /**
  37713. * Gets the current extend of the geometry
  37714. */
  37715. get: function () {
  37716. return this._extend;
  37717. },
  37718. enumerable: true,
  37719. configurable: true
  37720. });
  37721. /**
  37722. * Gets the hosting scene
  37723. * @returns the hosting {BABYLON.Scene}
  37724. */
  37725. Geometry.prototype.getScene = function () {
  37726. return this._scene;
  37727. };
  37728. /**
  37729. * Gets the hosting engine
  37730. * @returns the hosting {BABYLON.Engine}
  37731. */
  37732. Geometry.prototype.getEngine = function () {
  37733. return this._engine;
  37734. };
  37735. /**
  37736. * Defines if the geometry is ready to use
  37737. * @returns true if the geometry is ready to be used
  37738. */
  37739. Geometry.prototype.isReady = function () {
  37740. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37741. };
  37742. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37743. /**
  37744. * Gets a value indicating that the geometry should not be serialized
  37745. */
  37746. get: function () {
  37747. for (var index = 0; index < this._meshes.length; index++) {
  37748. if (!this._meshes[index].doNotSerialize) {
  37749. return false;
  37750. }
  37751. }
  37752. return true;
  37753. },
  37754. enumerable: true,
  37755. configurable: true
  37756. });
  37757. /** @ignore */
  37758. Geometry.prototype._rebuild = function () {
  37759. if (this._vertexArrayObjects) {
  37760. this._vertexArrayObjects = {};
  37761. }
  37762. // Index buffer
  37763. if (this._meshes.length !== 0 && this._indices) {
  37764. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37765. }
  37766. // Vertex buffers
  37767. for (var key in this._vertexBuffers) {
  37768. var vertexBuffer = this._vertexBuffers[key];
  37769. vertexBuffer._rebuild();
  37770. }
  37771. };
  37772. /**
  37773. * Affects all gemetry data in one call
  37774. * @param vertexData defines the geometry data
  37775. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  37776. */
  37777. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37778. vertexData.applyToGeometry(this, updatable);
  37779. this.notifyUpdate();
  37780. };
  37781. /**
  37782. * Set specific vertex data
  37783. * @param kind defines the data kind (Position, normal, etc...)
  37784. * @param data defines the vertex data to use
  37785. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  37786. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  37787. */
  37788. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37789. if (updatable === void 0) { updatable = false; }
  37790. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37791. this._totalVertices = data.length / (stride || 3);
  37792. }
  37793. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37794. this.setVerticesBuffer(buffer);
  37795. };
  37796. /**
  37797. * Removes a specific vertex data
  37798. * @param kind defines the data kind (Position, normal, etc...)
  37799. */
  37800. Geometry.prototype.removeVerticesData = function (kind) {
  37801. if (this._vertexBuffers[kind]) {
  37802. this._vertexBuffers[kind].dispose();
  37803. delete this._vertexBuffers[kind];
  37804. }
  37805. };
  37806. /**
  37807. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  37808. * @param buffer defines the vertex buffer to use
  37809. * @param totalVertices defines the total number of vertices for position kind (could be null)
  37810. */
  37811. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  37812. if (totalVertices === void 0) { totalVertices = null; }
  37813. var kind = buffer.getKind();
  37814. if (this._vertexBuffers[kind]) {
  37815. this._vertexBuffers[kind].dispose();
  37816. }
  37817. this._vertexBuffers[kind] = buffer;
  37818. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37819. if (totalVertices != null) {
  37820. this._totalVertices = totalVertices;
  37821. }
  37822. this._updateExtend();
  37823. this._resetPointsArrayCache();
  37824. var meshes = this._meshes;
  37825. var numOfMeshes = meshes.length;
  37826. for (var index = 0; index < numOfMeshes; index++) {
  37827. var mesh = meshes[index];
  37828. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37829. mesh._createGlobalSubMesh(false);
  37830. mesh.computeWorldMatrix(true);
  37831. }
  37832. }
  37833. this.notifyUpdate(kind);
  37834. if (this._vertexArrayObjects) {
  37835. this._disposeVertexArrayObjects();
  37836. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  37837. }
  37838. };
  37839. /**
  37840. * Update a specific vertex buffer
  37841. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  37842. * It will do nothing if the buffer is not updatable
  37843. * @param kind defines the data kind (Position, normal, etc...)
  37844. * @param data defines the data to use
  37845. * @param offset defines the offset in the target buffer where to store the data
  37846. */
  37847. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  37848. var vertexBuffer = this.getVertexBuffer(kind);
  37849. if (!vertexBuffer) {
  37850. return;
  37851. }
  37852. vertexBuffer.updateDirectly(data, offset);
  37853. this.notifyUpdate(kind);
  37854. };
  37855. /**
  37856. * Update a specific vertex buffer
  37857. * This function will create a new buffer if the current one is not updatable
  37858. * @param kind defines the data kind (Position, normal, etc...)
  37859. * @param data defines the data to use
  37860. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  37861. */
  37862. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  37863. if (updateExtends === void 0) { updateExtends = false; }
  37864. var vertexBuffer = this.getVertexBuffer(kind);
  37865. if (!vertexBuffer) {
  37866. return;
  37867. }
  37868. vertexBuffer.update(data);
  37869. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37870. this._updateBoundingInfo(updateExtends, data);
  37871. }
  37872. this.notifyUpdate(kind);
  37873. };
  37874. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  37875. if (updateExtends) {
  37876. this._updateExtend(data);
  37877. }
  37878. var meshes = this._meshes;
  37879. var numOfMeshes = meshes.length;
  37880. this._resetPointsArrayCache();
  37881. for (var index = 0; index < numOfMeshes; index++) {
  37882. var mesh = meshes[index];
  37883. if (updateExtends) {
  37884. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37885. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37886. var subMesh = mesh.subMeshes[subIndex];
  37887. subMesh.refreshBoundingInfo();
  37888. }
  37889. }
  37890. }
  37891. };
  37892. /** @ignore */
  37893. Geometry.prototype._bind = function (effect, indexToBind) {
  37894. if (!effect) {
  37895. return;
  37896. }
  37897. if (indexToBind === undefined) {
  37898. indexToBind = this._indexBuffer;
  37899. }
  37900. var vbs = this.getVertexBuffers();
  37901. if (!vbs) {
  37902. return;
  37903. }
  37904. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  37905. this._engine.bindBuffers(vbs, indexToBind, effect);
  37906. return;
  37907. }
  37908. // Using VAO
  37909. if (!this._vertexArrayObjects[effect.key]) {
  37910. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  37911. }
  37912. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  37913. };
  37914. /**
  37915. * Gets total number of vertices
  37916. * @returns the total number of vertices
  37917. */
  37918. Geometry.prototype.getTotalVertices = function () {
  37919. if (!this.isReady()) {
  37920. return 0;
  37921. }
  37922. return this._totalVertices;
  37923. };
  37924. /**
  37925. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  37926. * @param kind defines the data kind (Position, normal, etc...)
  37927. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  37928. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  37929. * @returns a float array containing vertex data
  37930. */
  37931. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  37932. var vertexBuffer = this.getVertexBuffer(kind);
  37933. if (!vertexBuffer) {
  37934. return null;
  37935. }
  37936. var data = vertexBuffer.getData();
  37937. if (!data) {
  37938. return null;
  37939. }
  37940. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  37941. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  37942. var count = this._totalVertices * defaultStride;
  37943. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  37944. var copy_1 = new Array(count);
  37945. vertexBuffer.forEach(count, function (value, index) {
  37946. copy_1[index] = value;
  37947. });
  37948. return copy_1;
  37949. }
  37950. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  37951. if (data instanceof Array) {
  37952. var offset = vertexBuffer.byteOffset / 4;
  37953. return BABYLON.Tools.Slice(data, offset, offset + count);
  37954. }
  37955. else if (data instanceof ArrayBuffer) {
  37956. return new Float32Array(data, vertexBuffer.byteOffset, count);
  37957. }
  37958. else {
  37959. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  37960. }
  37961. }
  37962. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  37963. return BABYLON.Tools.Slice(data);
  37964. }
  37965. return data;
  37966. };
  37967. /**
  37968. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  37969. * @param kind defines the data kind (Position, normal, etc...)
  37970. * @returns true if the vertex buffer with the specified kind is updatable
  37971. */
  37972. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  37973. var vb = this._vertexBuffers[kind];
  37974. if (!vb) {
  37975. return false;
  37976. }
  37977. return vb.isUpdatable();
  37978. };
  37979. /**
  37980. * Gets a specific vertex buffer
  37981. * @param kind defines the data kind (Position, normal, etc...)
  37982. * @returns a {BABYLON.VertexBuffer}
  37983. */
  37984. Geometry.prototype.getVertexBuffer = function (kind) {
  37985. if (!this.isReady()) {
  37986. return null;
  37987. }
  37988. return this._vertexBuffers[kind];
  37989. };
  37990. /**
  37991. * Returns all vertex buffers
  37992. * @return an object holding all vertex buffers indexed by kind
  37993. */
  37994. Geometry.prototype.getVertexBuffers = function () {
  37995. if (!this.isReady()) {
  37996. return null;
  37997. }
  37998. return this._vertexBuffers;
  37999. };
  38000. /**
  38001. * Gets a boolean indicating if specific vertex buffer is present
  38002. * @param kind defines the data kind (Position, normal, etc...)
  38003. * @returns true if data is present
  38004. */
  38005. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38006. if (!this._vertexBuffers) {
  38007. if (this._delayInfo) {
  38008. return this._delayInfo.indexOf(kind) !== -1;
  38009. }
  38010. return false;
  38011. }
  38012. return this._vertexBuffers[kind] !== undefined;
  38013. };
  38014. /**
  38015. * Gets a list of all attached data kinds (Position, normal, etc...)
  38016. * @returns a list of string containing all kinds
  38017. */
  38018. Geometry.prototype.getVerticesDataKinds = function () {
  38019. var result = [];
  38020. var kind;
  38021. if (!this._vertexBuffers && this._delayInfo) {
  38022. for (kind in this._delayInfo) {
  38023. result.push(kind);
  38024. }
  38025. }
  38026. else {
  38027. for (kind in this._vertexBuffers) {
  38028. result.push(kind);
  38029. }
  38030. }
  38031. return result;
  38032. };
  38033. /**
  38034. * Update index buffer
  38035. * @param indices defines the indices to store in the index buffer
  38036. * @param offset defines the offset in the target buffer where to store the data
  38037. */
  38038. Geometry.prototype.updateIndices = function (indices, offset) {
  38039. if (!this._indexBuffer) {
  38040. return;
  38041. }
  38042. if (!this._indexBufferIsUpdatable) {
  38043. this.setIndices(indices, null, true);
  38044. }
  38045. else {
  38046. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38047. }
  38048. };
  38049. /**
  38050. * Creates a new index buffer
  38051. * @param indices defines the indices to store in the index buffer
  38052. * @param totalVertices defines the total number of vertices (could be null)
  38053. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38054. */
  38055. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38056. if (totalVertices === void 0) { totalVertices = null; }
  38057. if (updatable === void 0) { updatable = false; }
  38058. if (this._indexBuffer) {
  38059. this._engine._releaseBuffer(this._indexBuffer);
  38060. }
  38061. this._disposeVertexArrayObjects();
  38062. this._indices = indices;
  38063. this._indexBufferIsUpdatable = updatable;
  38064. if (this._meshes.length !== 0 && this._indices) {
  38065. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38066. }
  38067. if (totalVertices != undefined) {
  38068. this._totalVertices = totalVertices;
  38069. }
  38070. var meshes = this._meshes;
  38071. var numOfMeshes = meshes.length;
  38072. for (var index = 0; index < numOfMeshes; index++) {
  38073. meshes[index]._createGlobalSubMesh(true);
  38074. }
  38075. this.notifyUpdate();
  38076. };
  38077. /**
  38078. * Return the total number of indices
  38079. * @returns the total number of indices
  38080. */
  38081. Geometry.prototype.getTotalIndices = function () {
  38082. if (!this.isReady()) {
  38083. return 0;
  38084. }
  38085. return this._indices.length;
  38086. };
  38087. /**
  38088. * Gets the index buffer array
  38089. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38090. * @returns the index buffer array
  38091. */
  38092. Geometry.prototype.getIndices = function (copyWhenShared) {
  38093. if (!this.isReady()) {
  38094. return null;
  38095. }
  38096. var orig = this._indices;
  38097. if (!copyWhenShared || this._meshes.length === 1) {
  38098. return orig;
  38099. }
  38100. else {
  38101. var len = orig.length;
  38102. var copy = [];
  38103. for (var i = 0; i < len; i++) {
  38104. copy.push(orig[i]);
  38105. }
  38106. return copy;
  38107. }
  38108. };
  38109. /**
  38110. * Gets the index buffer
  38111. * @return the index buffer
  38112. */
  38113. Geometry.prototype.getIndexBuffer = function () {
  38114. if (!this.isReady()) {
  38115. return null;
  38116. }
  38117. return this._indexBuffer;
  38118. };
  38119. /** @ignore */
  38120. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38121. if (effect === void 0) { effect = null; }
  38122. if (!effect || !this._vertexArrayObjects) {
  38123. return;
  38124. }
  38125. if (this._vertexArrayObjects[effect.key]) {
  38126. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38127. delete this._vertexArrayObjects[effect.key];
  38128. }
  38129. };
  38130. /**
  38131. * Release the associated resources for a specific mesh
  38132. * @param mesh defines the source mesh
  38133. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38134. */
  38135. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38136. var meshes = this._meshes;
  38137. var index = meshes.indexOf(mesh);
  38138. if (index === -1) {
  38139. return;
  38140. }
  38141. meshes.splice(index, 1);
  38142. mesh._geometry = null;
  38143. if (meshes.length === 0 && shouldDispose) {
  38144. this.dispose();
  38145. }
  38146. };
  38147. /**
  38148. * Apply current geometry to a given mesh
  38149. * @param mesh defines the mesh to apply geometry to
  38150. */
  38151. Geometry.prototype.applyToMesh = function (mesh) {
  38152. if (mesh._geometry === this) {
  38153. return;
  38154. }
  38155. var previousGeometry = mesh._geometry;
  38156. if (previousGeometry) {
  38157. previousGeometry.releaseForMesh(mesh);
  38158. }
  38159. var meshes = this._meshes;
  38160. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38161. mesh._geometry = this;
  38162. this._scene.pushGeometry(this);
  38163. meshes.push(mesh);
  38164. if (this.isReady()) {
  38165. this._applyToMesh(mesh);
  38166. }
  38167. else {
  38168. mesh._boundingInfo = this._boundingInfo;
  38169. }
  38170. };
  38171. Geometry.prototype._updateExtend = function (data) {
  38172. if (data === void 0) { data = null; }
  38173. if (!data) {
  38174. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38175. }
  38176. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38177. };
  38178. Geometry.prototype._applyToMesh = function (mesh) {
  38179. var numOfMeshes = this._meshes.length;
  38180. // vertexBuffers
  38181. for (var kind in this._vertexBuffers) {
  38182. if (numOfMeshes === 1) {
  38183. this._vertexBuffers[kind].create();
  38184. }
  38185. var buffer = this._vertexBuffers[kind].getBuffer();
  38186. if (buffer)
  38187. buffer.references = numOfMeshes;
  38188. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38189. if (!this._extend) {
  38190. this._updateExtend();
  38191. }
  38192. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38193. mesh._createGlobalSubMesh(false);
  38194. //bounding info was just created again, world matrix should be applied again.
  38195. mesh._updateBoundingInfo();
  38196. }
  38197. }
  38198. // indexBuffer
  38199. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38200. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38201. }
  38202. if (this._indexBuffer) {
  38203. this._indexBuffer.references = numOfMeshes;
  38204. }
  38205. };
  38206. Geometry.prototype.notifyUpdate = function (kind) {
  38207. if (this.onGeometryUpdated) {
  38208. this.onGeometryUpdated(this, kind);
  38209. }
  38210. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38211. var mesh = _a[_i];
  38212. mesh._markSubMeshesAsAttributesDirty();
  38213. }
  38214. };
  38215. /**
  38216. * Load the geometry if it was flagged as delay loaded
  38217. * @param scene defines the hosting scene
  38218. * @param onLoaded defines a callback called when the geometry is loaded
  38219. */
  38220. Geometry.prototype.load = function (scene, onLoaded) {
  38221. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38222. return;
  38223. }
  38224. if (this.isReady()) {
  38225. if (onLoaded) {
  38226. onLoaded();
  38227. }
  38228. return;
  38229. }
  38230. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38231. this._queueLoad(scene, onLoaded);
  38232. };
  38233. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38234. var _this = this;
  38235. if (!this.delayLoadingFile) {
  38236. return;
  38237. }
  38238. scene._addPendingData(this);
  38239. scene._loadFile(this.delayLoadingFile, function (data) {
  38240. if (!_this._delayLoadingFunction) {
  38241. return;
  38242. }
  38243. _this._delayLoadingFunction(JSON.parse(data), _this);
  38244. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38245. _this._delayInfo = [];
  38246. scene._removePendingData(_this);
  38247. var meshes = _this._meshes;
  38248. var numOfMeshes = meshes.length;
  38249. for (var index = 0; index < numOfMeshes; index++) {
  38250. _this._applyToMesh(meshes[index]);
  38251. }
  38252. if (onLoaded) {
  38253. onLoaded();
  38254. }
  38255. }, undefined, true);
  38256. };
  38257. /**
  38258. * Invert the geometry to move from a right handed system to a left handed one.
  38259. */
  38260. Geometry.prototype.toLeftHanded = function () {
  38261. // Flip faces
  38262. var tIndices = this.getIndices(false);
  38263. if (tIndices != null && tIndices.length > 0) {
  38264. for (var i = 0; i < tIndices.length; i += 3) {
  38265. var tTemp = tIndices[i + 0];
  38266. tIndices[i + 0] = tIndices[i + 2];
  38267. tIndices[i + 2] = tTemp;
  38268. }
  38269. this.setIndices(tIndices);
  38270. }
  38271. // Negate position.z
  38272. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38273. if (tPositions != null && tPositions.length > 0) {
  38274. for (var i = 0; i < tPositions.length; i += 3) {
  38275. tPositions[i + 2] = -tPositions[i + 2];
  38276. }
  38277. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38278. }
  38279. // Negate normal.z
  38280. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38281. if (tNormals != null && tNormals.length > 0) {
  38282. for (var i = 0; i < tNormals.length; i += 3) {
  38283. tNormals[i + 2] = -tNormals[i + 2];
  38284. }
  38285. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38286. }
  38287. };
  38288. // Cache
  38289. /** @ignore */
  38290. Geometry.prototype._resetPointsArrayCache = function () {
  38291. this._positions = null;
  38292. };
  38293. /** @ignore */
  38294. Geometry.prototype._generatePointsArray = function () {
  38295. if (this._positions)
  38296. return true;
  38297. this._positions = [];
  38298. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38299. if (!data) {
  38300. return false;
  38301. }
  38302. for (var index = 0; index < data.length; index += 3) {
  38303. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38304. }
  38305. return true;
  38306. };
  38307. /**
  38308. * Gets a value indicating if the geometry is disposed
  38309. * @returns true if the geometry was disposed
  38310. */
  38311. Geometry.prototype.isDisposed = function () {
  38312. return this._isDisposed;
  38313. };
  38314. Geometry.prototype._disposeVertexArrayObjects = function () {
  38315. if (this._vertexArrayObjects) {
  38316. for (var kind in this._vertexArrayObjects) {
  38317. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38318. }
  38319. this._vertexArrayObjects = {};
  38320. }
  38321. };
  38322. /**
  38323. * Free all associated resources
  38324. */
  38325. Geometry.prototype.dispose = function () {
  38326. var meshes = this._meshes;
  38327. var numOfMeshes = meshes.length;
  38328. var index;
  38329. for (index = 0; index < numOfMeshes; index++) {
  38330. this.releaseForMesh(meshes[index]);
  38331. }
  38332. this._meshes = [];
  38333. this._disposeVertexArrayObjects();
  38334. for (var kind in this._vertexBuffers) {
  38335. this._vertexBuffers[kind].dispose();
  38336. }
  38337. this._vertexBuffers = {};
  38338. this._totalVertices = 0;
  38339. if (this._indexBuffer) {
  38340. this._engine._releaseBuffer(this._indexBuffer);
  38341. }
  38342. this._indexBuffer = null;
  38343. this._indices = [];
  38344. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38345. this.delayLoadingFile = null;
  38346. this._delayLoadingFunction = null;
  38347. this._delayInfo = [];
  38348. this._boundingInfo = null;
  38349. this._scene.removeGeometry(this);
  38350. this._isDisposed = true;
  38351. };
  38352. /**
  38353. * Clone the current geometry into a new geometry
  38354. * @param id defines the unique ID of the new geometry
  38355. * @returns a new geometry object
  38356. */
  38357. Geometry.prototype.copy = function (id) {
  38358. var vertexData = new BABYLON.VertexData();
  38359. vertexData.indices = [];
  38360. var indices = this.getIndices();
  38361. if (indices) {
  38362. for (var index = 0; index < indices.length; index++) {
  38363. vertexData.indices.push(indices[index]);
  38364. }
  38365. }
  38366. var updatable = false;
  38367. var stopChecking = false;
  38368. var kind;
  38369. for (kind in this._vertexBuffers) {
  38370. // using slice() to make a copy of the array and not just reference it
  38371. var data = this.getVerticesData(kind);
  38372. if (data instanceof Float32Array) {
  38373. vertexData.set(new Float32Array(data), kind);
  38374. }
  38375. else {
  38376. vertexData.set(data.slice(0), kind);
  38377. }
  38378. if (!stopChecking) {
  38379. var vb = this.getVertexBuffer(kind);
  38380. if (vb) {
  38381. updatable = vb.isUpdatable();
  38382. stopChecking = !updatable;
  38383. }
  38384. }
  38385. }
  38386. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38387. geometry.delayLoadState = this.delayLoadState;
  38388. geometry.delayLoadingFile = this.delayLoadingFile;
  38389. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38390. for (kind in this._delayInfo) {
  38391. geometry._delayInfo = geometry._delayInfo || [];
  38392. geometry._delayInfo.push(kind);
  38393. }
  38394. // Bounding info
  38395. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38396. return geometry;
  38397. };
  38398. /**
  38399. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38400. * @return a JSON representation of the current geometry data (without the vertices data)
  38401. */
  38402. Geometry.prototype.serialize = function () {
  38403. var serializationObject = {};
  38404. serializationObject.id = this.id;
  38405. serializationObject.updatable = this._updatable;
  38406. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38407. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38408. }
  38409. return serializationObject;
  38410. };
  38411. Geometry.prototype.toNumberArray = function (origin) {
  38412. if (Array.isArray(origin)) {
  38413. return origin;
  38414. }
  38415. else {
  38416. return Array.prototype.slice.call(origin);
  38417. }
  38418. };
  38419. /**
  38420. * Serialize all vertices data into a JSON oject
  38421. * @returns a JSON representation of the current geometry data
  38422. */
  38423. Geometry.prototype.serializeVerticeData = function () {
  38424. var serializationObject = this.serialize();
  38425. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38426. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38427. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38428. serializationObject.positions._updatable = true;
  38429. }
  38430. }
  38431. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38432. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38433. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38434. serializationObject.normals._updatable = true;
  38435. }
  38436. }
  38437. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38438. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38439. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38440. serializationObject.tangets._updatable = true;
  38441. }
  38442. }
  38443. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38444. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38445. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38446. serializationObject.uvs._updatable = true;
  38447. }
  38448. }
  38449. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38450. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38451. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38452. serializationObject.uv2s._updatable = true;
  38453. }
  38454. }
  38455. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38456. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38457. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38458. serializationObject.uv3s._updatable = true;
  38459. }
  38460. }
  38461. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38462. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38463. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38464. serializationObject.uv4s._updatable = true;
  38465. }
  38466. }
  38467. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38468. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38469. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38470. serializationObject.uv5s._updatable = true;
  38471. }
  38472. }
  38473. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38474. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38475. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38476. serializationObject.uv6s._updatable = true;
  38477. }
  38478. }
  38479. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38480. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38481. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38482. serializationObject.colors._updatable = true;
  38483. }
  38484. }
  38485. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38486. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38487. serializationObject.matricesIndices._isExpanded = true;
  38488. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38489. serializationObject.matricesIndices._updatable = true;
  38490. }
  38491. }
  38492. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38493. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38494. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38495. serializationObject.matricesWeights._updatable = true;
  38496. }
  38497. }
  38498. serializationObject.indices = this.toNumberArray(this.getIndices());
  38499. return serializationObject;
  38500. };
  38501. // Statics
  38502. /**
  38503. * Extracts a clone of a mesh geometry
  38504. * @param mesh defines the source mesh
  38505. * @param id defines the unique ID of the new geometry object
  38506. * @returns the new geometry object
  38507. */
  38508. Geometry.ExtractFromMesh = function (mesh, id) {
  38509. var geometry = mesh._geometry;
  38510. if (!geometry) {
  38511. return null;
  38512. }
  38513. return geometry.copy(id);
  38514. };
  38515. /**
  38516. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  38517. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  38518. * Be aware Math.random() could cause collisions, but:
  38519. * "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"
  38520. * @returns a string containing a new GUID
  38521. */
  38522. Geometry.RandomId = function () {
  38523. return BABYLON.Tools.RandomId();
  38524. };
  38525. /** @ignore */
  38526. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  38527. var scene = mesh.getScene();
  38528. // Geometry
  38529. var geometryId = parsedGeometry.geometryId;
  38530. if (geometryId) {
  38531. var geometry = scene.getGeometryByID(geometryId);
  38532. if (geometry) {
  38533. geometry.applyToMesh(mesh);
  38534. }
  38535. }
  38536. else if (parsedGeometry instanceof ArrayBuffer) {
  38537. var binaryInfo = mesh._binaryInfo;
  38538. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  38539. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  38540. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  38541. }
  38542. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  38543. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  38544. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  38545. }
  38546. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  38547. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  38548. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  38549. }
  38550. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  38551. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  38552. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  38553. }
  38554. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  38555. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  38556. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  38557. }
  38558. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  38559. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  38560. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  38561. }
  38562. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  38563. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  38564. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  38565. }
  38566. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  38567. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  38568. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  38569. }
  38570. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  38571. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  38572. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  38573. }
  38574. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  38575. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  38576. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  38577. }
  38578. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  38579. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  38580. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  38581. }
  38582. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  38583. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  38584. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  38585. }
  38586. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  38587. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  38588. mesh.setIndices(indicesData, null);
  38589. }
  38590. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  38591. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  38592. mesh.subMeshes = [];
  38593. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  38594. var materialIndex = subMeshesData[(i * 5) + 0];
  38595. var verticesStart = subMeshesData[(i * 5) + 1];
  38596. var verticesCount = subMeshesData[(i * 5) + 2];
  38597. var indexStart = subMeshesData[(i * 5) + 3];
  38598. var indexCount = subMeshesData[(i * 5) + 4];
  38599. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  38600. }
  38601. }
  38602. }
  38603. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  38604. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  38605. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  38606. if (parsedGeometry.tangents) {
  38607. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  38608. }
  38609. if (parsedGeometry.uvs) {
  38610. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  38611. }
  38612. if (parsedGeometry.uvs2) {
  38613. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  38614. }
  38615. if (parsedGeometry.uvs3) {
  38616. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  38617. }
  38618. if (parsedGeometry.uvs4) {
  38619. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  38620. }
  38621. if (parsedGeometry.uvs5) {
  38622. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  38623. }
  38624. if (parsedGeometry.uvs6) {
  38625. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  38626. }
  38627. if (parsedGeometry.colors) {
  38628. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  38629. }
  38630. if (parsedGeometry.matricesIndices) {
  38631. if (!parsedGeometry.matricesIndices._isExpanded) {
  38632. var floatIndices = [];
  38633. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  38634. var matricesIndex = parsedGeometry.matricesIndices[i];
  38635. floatIndices.push(matricesIndex & 0x000000FF);
  38636. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38637. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38638. floatIndices.push(matricesIndex >> 24);
  38639. }
  38640. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  38641. }
  38642. else {
  38643. delete parsedGeometry.matricesIndices._isExpanded;
  38644. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  38645. }
  38646. }
  38647. if (parsedGeometry.matricesIndicesExtra) {
  38648. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  38649. var floatIndices = [];
  38650. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  38651. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  38652. floatIndices.push(matricesIndex & 0x000000FF);
  38653. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  38654. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  38655. floatIndices.push(matricesIndex >> 24);
  38656. }
  38657. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  38658. }
  38659. else {
  38660. delete parsedGeometry.matricesIndices._isExpanded;
  38661. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  38662. }
  38663. }
  38664. if (parsedGeometry.matricesWeights) {
  38665. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  38666. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  38667. }
  38668. if (parsedGeometry.matricesWeightsExtra) {
  38669. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  38670. }
  38671. mesh.setIndices(parsedGeometry.indices, null);
  38672. }
  38673. // SubMeshes
  38674. if (parsedGeometry.subMeshes) {
  38675. mesh.subMeshes = [];
  38676. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  38677. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  38678. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  38679. }
  38680. }
  38681. // Flat shading
  38682. if (mesh._shouldGenerateFlatShading) {
  38683. mesh.convertToFlatShadedMesh();
  38684. delete mesh._shouldGenerateFlatShading;
  38685. }
  38686. // Update
  38687. mesh.computeWorldMatrix(true);
  38688. // Octree
  38689. var sceneOctree = scene.selectionOctree;
  38690. if (sceneOctree !== undefined && sceneOctree !== null) {
  38691. sceneOctree.addMesh(mesh);
  38692. }
  38693. };
  38694. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  38695. var epsilon = 1e-3;
  38696. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  38697. return;
  38698. }
  38699. var noInfluenceBoneIndex = 0.0;
  38700. if (parsedGeometry.skeletonId > -1) {
  38701. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  38702. if (!skeleton) {
  38703. return;
  38704. }
  38705. noInfluenceBoneIndex = skeleton.bones.length;
  38706. }
  38707. else {
  38708. return;
  38709. }
  38710. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  38711. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38712. var matricesWeights = parsedGeometry.matricesWeights;
  38713. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  38714. var influencers = parsedGeometry.numBoneInfluencer;
  38715. var size = matricesWeights.length;
  38716. for (var i = 0; i < size; i += 4) {
  38717. var weight = 0.0;
  38718. var firstZeroWeight = -1;
  38719. for (var j = 0; j < 4; j++) {
  38720. var w = matricesWeights[i + j];
  38721. weight += w;
  38722. if (w < epsilon && firstZeroWeight < 0) {
  38723. firstZeroWeight = j;
  38724. }
  38725. }
  38726. if (matricesWeightsExtra) {
  38727. for (var j = 0; j < 4; j++) {
  38728. var w = matricesWeightsExtra[i + j];
  38729. weight += w;
  38730. if (w < epsilon && firstZeroWeight < 0) {
  38731. firstZeroWeight = j + 4;
  38732. }
  38733. }
  38734. }
  38735. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  38736. firstZeroWeight = influencers - 1;
  38737. }
  38738. if (weight > epsilon) {
  38739. var mweight = 1.0 / weight;
  38740. for (var j = 0; j < 4; j++) {
  38741. matricesWeights[i + j] *= mweight;
  38742. }
  38743. if (matricesWeightsExtra) {
  38744. for (var j = 0; j < 4; j++) {
  38745. matricesWeightsExtra[i + j] *= mweight;
  38746. }
  38747. }
  38748. }
  38749. else {
  38750. if (firstZeroWeight >= 4) {
  38751. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  38752. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  38753. }
  38754. else {
  38755. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  38756. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  38757. }
  38758. }
  38759. }
  38760. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  38761. if (parsedGeometry.matricesWeightsExtra) {
  38762. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  38763. }
  38764. };
  38765. /**
  38766. * Create a new geometry from persisted data (Using .babylon file format)
  38767. * @param parsedVertexData defines the persisted data
  38768. * @param scene defines the hosting scene
  38769. * @param rootUrl defines the root url to use to load assets (like delayed data)
  38770. * @returns the new geometry object
  38771. */
  38772. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  38773. if (scene.getGeometryByID(parsedVertexData.id)) {
  38774. return null; // null since geometry could be something else than a box...
  38775. }
  38776. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  38777. if (BABYLON.Tags) {
  38778. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  38779. }
  38780. if (parsedVertexData.delayLoadingFile) {
  38781. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38782. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  38783. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  38784. geometry._delayInfo = [];
  38785. if (parsedVertexData.hasUVs) {
  38786. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  38787. }
  38788. if (parsedVertexData.hasUVs2) {
  38789. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  38790. }
  38791. if (parsedVertexData.hasUVs3) {
  38792. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  38793. }
  38794. if (parsedVertexData.hasUVs4) {
  38795. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  38796. }
  38797. if (parsedVertexData.hasUVs5) {
  38798. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  38799. }
  38800. if (parsedVertexData.hasUVs6) {
  38801. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  38802. }
  38803. if (parsedVertexData.hasColors) {
  38804. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  38805. }
  38806. if (parsedVertexData.hasMatricesIndices) {
  38807. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38808. }
  38809. if (parsedVertexData.hasMatricesWeights) {
  38810. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38811. }
  38812. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  38813. }
  38814. else {
  38815. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  38816. }
  38817. scene.pushGeometry(geometry, true);
  38818. return geometry;
  38819. };
  38820. return Geometry;
  38821. }());
  38822. BABYLON.Geometry = Geometry;
  38823. // Primitives
  38824. /// Abstract class
  38825. /**
  38826. * Abstract class used to provide common services for all typed geometries
  38827. */
  38828. var _PrimitiveGeometry = /** @class */ (function (_super) {
  38829. __extends(_PrimitiveGeometry, _super);
  38830. /**
  38831. * Creates a new typed geometry
  38832. * @param id defines the unique ID of the geometry
  38833. * @param scene defines the hosting scene
  38834. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38835. * @param mesh defines the hosting mesh (can be null)
  38836. */
  38837. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  38838. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  38839. if (mesh === void 0) { mesh = null; }
  38840. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  38841. _this._canBeRegenerated = _canBeRegenerated;
  38842. _this._beingRegenerated = true;
  38843. _this.regenerate();
  38844. _this._beingRegenerated = false;
  38845. return _this;
  38846. }
  38847. /**
  38848. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  38849. * @returns true if the geometry can be regenerated
  38850. */
  38851. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  38852. return this._canBeRegenerated;
  38853. };
  38854. /**
  38855. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  38856. */
  38857. _PrimitiveGeometry.prototype.regenerate = function () {
  38858. if (!this._canBeRegenerated) {
  38859. return;
  38860. }
  38861. this._beingRegenerated = true;
  38862. this.setAllVerticesData(this._regenerateVertexData(), false);
  38863. this._beingRegenerated = false;
  38864. };
  38865. /**
  38866. * Clone the geometry
  38867. * @param id defines the unique ID of the new geometry
  38868. * @returns the new geometry
  38869. */
  38870. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  38871. return _super.prototype.copy.call(this, id);
  38872. };
  38873. // overrides
  38874. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38875. if (!this._beingRegenerated) {
  38876. return;
  38877. }
  38878. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  38879. };
  38880. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  38881. if (!this._beingRegenerated) {
  38882. return;
  38883. }
  38884. _super.prototype.setVerticesData.call(this, kind, data, false);
  38885. };
  38886. // to override
  38887. /** @ignore */
  38888. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  38889. throw new Error("Abstract method");
  38890. };
  38891. _PrimitiveGeometry.prototype.copy = function (id) {
  38892. throw new Error("Must be overriden in sub-classes.");
  38893. };
  38894. _PrimitiveGeometry.prototype.serialize = function () {
  38895. var serializationObject = _super.prototype.serialize.call(this);
  38896. serializationObject.canBeRegenerated = this.canBeRegenerated();
  38897. return serializationObject;
  38898. };
  38899. return _PrimitiveGeometry;
  38900. }(Geometry));
  38901. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  38902. /**
  38903. * Creates a ribbon geometry
  38904. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  38905. */
  38906. var RibbonGeometry = /** @class */ (function (_super) {
  38907. __extends(RibbonGeometry, _super);
  38908. /**
  38909. * Creates a ribbon geometry
  38910. * @param id defines the unique ID of the geometry
  38911. * @param scene defines the hosting scene
  38912. * @param pathArray defines the array of paths to use
  38913. * @param closeArray defines if the last path and the first path must be joined
  38914. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  38915. * @param offset defines the offset between points
  38916. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38917. * @param mesh defines the hosting mesh (can be null)
  38918. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38919. */
  38920. function RibbonGeometry(id, scene,
  38921. /**
  38922. * Defines the array of paths to use
  38923. */
  38924. pathArray,
  38925. /**
  38926. * Defines if the last and first points of each path in your pathArray must be joined
  38927. */
  38928. closeArray,
  38929. /**
  38930. * Defines if the last and first points of each path in your pathArray must be joined
  38931. */
  38932. closePath,
  38933. /**
  38934. * Defines the offset between points
  38935. */
  38936. offset, canBeRegenerated, mesh,
  38937. /**
  38938. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38939. */
  38940. side) {
  38941. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38942. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38943. _this.pathArray = pathArray;
  38944. _this.closeArray = closeArray;
  38945. _this.closePath = closePath;
  38946. _this.offset = offset;
  38947. _this.side = side;
  38948. return _this;
  38949. }
  38950. /** @ignore */
  38951. RibbonGeometry.prototype._regenerateVertexData = function () {
  38952. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  38953. };
  38954. RibbonGeometry.prototype.copy = function (id) {
  38955. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  38956. };
  38957. return RibbonGeometry;
  38958. }(_PrimitiveGeometry));
  38959. BABYLON.RibbonGeometry = RibbonGeometry;
  38960. /**
  38961. * Creates a box geometry
  38962. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  38963. */
  38964. var BoxGeometry = /** @class */ (function (_super) {
  38965. __extends(BoxGeometry, _super);
  38966. /**
  38967. * Creates a box geometry
  38968. * @param id defines the unique ID of the geometry
  38969. * @param scene defines the hosting scene
  38970. * @param size defines the zise of the box (width, height and depth are the same)
  38971. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  38972. * @param mesh defines the hosting mesh (can be null)
  38973. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38974. */
  38975. function BoxGeometry(id, scene,
  38976. /**
  38977. * Defines the zise of the box (width, height and depth are the same)
  38978. */
  38979. size, canBeRegenerated, mesh,
  38980. /**
  38981. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  38982. */
  38983. side) {
  38984. if (mesh === void 0) { mesh = null; }
  38985. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38986. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38987. _this.size = size;
  38988. _this.side = side;
  38989. return _this;
  38990. }
  38991. BoxGeometry.prototype._regenerateVertexData = function () {
  38992. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  38993. };
  38994. BoxGeometry.prototype.copy = function (id) {
  38995. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  38996. };
  38997. BoxGeometry.prototype.serialize = function () {
  38998. var serializationObject = _super.prototype.serialize.call(this);
  38999. serializationObject.size = this.size;
  39000. return serializationObject;
  39001. };
  39002. BoxGeometry.Parse = function (parsedBox, scene) {
  39003. if (scene.getGeometryByID(parsedBox.id)) {
  39004. return null; // null since geometry could be something else than a box...
  39005. }
  39006. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39007. if (BABYLON.Tags) {
  39008. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39009. }
  39010. scene.pushGeometry(box, true);
  39011. return box;
  39012. };
  39013. return BoxGeometry;
  39014. }(_PrimitiveGeometry));
  39015. BABYLON.BoxGeometry = BoxGeometry;
  39016. /**
  39017. * Creates a sphere geometry
  39018. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39019. */
  39020. var SphereGeometry = /** @class */ (function (_super) {
  39021. __extends(SphereGeometry, _super);
  39022. /**
  39023. * Create a new sphere geometry
  39024. * @param id defines the unique ID of the geometry
  39025. * @param scene defines the hosting scene
  39026. * @param segments defines the number of segments to use to create the sphere
  39027. * @param diameter defines the diameter of the sphere
  39028. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39029. * @param mesh defines the hosting mesh (can be null)
  39030. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39031. */
  39032. function SphereGeometry(id, scene,
  39033. /**
  39034. * Defines the number of segments to use to create the sphere
  39035. */
  39036. segments,
  39037. /**
  39038. * Defines the diameter of the sphere
  39039. */
  39040. diameter, canBeRegenerated, mesh,
  39041. /**
  39042. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39043. */
  39044. side) {
  39045. if (mesh === void 0) { mesh = null; }
  39046. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39047. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39048. _this.segments = segments;
  39049. _this.diameter = diameter;
  39050. _this.side = side;
  39051. return _this;
  39052. }
  39053. SphereGeometry.prototype._regenerateVertexData = function () {
  39054. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39055. };
  39056. SphereGeometry.prototype.copy = function (id) {
  39057. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39058. };
  39059. SphereGeometry.prototype.serialize = function () {
  39060. var serializationObject = _super.prototype.serialize.call(this);
  39061. serializationObject.segments = this.segments;
  39062. serializationObject.diameter = this.diameter;
  39063. return serializationObject;
  39064. };
  39065. SphereGeometry.Parse = function (parsedSphere, scene) {
  39066. if (scene.getGeometryByID(parsedSphere.id)) {
  39067. return null; // null since geometry could be something else than a sphere...
  39068. }
  39069. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39070. if (BABYLON.Tags) {
  39071. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39072. }
  39073. scene.pushGeometry(sphere, true);
  39074. return sphere;
  39075. };
  39076. return SphereGeometry;
  39077. }(_PrimitiveGeometry));
  39078. BABYLON.SphereGeometry = SphereGeometry;
  39079. /**
  39080. * Creates a disc geometry
  39081. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39082. */
  39083. var DiscGeometry = /** @class */ (function (_super) {
  39084. __extends(DiscGeometry, _super);
  39085. /**
  39086. * Creates a new disc geometry
  39087. * @param id defines the unique ID of the geometry
  39088. * @param scene defines the hosting scene
  39089. * @param radius defines the radius of the disc
  39090. * @param tessellation defines the tesselation factor to apply to the disc
  39091. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39092. * @param mesh defines the hosting mesh (can be null)
  39093. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39094. */
  39095. function DiscGeometry(id, scene,
  39096. /**
  39097. * Defines the radius of the disc
  39098. */
  39099. radius,
  39100. /**
  39101. * Defines the tesselation factor to apply to the disc
  39102. */
  39103. tessellation, canBeRegenerated, mesh,
  39104. /**
  39105. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39106. */
  39107. side) {
  39108. if (mesh === void 0) { mesh = null; }
  39109. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39110. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39111. _this.radius = radius;
  39112. _this.tessellation = tessellation;
  39113. _this.side = side;
  39114. return _this;
  39115. }
  39116. DiscGeometry.prototype._regenerateVertexData = function () {
  39117. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39118. };
  39119. DiscGeometry.prototype.copy = function (id) {
  39120. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39121. };
  39122. return DiscGeometry;
  39123. }(_PrimitiveGeometry));
  39124. BABYLON.DiscGeometry = DiscGeometry;
  39125. /**
  39126. * Creates a new cylinder geometry
  39127. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39128. */
  39129. var CylinderGeometry = /** @class */ (function (_super) {
  39130. __extends(CylinderGeometry, _super);
  39131. /**
  39132. * Creates a new cylinder geometry
  39133. * @param id defines the unique ID of the geometry
  39134. * @param scene defines the hosting scene
  39135. * @param height defines the height of the cylinder
  39136. * @param diameterTop defines the diameter of the cylinder's top cap
  39137. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39138. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39139. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39140. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39141. * @param mesh defines the hosting mesh (can be null)
  39142. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39143. */
  39144. function CylinderGeometry(id, scene,
  39145. /**
  39146. * Defines the height of the cylinder
  39147. */
  39148. height,
  39149. /**
  39150. * Defines the diameter of the cylinder's top cap
  39151. */
  39152. diameterTop,
  39153. /**
  39154. * Defines the diameter of the cylinder's bottom cap
  39155. */
  39156. diameterBottom,
  39157. /**
  39158. * Defines the tessellation factor to apply to the cylinder
  39159. */
  39160. tessellation,
  39161. /**
  39162. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39163. */
  39164. subdivisions, canBeRegenerated, mesh,
  39165. /**
  39166. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39167. */
  39168. side) {
  39169. if (subdivisions === void 0) { subdivisions = 1; }
  39170. if (mesh === void 0) { mesh = null; }
  39171. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39172. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39173. _this.height = height;
  39174. _this.diameterTop = diameterTop;
  39175. _this.diameterBottom = diameterBottom;
  39176. _this.tessellation = tessellation;
  39177. _this.subdivisions = subdivisions;
  39178. _this.side = side;
  39179. return _this;
  39180. }
  39181. CylinderGeometry.prototype._regenerateVertexData = function () {
  39182. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39183. };
  39184. CylinderGeometry.prototype.copy = function (id) {
  39185. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39186. };
  39187. CylinderGeometry.prototype.serialize = function () {
  39188. var serializationObject = _super.prototype.serialize.call(this);
  39189. serializationObject.height = this.height;
  39190. serializationObject.diameterTop = this.diameterTop;
  39191. serializationObject.diameterBottom = this.diameterBottom;
  39192. serializationObject.tessellation = this.tessellation;
  39193. return serializationObject;
  39194. };
  39195. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39196. if (scene.getGeometryByID(parsedCylinder.id)) {
  39197. return null; // null since geometry could be something else than a cylinder...
  39198. }
  39199. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39200. if (BABYLON.Tags) {
  39201. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39202. }
  39203. scene.pushGeometry(cylinder, true);
  39204. return cylinder;
  39205. };
  39206. return CylinderGeometry;
  39207. }(_PrimitiveGeometry));
  39208. BABYLON.CylinderGeometry = CylinderGeometry;
  39209. /**
  39210. * Creates a new torus geometry
  39211. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39212. */
  39213. var TorusGeometry = /** @class */ (function (_super) {
  39214. __extends(TorusGeometry, _super);
  39215. /**
  39216. * Creates a new torus geometry
  39217. * @param id defines the unique ID of the geometry
  39218. * @param scene defines the hosting scene
  39219. * @param diameter defines the diameter of the torus
  39220. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39221. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39222. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39223. * @param mesh defines the hosting mesh (can be null)
  39224. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39225. */
  39226. function TorusGeometry(id, scene,
  39227. /**
  39228. * Defines the diameter of the torus
  39229. */
  39230. diameter,
  39231. /**
  39232. * Defines the thickness of the torus (ie. internal diameter)
  39233. */
  39234. thickness,
  39235. /**
  39236. * Defines the tesselation factor to apply to the torus
  39237. */
  39238. tessellation, canBeRegenerated, mesh,
  39239. /**
  39240. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39241. */
  39242. side) {
  39243. if (mesh === void 0) { mesh = null; }
  39244. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39245. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39246. _this.diameter = diameter;
  39247. _this.thickness = thickness;
  39248. _this.tessellation = tessellation;
  39249. _this.side = side;
  39250. return _this;
  39251. }
  39252. TorusGeometry.prototype._regenerateVertexData = function () {
  39253. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39254. };
  39255. TorusGeometry.prototype.copy = function (id) {
  39256. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39257. };
  39258. TorusGeometry.prototype.serialize = function () {
  39259. var serializationObject = _super.prototype.serialize.call(this);
  39260. serializationObject.diameter = this.diameter;
  39261. serializationObject.thickness = this.thickness;
  39262. serializationObject.tessellation = this.tessellation;
  39263. return serializationObject;
  39264. };
  39265. TorusGeometry.Parse = function (parsedTorus, scene) {
  39266. if (scene.getGeometryByID(parsedTorus.id)) {
  39267. return null; // null since geometry could be something else than a torus...
  39268. }
  39269. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39270. if (BABYLON.Tags) {
  39271. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39272. }
  39273. scene.pushGeometry(torus, true);
  39274. return torus;
  39275. };
  39276. return TorusGeometry;
  39277. }(_PrimitiveGeometry));
  39278. BABYLON.TorusGeometry = TorusGeometry;
  39279. /**
  39280. * Creates a new ground geometry
  39281. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39282. */
  39283. var GroundGeometry = /** @class */ (function (_super) {
  39284. __extends(GroundGeometry, _super);
  39285. /**
  39286. * Creates a new ground geometry
  39287. * @param id defines the unique ID of the geometry
  39288. * @param scene defines the hosting scene
  39289. * @param width defines the width of the ground
  39290. * @param height defines the height of the ground
  39291. * @param subdivisions defines the subdivisions to apply to the ground
  39292. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39293. * @param mesh defines the hosting mesh (can be null)
  39294. */
  39295. function GroundGeometry(id, scene,
  39296. /**
  39297. * Defines the width of the ground
  39298. */
  39299. width,
  39300. /**
  39301. * Defines the height of the ground
  39302. */
  39303. height,
  39304. /**
  39305. * Defines the subdivisions to apply to the ground
  39306. */
  39307. subdivisions, canBeRegenerated, mesh) {
  39308. if (mesh === void 0) { mesh = null; }
  39309. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39310. _this.width = width;
  39311. _this.height = height;
  39312. _this.subdivisions = subdivisions;
  39313. return _this;
  39314. }
  39315. GroundGeometry.prototype._regenerateVertexData = function () {
  39316. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39317. };
  39318. GroundGeometry.prototype.copy = function (id) {
  39319. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39320. };
  39321. GroundGeometry.prototype.serialize = function () {
  39322. var serializationObject = _super.prototype.serialize.call(this);
  39323. serializationObject.width = this.width;
  39324. serializationObject.height = this.height;
  39325. serializationObject.subdivisions = this.subdivisions;
  39326. return serializationObject;
  39327. };
  39328. GroundGeometry.Parse = function (parsedGround, scene) {
  39329. if (scene.getGeometryByID(parsedGround.id)) {
  39330. return null; // null since geometry could be something else than a ground...
  39331. }
  39332. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39333. if (BABYLON.Tags) {
  39334. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39335. }
  39336. scene.pushGeometry(ground, true);
  39337. return ground;
  39338. };
  39339. return GroundGeometry;
  39340. }(_PrimitiveGeometry));
  39341. BABYLON.GroundGeometry = GroundGeometry;
  39342. /**
  39343. * Creates a tiled ground geometry
  39344. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39345. */
  39346. var TiledGroundGeometry = /** @class */ (function (_super) {
  39347. __extends(TiledGroundGeometry, _super);
  39348. /**
  39349. * Creates a tiled ground geometry
  39350. * @param id defines the unique ID of the geometry
  39351. * @param scene defines the hosting scene
  39352. * @param xmin defines the minimum value on X axis
  39353. * @param zmin defines the minimum value on Z axis
  39354. * @param xmax defines the maximum value on X axis
  39355. * @param zmax defines the maximum value on Z axis
  39356. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39357. * @param precision defines the precision to use when computing the tiles
  39358. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39359. * @param mesh defines the hosting mesh (can be null)
  39360. */
  39361. function TiledGroundGeometry(id, scene,
  39362. /**
  39363. * Defines the minimum value on X axis
  39364. */
  39365. xmin,
  39366. /**
  39367. * Defines the minimum value on Z axis
  39368. */
  39369. zmin,
  39370. /**
  39371. * Defines the maximum value on X axis
  39372. */
  39373. xmax,
  39374. /**
  39375. * Defines the maximum value on Z axis
  39376. */
  39377. zmax,
  39378. /**
  39379. * Defines the subdivisions to apply to the ground
  39380. */
  39381. subdivisions,
  39382. /**
  39383. * Defines the precision to use when computing the tiles
  39384. */
  39385. precision, canBeRegenerated, mesh) {
  39386. if (mesh === void 0) { mesh = null; }
  39387. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39388. _this.xmin = xmin;
  39389. _this.zmin = zmin;
  39390. _this.xmax = xmax;
  39391. _this.zmax = zmax;
  39392. _this.subdivisions = subdivisions;
  39393. _this.precision = precision;
  39394. return _this;
  39395. }
  39396. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39397. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39398. };
  39399. TiledGroundGeometry.prototype.copy = function (id) {
  39400. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39401. };
  39402. return TiledGroundGeometry;
  39403. }(_PrimitiveGeometry));
  39404. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39405. /**
  39406. * Creates a plane geometry
  39407. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39408. */
  39409. var PlaneGeometry = /** @class */ (function (_super) {
  39410. __extends(PlaneGeometry, _super);
  39411. /**
  39412. * Creates a plane geometry
  39413. * @param id defines the unique ID of the geometry
  39414. * @param scene defines the hosting scene
  39415. * @param size defines the size of the plane (width === height)
  39416. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39417. * @param mesh defines the hosting mesh (can be null)
  39418. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39419. */
  39420. function PlaneGeometry(id, scene,
  39421. /**
  39422. * Defines the size of the plane (width === height)
  39423. */
  39424. size, canBeRegenerated, mesh,
  39425. /**
  39426. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39427. */
  39428. side) {
  39429. if (mesh === void 0) { mesh = null; }
  39430. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39431. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39432. _this.size = size;
  39433. _this.side = side;
  39434. return _this;
  39435. }
  39436. PlaneGeometry.prototype._regenerateVertexData = function () {
  39437. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39438. };
  39439. PlaneGeometry.prototype.copy = function (id) {
  39440. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39441. };
  39442. PlaneGeometry.prototype.serialize = function () {
  39443. var serializationObject = _super.prototype.serialize.call(this);
  39444. serializationObject.size = this.size;
  39445. return serializationObject;
  39446. };
  39447. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39448. if (scene.getGeometryByID(parsedPlane.id)) {
  39449. return null; // null since geometry could be something else than a ground...
  39450. }
  39451. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39452. if (BABYLON.Tags) {
  39453. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39454. }
  39455. scene.pushGeometry(plane, true);
  39456. return plane;
  39457. };
  39458. return PlaneGeometry;
  39459. }(_PrimitiveGeometry));
  39460. BABYLON.PlaneGeometry = PlaneGeometry;
  39461. /**
  39462. * Creates a torus knot geometry
  39463. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39464. */
  39465. var TorusKnotGeometry = /** @class */ (function (_super) {
  39466. __extends(TorusKnotGeometry, _super);
  39467. /**
  39468. * Creates a torus knot geometry
  39469. * @param id defines the unique ID of the geometry
  39470. * @param scene defines the hosting scene
  39471. * @param radius defines the radius of the torus knot
  39472. * @param tube defines the thickness of the torus knot tube
  39473. * @param radialSegments defines the number of radial segments
  39474. * @param tubularSegments defines the number of tubular segments
  39475. * @param p defines the first number of windings
  39476. * @param q defines the second number of windings
  39477. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39478. * @param mesh defines the hosting mesh (can be null)
  39479. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39480. */
  39481. function TorusKnotGeometry(id, scene,
  39482. /**
  39483. * Defines the radius of the torus knot
  39484. */
  39485. radius,
  39486. /**
  39487. * Defines the thickness of the torus knot tube
  39488. */
  39489. tube,
  39490. /**
  39491. * Defines the number of radial segments
  39492. */
  39493. radialSegments,
  39494. /**
  39495. * Defines the number of tubular segments
  39496. */
  39497. tubularSegments,
  39498. /**
  39499. * Defines the first number of windings
  39500. */
  39501. p,
  39502. /**
  39503. * Defines the second number of windings
  39504. */
  39505. q, canBeRegenerated, mesh,
  39506. /**
  39507. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39508. */
  39509. side) {
  39510. if (mesh === void 0) { mesh = null; }
  39511. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39512. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39513. _this.radius = radius;
  39514. _this.tube = tube;
  39515. _this.radialSegments = radialSegments;
  39516. _this.tubularSegments = tubularSegments;
  39517. _this.p = p;
  39518. _this.q = q;
  39519. _this.side = side;
  39520. return _this;
  39521. }
  39522. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  39523. 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 });
  39524. };
  39525. TorusKnotGeometry.prototype.copy = function (id) {
  39526. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  39527. };
  39528. TorusKnotGeometry.prototype.serialize = function () {
  39529. var serializationObject = _super.prototype.serialize.call(this);
  39530. serializationObject.radius = this.radius;
  39531. serializationObject.tube = this.tube;
  39532. serializationObject.radialSegments = this.radialSegments;
  39533. serializationObject.tubularSegments = this.tubularSegments;
  39534. serializationObject.p = this.p;
  39535. serializationObject.q = this.q;
  39536. return serializationObject;
  39537. };
  39538. ;
  39539. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  39540. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  39541. return null; // null since geometry could be something else than a ground...
  39542. }
  39543. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  39544. if (BABYLON.Tags) {
  39545. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  39546. }
  39547. scene.pushGeometry(torusKnot, true);
  39548. return torusKnot;
  39549. };
  39550. return TorusKnotGeometry;
  39551. }(_PrimitiveGeometry));
  39552. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  39553. //}
  39554. })(BABYLON || (BABYLON = {}));
  39555. //# sourceMappingURL=babylon.geometry.js.map
  39556. "use strict";
  39557. var BABYLON;
  39558. (function (BABYLON) {
  39559. /**
  39560. * PostProcessManager is used to manage one or more post processes or post process pipelines
  39561. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  39562. */
  39563. var PostProcessManager = /** @class */ (function () {
  39564. /**
  39565. * Creates a new instance PostProcess
  39566. * @param scene The scene that the post process is associated with.
  39567. */
  39568. function PostProcessManager(scene) {
  39569. this._vertexBuffers = {};
  39570. this._scene = scene;
  39571. }
  39572. PostProcessManager.prototype._prepareBuffers = function () {
  39573. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  39574. return;
  39575. }
  39576. // VBO
  39577. var vertices = [];
  39578. vertices.push(1, 1);
  39579. vertices.push(-1, 1);
  39580. vertices.push(-1, -1);
  39581. vertices.push(1, -1);
  39582. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39583. this._buildIndexBuffer();
  39584. };
  39585. PostProcessManager.prototype._buildIndexBuffer = function () {
  39586. // Indices
  39587. var indices = [];
  39588. indices.push(0);
  39589. indices.push(1);
  39590. indices.push(2);
  39591. indices.push(0);
  39592. indices.push(2);
  39593. indices.push(3);
  39594. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  39595. };
  39596. /**
  39597. * Rebuilds the vertex buffers of the manager.
  39598. */
  39599. PostProcessManager.prototype._rebuild = function () {
  39600. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39601. if (!vb) {
  39602. return;
  39603. }
  39604. vb._rebuild();
  39605. this._buildIndexBuffer();
  39606. };
  39607. // Methods
  39608. /**
  39609. * Prepares a frame to be run through a post process.
  39610. * @param sourceTexture The input texture to the post procesess. (default: null)
  39611. * @param postProcesses An array of post processes to be run. (default: null)
  39612. * @returns True if the post processes were able to be run.
  39613. */
  39614. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  39615. if (sourceTexture === void 0) { sourceTexture = null; }
  39616. if (postProcesses === void 0) { postProcesses = null; }
  39617. var camera = this._scene.activeCamera;
  39618. if (!camera) {
  39619. return false;
  39620. }
  39621. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39622. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39623. return false;
  39624. }
  39625. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  39626. return true;
  39627. };
  39628. /**
  39629. * Manually render a set of post processes to a texture.
  39630. * @param postProcesses An array of post processes to be run.
  39631. * @param targetTexture The target texture to render to.
  39632. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  39633. */
  39634. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  39635. if (targetTexture === void 0) { targetTexture = null; }
  39636. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39637. var engine = this._scene.getEngine();
  39638. for (var index = 0; index < postProcesses.length; index++) {
  39639. if (index < postProcesses.length - 1) {
  39640. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  39641. }
  39642. else {
  39643. if (targetTexture) {
  39644. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  39645. }
  39646. else {
  39647. engine.restoreDefaultFramebuffer();
  39648. }
  39649. }
  39650. var pp = postProcesses[index];
  39651. var effect = pp.apply();
  39652. if (effect) {
  39653. pp.onBeforeRenderObservable.notifyObservers(effect);
  39654. // VBOs
  39655. this._prepareBuffers();
  39656. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39657. // Draw order
  39658. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39659. pp.onAfterRenderObservable.notifyObservers(effect);
  39660. }
  39661. }
  39662. // Restore depth buffer
  39663. engine.setDepthBuffer(true);
  39664. engine.setDepthWrite(true);
  39665. };
  39666. /**
  39667. * Finalize the result of the output of the postprocesses.
  39668. * @param doNotPresent If true the result will not be displayed to the screen.
  39669. * @param targetTexture The target texture to render to.
  39670. * @param faceIndex The index of the face to bind the target texture to.
  39671. * @param postProcesses The array of post processes to render.
  39672. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  39673. */
  39674. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  39675. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  39676. var camera = this._scene.activeCamera;
  39677. if (!camera) {
  39678. return;
  39679. }
  39680. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  39681. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  39682. return;
  39683. }
  39684. var engine = this._scene.getEngine();
  39685. for (var index = 0, len = postProcesses.length; index < len; index++) {
  39686. var pp = postProcesses[index];
  39687. if (index < len - 1) {
  39688. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  39689. }
  39690. else {
  39691. if (targetTexture) {
  39692. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  39693. pp._outputTexture = targetTexture;
  39694. }
  39695. else {
  39696. engine.restoreDefaultFramebuffer();
  39697. pp._outputTexture = null;
  39698. }
  39699. }
  39700. if (doNotPresent) {
  39701. break;
  39702. }
  39703. var effect = pp.apply();
  39704. if (effect) {
  39705. pp.onBeforeRenderObservable.notifyObservers(effect);
  39706. // VBOs
  39707. this._prepareBuffers();
  39708. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39709. // Draw order
  39710. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  39711. pp.onAfterRenderObservable.notifyObservers(effect);
  39712. }
  39713. }
  39714. // Restore states
  39715. engine.setDepthBuffer(true);
  39716. engine.setDepthWrite(true);
  39717. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39718. };
  39719. /**
  39720. * Disposes of the post process manager.
  39721. */
  39722. PostProcessManager.prototype.dispose = function () {
  39723. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39724. if (buffer) {
  39725. buffer.dispose();
  39726. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39727. }
  39728. if (this._indexBuffer) {
  39729. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39730. this._indexBuffer = null;
  39731. }
  39732. };
  39733. return PostProcessManager;
  39734. }());
  39735. BABYLON.PostProcessManager = PostProcessManager;
  39736. })(BABYLON || (BABYLON = {}));
  39737. //# sourceMappingURL=babylon.postProcessManager.js.map
  39738. "use strict";
  39739. var BABYLON;
  39740. (function (BABYLON) {
  39741. /**
  39742. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  39743. */
  39744. var PerformanceMonitor = /** @class */ (function () {
  39745. /**
  39746. * constructor
  39747. * @param frameSampleSize The number of samples required to saturate the sliding window
  39748. */
  39749. function PerformanceMonitor(frameSampleSize) {
  39750. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  39751. this._enabled = true;
  39752. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  39753. }
  39754. /**
  39755. * Samples current frame
  39756. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  39757. */
  39758. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  39759. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  39760. if (!this._enabled)
  39761. return;
  39762. if (this._lastFrameTimeMs != null) {
  39763. var dt = timeMs - this._lastFrameTimeMs;
  39764. this._rollingFrameTime.add(dt);
  39765. }
  39766. this._lastFrameTimeMs = timeMs;
  39767. };
  39768. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  39769. /**
  39770. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39771. * @return Average frame time in milliseconds
  39772. */
  39773. get: function () {
  39774. return this._rollingFrameTime.average;
  39775. },
  39776. enumerable: true,
  39777. configurable: true
  39778. });
  39779. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  39780. /**
  39781. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  39782. * @return Frame time variance in milliseconds squared
  39783. */
  39784. get: function () {
  39785. return this._rollingFrameTime.variance;
  39786. },
  39787. enumerable: true,
  39788. configurable: true
  39789. });
  39790. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  39791. /**
  39792. * Returns the frame time of the most recent frame
  39793. * @return Frame time in milliseconds
  39794. */
  39795. get: function () {
  39796. return this._rollingFrameTime.history(0);
  39797. },
  39798. enumerable: true,
  39799. configurable: true
  39800. });
  39801. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  39802. /**
  39803. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  39804. * @return Framerate in frames per second
  39805. */
  39806. get: function () {
  39807. return 1000.0 / this._rollingFrameTime.average;
  39808. },
  39809. enumerable: true,
  39810. configurable: true
  39811. });
  39812. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  39813. /**
  39814. * Returns the average framerate in frames per second using the most recent frame time
  39815. * @return Framerate in frames per second
  39816. */
  39817. get: function () {
  39818. var history = this._rollingFrameTime.history(0);
  39819. if (history === 0) {
  39820. return 0;
  39821. }
  39822. return 1000.0 / history;
  39823. },
  39824. enumerable: true,
  39825. configurable: true
  39826. });
  39827. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  39828. /**
  39829. * Returns true if enough samples have been taken to completely fill the sliding window
  39830. * @return true if saturated
  39831. */
  39832. get: function () {
  39833. return this._rollingFrameTime.isSaturated();
  39834. },
  39835. enumerable: true,
  39836. configurable: true
  39837. });
  39838. /**
  39839. * Enables contributions to the sliding window sample set
  39840. */
  39841. PerformanceMonitor.prototype.enable = function () {
  39842. this._enabled = true;
  39843. };
  39844. /**
  39845. * Disables contributions to the sliding window sample set
  39846. * Samples will not be interpolated over the disabled period
  39847. */
  39848. PerformanceMonitor.prototype.disable = function () {
  39849. this._enabled = false;
  39850. //clear last sample to avoid interpolating over the disabled period when next enabled
  39851. this._lastFrameTimeMs = null;
  39852. };
  39853. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  39854. /**
  39855. * Returns true if sampling is enabled
  39856. * @return true if enabled
  39857. */
  39858. get: function () {
  39859. return this._enabled;
  39860. },
  39861. enumerable: true,
  39862. configurable: true
  39863. });
  39864. /**
  39865. * Resets performance monitor
  39866. */
  39867. PerformanceMonitor.prototype.reset = function () {
  39868. //clear last sample to avoid interpolating over the disabled period when next enabled
  39869. this._lastFrameTimeMs = null;
  39870. //wipe record
  39871. this._rollingFrameTime.reset();
  39872. };
  39873. return PerformanceMonitor;
  39874. }());
  39875. BABYLON.PerformanceMonitor = PerformanceMonitor;
  39876. /**
  39877. * RollingAverage
  39878. *
  39879. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  39880. */
  39881. var RollingAverage = /** @class */ (function () {
  39882. /**
  39883. * constructor
  39884. * @param length The number of samples required to saturate the sliding window
  39885. */
  39886. function RollingAverage(length) {
  39887. this._samples = new Array(length);
  39888. this.reset();
  39889. }
  39890. /**
  39891. * Adds a sample to the sample set
  39892. * @param v The sample value
  39893. */
  39894. RollingAverage.prototype.add = function (v) {
  39895. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  39896. var delta;
  39897. //we need to check if we've already wrapped round
  39898. if (this.isSaturated()) {
  39899. //remove bottom of stack from mean
  39900. var bottomValue = this._samples[this._pos];
  39901. delta = bottomValue - this.average;
  39902. this.average -= delta / (this._sampleCount - 1);
  39903. this._m2 -= delta * (bottomValue - this.average);
  39904. }
  39905. else {
  39906. this._sampleCount++;
  39907. }
  39908. //add new value to mean
  39909. delta = v - this.average;
  39910. this.average += delta / (this._sampleCount);
  39911. this._m2 += delta * (v - this.average);
  39912. //set the new variance
  39913. this.variance = this._m2 / (this._sampleCount - 1);
  39914. this._samples[this._pos] = v;
  39915. this._pos++;
  39916. this._pos %= this._samples.length; //positive wrap around
  39917. };
  39918. /**
  39919. * Returns previously added values or null if outside of history or outside the sliding window domain
  39920. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  39921. * @return Value previously recorded with add() or null if outside of range
  39922. */
  39923. RollingAverage.prototype.history = function (i) {
  39924. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  39925. return 0;
  39926. }
  39927. var i0 = this._wrapPosition(this._pos - 1.0);
  39928. return this._samples[this._wrapPosition(i0 - i)];
  39929. };
  39930. /**
  39931. * Returns true if enough samples have been taken to completely fill the sliding window
  39932. * @return true if sample-set saturated
  39933. */
  39934. RollingAverage.prototype.isSaturated = function () {
  39935. return this._sampleCount >= this._samples.length;
  39936. };
  39937. /**
  39938. * Resets the rolling average (equivalent to 0 samples taken so far)
  39939. */
  39940. RollingAverage.prototype.reset = function () {
  39941. this.average = 0;
  39942. this.variance = 0;
  39943. this._sampleCount = 0;
  39944. this._pos = 0;
  39945. this._m2 = 0;
  39946. };
  39947. /**
  39948. * Wraps a value around the sample range boundaries
  39949. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  39950. * @return Wrapped position in sample range
  39951. */
  39952. RollingAverage.prototype._wrapPosition = function (i) {
  39953. var max = this._samples.length;
  39954. return ((i % max) + max) % max;
  39955. };
  39956. return RollingAverage;
  39957. }());
  39958. BABYLON.RollingAverage = RollingAverage;
  39959. })(BABYLON || (BABYLON = {}));
  39960. //# sourceMappingURL=babylon.performanceMonitor.js.map
  39961. "use strict";
  39962. var BABYLON;
  39963. (function (BABYLON) {
  39964. /**
  39965. * This groups together the common properties used for image processing either in direct forward pass
  39966. * or through post processing effect depending on the use of the image processing pipeline in your scene
  39967. * or not.
  39968. */
  39969. var ImageProcessingConfiguration = /** @class */ (function () {
  39970. function ImageProcessingConfiguration() {
  39971. /**
  39972. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  39973. */
  39974. this.colorCurves = new BABYLON.ColorCurves();
  39975. this._colorCurvesEnabled = false;
  39976. this._colorGradingEnabled = false;
  39977. this._colorGradingWithGreenDepth = true;
  39978. this._colorGradingBGR = true;
  39979. this._exposure = 1.0;
  39980. this._toneMappingEnabled = false;
  39981. this._contrast = 1.0;
  39982. /**
  39983. * Vignette stretch size.
  39984. */
  39985. this.vignetteStretch = 0;
  39986. /**
  39987. * Vignette centre X Offset.
  39988. */
  39989. this.vignetteCentreX = 0;
  39990. /**
  39991. * Vignette centre Y Offset.
  39992. */
  39993. this.vignetteCentreY = 0;
  39994. /**
  39995. * Vignette weight or intensity of the vignette effect.
  39996. */
  39997. this.vignetteWeight = 1.5;
  39998. /**
  39999. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40000. * if vignetteEnabled is set to true.
  40001. */
  40002. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40003. /**
  40004. * Camera field of view used by the Vignette effect.
  40005. */
  40006. this.vignetteCameraFov = 0.5;
  40007. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40008. this._vignetteEnabled = false;
  40009. this._applyByPostProcess = false;
  40010. this._isEnabled = true;
  40011. /**
  40012. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40013. */
  40014. this.onUpdateParameters = new BABYLON.Observable();
  40015. }
  40016. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40017. /**
  40018. * Gets wether the color curves effect is enabled.
  40019. */
  40020. get: function () {
  40021. return this._colorCurvesEnabled;
  40022. },
  40023. /**
  40024. * Sets wether the color curves effect is enabled.
  40025. */
  40026. set: function (value) {
  40027. if (this._colorCurvesEnabled === value) {
  40028. return;
  40029. }
  40030. this._colorCurvesEnabled = value;
  40031. this._updateParameters();
  40032. },
  40033. enumerable: true,
  40034. configurable: true
  40035. });
  40036. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40037. /**
  40038. * Gets wether the color grading effect is enabled.
  40039. */
  40040. get: function () {
  40041. return this._colorGradingEnabled;
  40042. },
  40043. /**
  40044. * Sets wether the color grading effect is enabled.
  40045. */
  40046. set: function (value) {
  40047. if (this._colorGradingEnabled === value) {
  40048. return;
  40049. }
  40050. this._colorGradingEnabled = value;
  40051. this._updateParameters();
  40052. },
  40053. enumerable: true,
  40054. configurable: true
  40055. });
  40056. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40057. /**
  40058. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40059. */
  40060. get: function () {
  40061. return this._colorGradingWithGreenDepth;
  40062. },
  40063. /**
  40064. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40065. */
  40066. set: function (value) {
  40067. if (this._colorGradingWithGreenDepth === value) {
  40068. return;
  40069. }
  40070. this._colorGradingWithGreenDepth = value;
  40071. this._updateParameters();
  40072. },
  40073. enumerable: true,
  40074. configurable: true
  40075. });
  40076. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40077. /**
  40078. * Gets wether the color grading texture contains BGR values.
  40079. */
  40080. get: function () {
  40081. return this._colorGradingBGR;
  40082. },
  40083. /**
  40084. * Sets wether the color grading texture contains BGR values.
  40085. */
  40086. set: function (value) {
  40087. if (this._colorGradingBGR === value) {
  40088. return;
  40089. }
  40090. this._colorGradingBGR = value;
  40091. this._updateParameters();
  40092. },
  40093. enumerable: true,
  40094. configurable: true
  40095. });
  40096. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40097. /**
  40098. * Gets the Exposure used in the effect.
  40099. */
  40100. get: function () {
  40101. return this._exposure;
  40102. },
  40103. /**
  40104. * Sets the Exposure used in the effect.
  40105. */
  40106. set: function (value) {
  40107. if (this._exposure === value) {
  40108. return;
  40109. }
  40110. this._exposure = value;
  40111. this._updateParameters();
  40112. },
  40113. enumerable: true,
  40114. configurable: true
  40115. });
  40116. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40117. /**
  40118. * Gets wether the tone mapping effect is enabled.
  40119. */
  40120. get: function () {
  40121. return this._toneMappingEnabled;
  40122. },
  40123. /**
  40124. * Sets wether the tone mapping effect is enabled.
  40125. */
  40126. set: function (value) {
  40127. if (this._toneMappingEnabled === value) {
  40128. return;
  40129. }
  40130. this._toneMappingEnabled = value;
  40131. this._updateParameters();
  40132. },
  40133. enumerable: true,
  40134. configurable: true
  40135. });
  40136. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40137. /**
  40138. * Gets the contrast used in the effect.
  40139. */
  40140. get: function () {
  40141. return this._contrast;
  40142. },
  40143. /**
  40144. * Sets the contrast used in the effect.
  40145. */
  40146. set: function (value) {
  40147. if (this._contrast === value) {
  40148. return;
  40149. }
  40150. this._contrast = value;
  40151. this._updateParameters();
  40152. },
  40153. enumerable: true,
  40154. configurable: true
  40155. });
  40156. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40157. /**
  40158. * Gets the vignette blend mode allowing different kind of effect.
  40159. */
  40160. get: function () {
  40161. return this._vignetteBlendMode;
  40162. },
  40163. /**
  40164. * Sets the vignette blend mode allowing different kind of effect.
  40165. */
  40166. set: function (value) {
  40167. if (this._vignetteBlendMode === value) {
  40168. return;
  40169. }
  40170. this._vignetteBlendMode = value;
  40171. this._updateParameters();
  40172. },
  40173. enumerable: true,
  40174. configurable: true
  40175. });
  40176. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40177. /**
  40178. * Gets wether the vignette effect is enabled.
  40179. */
  40180. get: function () {
  40181. return this._vignetteEnabled;
  40182. },
  40183. /**
  40184. * Sets wether the vignette effect is enabled.
  40185. */
  40186. set: function (value) {
  40187. if (this._vignetteEnabled === value) {
  40188. return;
  40189. }
  40190. this._vignetteEnabled = value;
  40191. this._updateParameters();
  40192. },
  40193. enumerable: true,
  40194. configurable: true
  40195. });
  40196. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40197. /**
  40198. * Gets wether the image processing is applied through a post process or not.
  40199. */
  40200. get: function () {
  40201. return this._applyByPostProcess;
  40202. },
  40203. /**
  40204. * Sets wether the image processing is applied through a post process or not.
  40205. */
  40206. set: function (value) {
  40207. if (this._applyByPostProcess === value) {
  40208. return;
  40209. }
  40210. this._applyByPostProcess = value;
  40211. this._updateParameters();
  40212. },
  40213. enumerable: true,
  40214. configurable: true
  40215. });
  40216. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40217. /**
  40218. * Gets wether the image processing is enabled or not.
  40219. */
  40220. get: function () {
  40221. return this._isEnabled;
  40222. },
  40223. /**
  40224. * Sets wether the image processing is enabled or not.
  40225. */
  40226. set: function (value) {
  40227. if (this._isEnabled === value) {
  40228. return;
  40229. }
  40230. this._isEnabled = value;
  40231. this._updateParameters();
  40232. },
  40233. enumerable: true,
  40234. configurable: true
  40235. });
  40236. /**
  40237. * Method called each time the image processing information changes requires to recompile the effect.
  40238. */
  40239. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40240. this.onUpdateParameters.notifyObservers(this);
  40241. };
  40242. ImageProcessingConfiguration.prototype.getClassName = function () {
  40243. return "ImageProcessingConfiguration";
  40244. };
  40245. /**
  40246. * Prepare the list of uniforms associated with the Image Processing effects.
  40247. * @param uniformsList The list of uniforms used in the effect
  40248. * @param defines the list of defines currently in use
  40249. */
  40250. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40251. if (defines.EXPOSURE) {
  40252. uniforms.push("exposureLinear");
  40253. }
  40254. if (defines.CONTRAST) {
  40255. uniforms.push("contrast");
  40256. }
  40257. if (defines.COLORGRADING) {
  40258. uniforms.push("colorTransformSettings");
  40259. }
  40260. if (defines.VIGNETTE) {
  40261. uniforms.push("vInverseScreenSize");
  40262. uniforms.push("vignetteSettings1");
  40263. uniforms.push("vignetteSettings2");
  40264. }
  40265. if (defines.COLORCURVES) {
  40266. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40267. }
  40268. };
  40269. /**
  40270. * Prepare the list of samplers associated with the Image Processing effects.
  40271. * @param uniformsList The list of uniforms used in the effect
  40272. * @param defines the list of defines currently in use
  40273. */
  40274. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40275. if (defines.COLORGRADING) {
  40276. samplersList.push("txColorTransform");
  40277. }
  40278. };
  40279. /**
  40280. * Prepare the list of defines associated to the shader.
  40281. * @param defines the list of defines to complete
  40282. */
  40283. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40284. if (forPostProcess === void 0) { forPostProcess = false; }
  40285. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40286. defines.VIGNETTE = false;
  40287. defines.TONEMAPPING = false;
  40288. defines.CONTRAST = false;
  40289. defines.EXPOSURE = false;
  40290. defines.COLORCURVES = false;
  40291. defines.COLORGRADING = false;
  40292. defines.COLORGRADING3D = false;
  40293. defines.IMAGEPROCESSING = false;
  40294. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40295. return;
  40296. }
  40297. defines.VIGNETTE = this.vignetteEnabled;
  40298. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40299. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40300. defines.TONEMAPPING = this.toneMappingEnabled;
  40301. defines.CONTRAST = (this.contrast !== 1.0);
  40302. defines.EXPOSURE = (this.exposure !== 1.0);
  40303. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40304. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40305. if (defines.COLORGRADING) {
  40306. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40307. }
  40308. else {
  40309. defines.COLORGRADING3D = false;
  40310. }
  40311. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40312. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40313. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40314. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40315. };
  40316. /**
  40317. * Returns true if all the image processing information are ready.
  40318. */
  40319. ImageProcessingConfiguration.prototype.isReady = function () {
  40320. // Color Grading texure can not be none blocking.
  40321. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40322. };
  40323. /**
  40324. * Binds the image processing to the shader.
  40325. * @param effect The effect to bind to
  40326. */
  40327. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40328. if (aspectRatio === void 0) { aspectRatio = 1; }
  40329. // Color Curves
  40330. if (this._colorCurvesEnabled && this.colorCurves) {
  40331. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40332. }
  40333. // Vignette
  40334. if (this._vignetteEnabled) {
  40335. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40336. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40337. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40338. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40339. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40340. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40341. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40342. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40343. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40344. var vignettePower = -2.0 * this.vignetteWeight;
  40345. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40346. }
  40347. // Exposure
  40348. effect.setFloat("exposureLinear", this.exposure);
  40349. // Contrast
  40350. effect.setFloat("contrast", this.contrast);
  40351. // Color transform settings
  40352. if (this.colorGradingTexture) {
  40353. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40354. var textureSize = this.colorGradingTexture.getSize().height;
  40355. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40356. 0.5 / textureSize, // textureOffset
  40357. textureSize, // textureSize
  40358. this.colorGradingTexture.level // weight
  40359. );
  40360. }
  40361. };
  40362. /**
  40363. * Clones the current image processing instance.
  40364. * @return The cloned image processing
  40365. */
  40366. ImageProcessingConfiguration.prototype.clone = function () {
  40367. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40368. };
  40369. /**
  40370. * Serializes the current image processing instance to a json representation.
  40371. * @return a JSON representation
  40372. */
  40373. ImageProcessingConfiguration.prototype.serialize = function () {
  40374. return BABYLON.SerializationHelper.Serialize(this);
  40375. };
  40376. /**
  40377. * Parses the image processing from a json representation.
  40378. * @param source the JSON source to parse
  40379. * @return The parsed image processing
  40380. */
  40381. ImageProcessingConfiguration.Parse = function (source) {
  40382. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40383. };
  40384. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40385. /**
  40386. * Used to apply the vignette as a mix with the pixel color.
  40387. */
  40388. get: function () {
  40389. return this._VIGNETTEMODE_MULTIPLY;
  40390. },
  40391. enumerable: true,
  40392. configurable: true
  40393. });
  40394. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40395. /**
  40396. * Used to apply the vignette as a replacement of the pixel color.
  40397. */
  40398. get: function () {
  40399. return this._VIGNETTEMODE_OPAQUE;
  40400. },
  40401. enumerable: true,
  40402. configurable: true
  40403. });
  40404. // Static constants associated to the image processing.
  40405. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40406. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40407. __decorate([
  40408. BABYLON.serializeAsColorCurves()
  40409. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40410. __decorate([
  40411. BABYLON.serialize()
  40412. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40413. __decorate([
  40414. BABYLON.serializeAsTexture()
  40415. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40416. __decorate([
  40417. BABYLON.serialize()
  40418. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40419. __decorate([
  40420. BABYLON.serialize()
  40421. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40422. __decorate([
  40423. BABYLON.serialize()
  40424. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40425. __decorate([
  40426. BABYLON.serialize()
  40427. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40428. __decorate([
  40429. BABYLON.serialize()
  40430. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40431. __decorate([
  40432. BABYLON.serialize()
  40433. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40434. __decorate([
  40435. BABYLON.serialize()
  40436. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40437. __decorate([
  40438. BABYLON.serialize()
  40439. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40440. __decorate([
  40441. BABYLON.serialize()
  40442. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40443. __decorate([
  40444. BABYLON.serialize()
  40445. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40446. __decorate([
  40447. BABYLON.serializeAsColor4()
  40448. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40449. __decorate([
  40450. BABYLON.serialize()
  40451. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40452. __decorate([
  40453. BABYLON.serialize()
  40454. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40455. __decorate([
  40456. BABYLON.serialize()
  40457. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40458. __decorate([
  40459. BABYLON.serialize()
  40460. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40461. __decorate([
  40462. BABYLON.serialize()
  40463. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40464. return ImageProcessingConfiguration;
  40465. }());
  40466. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40467. })(BABYLON || (BABYLON = {}));
  40468. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40469. "use strict";
  40470. var BABYLON;
  40471. (function (BABYLON) {
  40472. /**
  40473. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40474. * It can help converting any input color in a desired output one. This can then be used to create effects
  40475. * from sepia, black and white to sixties or futuristic rendering...
  40476. *
  40477. * The only supported format is currently 3dl.
  40478. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40479. */
  40480. var ColorGradingTexture = /** @class */ (function (_super) {
  40481. __extends(ColorGradingTexture, _super);
  40482. /**
  40483. * Instantiates a ColorGradingTexture from the following parameters.
  40484. *
  40485. * @param url The location of the color gradind data (currently only supporting 3dl)
  40486. * @param scene The scene the texture will be used in
  40487. */
  40488. function ColorGradingTexture(url, scene) {
  40489. var _this = _super.call(this, scene) || this;
  40490. if (!url) {
  40491. return _this;
  40492. }
  40493. _this._engine = scene.getEngine();
  40494. _this._textureMatrix = BABYLON.Matrix.Identity();
  40495. _this.name = url;
  40496. _this.url = url;
  40497. _this.hasAlpha = false;
  40498. _this.isCube = false;
  40499. _this.is3D = _this._engine.webGLVersion > 1;
  40500. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40501. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40502. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40503. _this.anisotropicFilteringLevel = 1;
  40504. _this._texture = _this._getFromCache(url, true);
  40505. if (!_this._texture) {
  40506. if (!scene.useDelayedTextureLoading) {
  40507. _this.loadTexture();
  40508. }
  40509. else {
  40510. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40511. }
  40512. }
  40513. return _this;
  40514. }
  40515. /**
  40516. * Returns the texture matrix used in most of the material.
  40517. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  40518. */
  40519. ColorGradingTexture.prototype.getTextureMatrix = function () {
  40520. return this._textureMatrix;
  40521. };
  40522. /**
  40523. * Occurs when the file being loaded is a .3dl LUT file.
  40524. */
  40525. ColorGradingTexture.prototype.load3dlTexture = function () {
  40526. var engine = this._engine;
  40527. var texture;
  40528. if (engine.webGLVersion === 1) {
  40529. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40530. }
  40531. else {
  40532. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40533. }
  40534. this._texture = texture;
  40535. var callback = function (text) {
  40536. if (typeof text !== "string") {
  40537. return;
  40538. }
  40539. var data = null;
  40540. var tempData = null;
  40541. var line;
  40542. var lines = text.split('\n');
  40543. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  40544. var maxColor = 0;
  40545. for (var i = 0; i < lines.length; i++) {
  40546. line = lines[i];
  40547. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  40548. continue;
  40549. if (line.indexOf('#') === 0)
  40550. continue;
  40551. var words = line.split(" ");
  40552. if (size === 0) {
  40553. // Number of space + one
  40554. size = words.length;
  40555. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  40556. tempData = new Float32Array(size * size * size * 4);
  40557. continue;
  40558. }
  40559. if (size != 0) {
  40560. var r = Math.max(parseInt(words[0]), 0);
  40561. var g = Math.max(parseInt(words[1]), 0);
  40562. var b = Math.max(parseInt(words[2]), 0);
  40563. maxColor = Math.max(r, maxColor);
  40564. maxColor = Math.max(g, maxColor);
  40565. maxColor = Math.max(b, maxColor);
  40566. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  40567. if (tempData) {
  40568. tempData[pixelStorageIndex + 0] = r;
  40569. tempData[pixelStorageIndex + 1] = g;
  40570. tempData[pixelStorageIndex + 2] = b;
  40571. }
  40572. pixelIndexSlice++;
  40573. if (pixelIndexSlice % size == 0) {
  40574. pixelIndexH++;
  40575. pixelIndexSlice = 0;
  40576. if (pixelIndexH % size == 0) {
  40577. pixelIndexW++;
  40578. pixelIndexH = 0;
  40579. }
  40580. }
  40581. }
  40582. }
  40583. if (tempData && data) {
  40584. for (var i = 0; i < tempData.length; i++) {
  40585. if (i > 0 && (i + 1) % 4 === 0) {
  40586. data[i] = 255;
  40587. }
  40588. else {
  40589. var value = tempData[i];
  40590. data[i] = (value / maxColor * 255);
  40591. }
  40592. }
  40593. }
  40594. if (texture.is3D) {
  40595. texture.updateSize(size, size, size);
  40596. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40597. }
  40598. else {
  40599. texture.updateSize(size * size, size);
  40600. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  40601. }
  40602. };
  40603. var scene = this.getScene();
  40604. if (scene) {
  40605. scene._loadFile(this.url, callback);
  40606. }
  40607. else {
  40608. this._engine._loadFile(this.url, callback);
  40609. }
  40610. return this._texture;
  40611. };
  40612. /**
  40613. * Starts the loading process of the texture.
  40614. */
  40615. ColorGradingTexture.prototype.loadTexture = function () {
  40616. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  40617. this.load3dlTexture();
  40618. }
  40619. };
  40620. /**
  40621. * Clones the color gradind texture.
  40622. */
  40623. ColorGradingTexture.prototype.clone = function () {
  40624. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  40625. // Base texture
  40626. newTexture.level = this.level;
  40627. return newTexture;
  40628. };
  40629. /**
  40630. * Called during delayed load for textures.
  40631. */
  40632. ColorGradingTexture.prototype.delayLoad = function () {
  40633. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40634. return;
  40635. }
  40636. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40637. this._texture = this._getFromCache(this.url, true);
  40638. if (!this._texture) {
  40639. this.loadTexture();
  40640. }
  40641. };
  40642. /**
  40643. * Parses a color grading texture serialized by Babylon.
  40644. * @param parsedTexture The texture information being parsedTexture
  40645. * @param scene The scene to load the texture in
  40646. * @param rootUrl The root url of the data assets to load
  40647. * @return A color gradind texture
  40648. */
  40649. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40650. var texture = null;
  40651. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  40652. texture = new ColorGradingTexture(parsedTexture.name, scene);
  40653. texture.name = parsedTexture.name;
  40654. texture.level = parsedTexture.level;
  40655. }
  40656. return texture;
  40657. };
  40658. /**
  40659. * Serializes the LUT texture to json format.
  40660. */
  40661. ColorGradingTexture.prototype.serialize = function () {
  40662. if (!this.name) {
  40663. return null;
  40664. }
  40665. var serializationObject = {};
  40666. serializationObject.name = this.name;
  40667. serializationObject.level = this.level;
  40668. serializationObject.customType = "BABYLON.ColorGradingTexture";
  40669. return serializationObject;
  40670. };
  40671. /**
  40672. * Empty line regex stored for GC.
  40673. */
  40674. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  40675. return ColorGradingTexture;
  40676. }(BABYLON.BaseTexture));
  40677. BABYLON.ColorGradingTexture = ColorGradingTexture;
  40678. })(BABYLON || (BABYLON = {}));
  40679. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  40680. "use strict";
  40681. var BABYLON;
  40682. (function (BABYLON) {
  40683. /**
  40684. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40685. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40686. * 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;
  40687. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40688. */
  40689. var ColorCurves = /** @class */ (function () {
  40690. function ColorCurves() {
  40691. this._dirty = true;
  40692. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  40693. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  40694. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40695. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  40696. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  40697. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  40698. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  40699. this._globalHue = 30;
  40700. this._globalDensity = 0;
  40701. this._globalSaturation = 0;
  40702. this._globalExposure = 0;
  40703. this._highlightsHue = 30;
  40704. this._highlightsDensity = 0;
  40705. this._highlightsSaturation = 0;
  40706. this._highlightsExposure = 0;
  40707. this._midtonesHue = 30;
  40708. this._midtonesDensity = 0;
  40709. this._midtonesSaturation = 0;
  40710. this._midtonesExposure = 0;
  40711. this._shadowsHue = 30;
  40712. this._shadowsDensity = 0;
  40713. this._shadowsSaturation = 0;
  40714. this._shadowsExposure = 0;
  40715. }
  40716. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  40717. /**
  40718. * Gets the global Hue value.
  40719. * 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).
  40720. */
  40721. get: function () {
  40722. return this._globalHue;
  40723. },
  40724. /**
  40725. * Sets the global Hue value.
  40726. * 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).
  40727. */
  40728. set: function (value) {
  40729. this._globalHue = value;
  40730. this._dirty = true;
  40731. },
  40732. enumerable: true,
  40733. configurable: true
  40734. });
  40735. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  40736. /**
  40737. * Gets the global Density value.
  40738. * 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.
  40739. * Values less than zero provide a filter of opposite hue.
  40740. */
  40741. get: function () {
  40742. return this._globalDensity;
  40743. },
  40744. /**
  40745. * Sets the global Density value.
  40746. * 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.
  40747. * Values less than zero provide a filter of opposite hue.
  40748. */
  40749. set: function (value) {
  40750. this._globalDensity = value;
  40751. this._dirty = true;
  40752. },
  40753. enumerable: true,
  40754. configurable: true
  40755. });
  40756. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  40757. /**
  40758. * Gets the global Saturation value.
  40759. * 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.
  40760. */
  40761. get: function () {
  40762. return this._globalSaturation;
  40763. },
  40764. /**
  40765. * Sets the global Saturation value.
  40766. * 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.
  40767. */
  40768. set: function (value) {
  40769. this._globalSaturation = value;
  40770. this._dirty = true;
  40771. },
  40772. enumerable: true,
  40773. configurable: true
  40774. });
  40775. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  40776. /**
  40777. * Gets the highlights Hue value.
  40778. * 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).
  40779. */
  40780. get: function () {
  40781. return this._highlightsHue;
  40782. },
  40783. /**
  40784. * Sets the highlights Hue value.
  40785. * 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).
  40786. */
  40787. set: function (value) {
  40788. this._highlightsHue = value;
  40789. this._dirty = true;
  40790. },
  40791. enumerable: true,
  40792. configurable: true
  40793. });
  40794. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  40795. /**
  40796. * Gets the highlights Density value.
  40797. * 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.
  40798. * Values less than zero provide a filter of opposite hue.
  40799. */
  40800. get: function () {
  40801. return this._highlightsDensity;
  40802. },
  40803. /**
  40804. * Sets the highlights Density value.
  40805. * 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.
  40806. * Values less than zero provide a filter of opposite hue.
  40807. */
  40808. set: function (value) {
  40809. this._highlightsDensity = value;
  40810. this._dirty = true;
  40811. },
  40812. enumerable: true,
  40813. configurable: true
  40814. });
  40815. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  40816. /**
  40817. * Gets the highlights Saturation value.
  40818. * 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.
  40819. */
  40820. get: function () {
  40821. return this._highlightsSaturation;
  40822. },
  40823. /**
  40824. * Sets the highlights Saturation value.
  40825. * 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.
  40826. */
  40827. set: function (value) {
  40828. this._highlightsSaturation = value;
  40829. this._dirty = true;
  40830. },
  40831. enumerable: true,
  40832. configurable: true
  40833. });
  40834. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  40835. /**
  40836. * Gets the highlights Exposure value.
  40837. * 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.
  40838. */
  40839. get: function () {
  40840. return this._highlightsExposure;
  40841. },
  40842. /**
  40843. * Sets the highlights Exposure value.
  40844. * 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.
  40845. */
  40846. set: function (value) {
  40847. this._highlightsExposure = value;
  40848. this._dirty = true;
  40849. },
  40850. enumerable: true,
  40851. configurable: true
  40852. });
  40853. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  40854. /**
  40855. * Gets the midtones Hue value.
  40856. * 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).
  40857. */
  40858. get: function () {
  40859. return this._midtonesHue;
  40860. },
  40861. /**
  40862. * Sets the midtones Hue value.
  40863. * 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).
  40864. */
  40865. set: function (value) {
  40866. this._midtonesHue = value;
  40867. this._dirty = true;
  40868. },
  40869. enumerable: true,
  40870. configurable: true
  40871. });
  40872. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  40873. /**
  40874. * Gets the midtones Density value.
  40875. * 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.
  40876. * Values less than zero provide a filter of opposite hue.
  40877. */
  40878. get: function () {
  40879. return this._midtonesDensity;
  40880. },
  40881. /**
  40882. * Sets the midtones Density value.
  40883. * 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.
  40884. * Values less than zero provide a filter of opposite hue.
  40885. */
  40886. set: function (value) {
  40887. this._midtonesDensity = value;
  40888. this._dirty = true;
  40889. },
  40890. enumerable: true,
  40891. configurable: true
  40892. });
  40893. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  40894. /**
  40895. * Gets the midtones Saturation value.
  40896. * 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.
  40897. */
  40898. get: function () {
  40899. return this._midtonesSaturation;
  40900. },
  40901. /**
  40902. * Sets the midtones Saturation value.
  40903. * 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.
  40904. */
  40905. set: function (value) {
  40906. this._midtonesSaturation = value;
  40907. this._dirty = true;
  40908. },
  40909. enumerable: true,
  40910. configurable: true
  40911. });
  40912. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  40913. /**
  40914. * Gets the midtones Exposure value.
  40915. * 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.
  40916. */
  40917. get: function () {
  40918. return this._midtonesExposure;
  40919. },
  40920. /**
  40921. * Sets the midtones Exposure value.
  40922. * 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.
  40923. */
  40924. set: function (value) {
  40925. this._midtonesExposure = value;
  40926. this._dirty = true;
  40927. },
  40928. enumerable: true,
  40929. configurable: true
  40930. });
  40931. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  40932. /**
  40933. * Gets the shadows Hue value.
  40934. * 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).
  40935. */
  40936. get: function () {
  40937. return this._shadowsHue;
  40938. },
  40939. /**
  40940. * Sets the shadows Hue value.
  40941. * 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).
  40942. */
  40943. set: function (value) {
  40944. this._shadowsHue = value;
  40945. this._dirty = true;
  40946. },
  40947. enumerable: true,
  40948. configurable: true
  40949. });
  40950. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  40951. /**
  40952. * Gets the shadows Density value.
  40953. * 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.
  40954. * Values less than zero provide a filter of opposite hue.
  40955. */
  40956. get: function () {
  40957. return this._shadowsDensity;
  40958. },
  40959. /**
  40960. * Sets the shadows Density value.
  40961. * 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.
  40962. * Values less than zero provide a filter of opposite hue.
  40963. */
  40964. set: function (value) {
  40965. this._shadowsDensity = value;
  40966. this._dirty = true;
  40967. },
  40968. enumerable: true,
  40969. configurable: true
  40970. });
  40971. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  40972. /**
  40973. * Gets the shadows Saturation value.
  40974. * 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.
  40975. */
  40976. get: function () {
  40977. return this._shadowsSaturation;
  40978. },
  40979. /**
  40980. * Sets the shadows Saturation value.
  40981. * 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.
  40982. */
  40983. set: function (value) {
  40984. this._shadowsSaturation = value;
  40985. this._dirty = true;
  40986. },
  40987. enumerable: true,
  40988. configurable: true
  40989. });
  40990. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  40991. /**
  40992. * Gets the shadows Exposure value.
  40993. * 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.
  40994. */
  40995. get: function () {
  40996. return this._shadowsExposure;
  40997. },
  40998. /**
  40999. * Sets the shadows Exposure value.
  41000. * 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.
  41001. */
  41002. set: function (value) {
  41003. this._shadowsExposure = value;
  41004. this._dirty = true;
  41005. },
  41006. enumerable: true,
  41007. configurable: true
  41008. });
  41009. ColorCurves.prototype.getClassName = function () {
  41010. return "ColorCurves";
  41011. };
  41012. /**
  41013. * Binds the color curves to the shader.
  41014. * @param colorCurves The color curve to bind
  41015. * @param effect The effect to bind to
  41016. */
  41017. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41018. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41019. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41020. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41021. if (colorCurves._dirty) {
  41022. colorCurves._dirty = false;
  41023. // Fill in global info.
  41024. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41025. // Compute highlights info.
  41026. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41027. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41028. // Compute midtones info.
  41029. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41030. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41031. // Compute shadows info.
  41032. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41033. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41034. // Compute deltas (neutral is midtones).
  41035. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41036. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41037. }
  41038. if (effect) {
  41039. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41040. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41041. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41042. }
  41043. };
  41044. /**
  41045. * Prepare the list of uniforms associated with the ColorCurves effects.
  41046. * @param uniformsList The list of uniforms used in the effect
  41047. */
  41048. ColorCurves.PrepareUniforms = function (uniformsList) {
  41049. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41050. };
  41051. /**
  41052. * Returns color grading data based on a hue, density, saturation and exposure value.
  41053. * @param filterHue The hue of the color filter.
  41054. * @param filterDensity The density of the color filter.
  41055. * @param saturation The saturation.
  41056. * @param exposure The exposure.
  41057. * @param result The result data container.
  41058. */
  41059. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41060. if (hue == null) {
  41061. return;
  41062. }
  41063. hue = ColorCurves.clamp(hue, 0, 360);
  41064. density = ColorCurves.clamp(density, -100, 100);
  41065. saturation = ColorCurves.clamp(saturation, -100, 100);
  41066. exposure = ColorCurves.clamp(exposure, -100, 100);
  41067. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41068. // so that the maximum filter density is only 50% control. This provides fine control
  41069. // for small values and reasonable range.
  41070. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41071. density *= 0.5;
  41072. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41073. if (density < 0) {
  41074. density *= -1;
  41075. hue = (hue + 180) % 360;
  41076. }
  41077. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41078. result.scaleToRef(2, result);
  41079. result.a = 1 + 0.01 * saturation;
  41080. };
  41081. /**
  41082. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41083. * @param value The input slider value in range [-100,100].
  41084. * @returns Adjusted value.
  41085. */
  41086. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41087. value /= 100;
  41088. var x = Math.abs(value);
  41089. x = Math.pow(x, 2);
  41090. if (value < 0) {
  41091. x *= -1;
  41092. }
  41093. x *= 100;
  41094. return x;
  41095. };
  41096. /**
  41097. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41098. * @param hue The hue (H) input.
  41099. * @param saturation The saturation (S) input.
  41100. * @param brightness The brightness (B) input.
  41101. * @result An RGBA color represented as Vector4.
  41102. */
  41103. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41104. var h = ColorCurves.clamp(hue, 0, 360);
  41105. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41106. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41107. if (s === 0) {
  41108. result.r = v;
  41109. result.g = v;
  41110. result.b = v;
  41111. }
  41112. else {
  41113. // sector 0 to 5
  41114. h /= 60;
  41115. var i = Math.floor(h);
  41116. // fractional part of h
  41117. var f = h - i;
  41118. var p = v * (1 - s);
  41119. var q = v * (1 - s * f);
  41120. var t = v * (1 - s * (1 - f));
  41121. switch (i) {
  41122. case 0:
  41123. result.r = v;
  41124. result.g = t;
  41125. result.b = p;
  41126. break;
  41127. case 1:
  41128. result.r = q;
  41129. result.g = v;
  41130. result.b = p;
  41131. break;
  41132. case 2:
  41133. result.r = p;
  41134. result.g = v;
  41135. result.b = t;
  41136. break;
  41137. case 3:
  41138. result.r = p;
  41139. result.g = q;
  41140. result.b = v;
  41141. break;
  41142. case 4:
  41143. result.r = t;
  41144. result.g = p;
  41145. result.b = v;
  41146. break;
  41147. default:// case 5:
  41148. result.r = v;
  41149. result.g = p;
  41150. result.b = q;
  41151. break;
  41152. }
  41153. }
  41154. result.a = 1;
  41155. };
  41156. /**
  41157. * Returns a value clamped between min and max
  41158. * @param value The value to clamp
  41159. * @param min The minimum of value
  41160. * @param max The maximum of value
  41161. * @returns The clamped value.
  41162. */
  41163. ColorCurves.clamp = function (value, min, max) {
  41164. return Math.min(Math.max(value, min), max);
  41165. };
  41166. /**
  41167. * Clones the current color curve instance.
  41168. * @return The cloned curves
  41169. */
  41170. ColorCurves.prototype.clone = function () {
  41171. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41172. };
  41173. /**
  41174. * Serializes the current color curve instance to a json representation.
  41175. * @return a JSON representation
  41176. */
  41177. ColorCurves.prototype.serialize = function () {
  41178. return BABYLON.SerializationHelper.Serialize(this);
  41179. };
  41180. /**
  41181. * Parses the color curve from a json representation.
  41182. * @param source the JSON source to parse
  41183. * @return The parsed curves
  41184. */
  41185. ColorCurves.Parse = function (source) {
  41186. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41187. };
  41188. __decorate([
  41189. BABYLON.serialize()
  41190. ], ColorCurves.prototype, "_globalHue", void 0);
  41191. __decorate([
  41192. BABYLON.serialize()
  41193. ], ColorCurves.prototype, "_globalDensity", void 0);
  41194. __decorate([
  41195. BABYLON.serialize()
  41196. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41197. __decorate([
  41198. BABYLON.serialize()
  41199. ], ColorCurves.prototype, "_globalExposure", void 0);
  41200. __decorate([
  41201. BABYLON.serialize()
  41202. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41203. __decorate([
  41204. BABYLON.serialize()
  41205. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41206. __decorate([
  41207. BABYLON.serialize()
  41208. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41209. __decorate([
  41210. BABYLON.serialize()
  41211. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41212. __decorate([
  41213. BABYLON.serialize()
  41214. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41215. __decorate([
  41216. BABYLON.serialize()
  41217. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41218. __decorate([
  41219. BABYLON.serialize()
  41220. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41221. __decorate([
  41222. BABYLON.serialize()
  41223. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41224. return ColorCurves;
  41225. }());
  41226. BABYLON.ColorCurves = ColorCurves;
  41227. })(BABYLON || (BABYLON = {}));
  41228. //# sourceMappingURL=babylon.colorCurves.js.map
  41229. "use strict";
  41230. //# sourceMappingURL=babylon.behavior.js.map
  41231. "use strict";
  41232. var BABYLON;
  41233. (function (BABYLON) {
  41234. /**
  41235. * "Static Class" containing the most commonly used helper while dealing with material for
  41236. * rendering purpose.
  41237. *
  41238. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41239. *
  41240. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41241. */
  41242. var MaterialHelper = /** @class */ (function () {
  41243. function MaterialHelper() {
  41244. }
  41245. /**
  41246. * Bind the current view position to an effect.
  41247. * @param effect The effect to be bound
  41248. * @param scene The scene the eyes position is used from
  41249. */
  41250. MaterialHelper.BindEyePosition = function (effect, scene) {
  41251. if (scene._forcedViewPosition) {
  41252. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41253. return;
  41254. }
  41255. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41256. };
  41257. /**
  41258. * Helps preparing the defines values about the UVs in used in the effect.
  41259. * UVs are shared as much as we can accross chanels in the shaders.
  41260. * @param texture The texture we are preparing the UVs for
  41261. * @param defines The defines to update
  41262. * @param key The chanel key "diffuse", "specular"... used in the shader
  41263. */
  41264. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41265. defines._needUVs = true;
  41266. defines[key] = true;
  41267. if (texture.getTextureMatrix().isIdentity(true)) {
  41268. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41269. if (texture.coordinatesIndex === 0) {
  41270. defines["MAINUV1"] = true;
  41271. }
  41272. else {
  41273. defines["MAINUV2"] = true;
  41274. }
  41275. }
  41276. else {
  41277. defines[key + "DIRECTUV"] = 0;
  41278. }
  41279. };
  41280. /**
  41281. * Binds a texture matrix value to its corrsponding uniform
  41282. * @param texture The texture to bind the matrix for
  41283. * @param uniformBuffer The uniform buffer receivin the data
  41284. * @param key The chanel key "diffuse", "specular"... used in the shader
  41285. */
  41286. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41287. var matrix = texture.getTextureMatrix();
  41288. if (!matrix.isIdentity(true)) {
  41289. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41290. }
  41291. };
  41292. /**
  41293. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41294. * @param mesh defines the current mesh
  41295. * @param scene defines the current scene
  41296. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41297. * @param pointsCloud defines if point cloud rendering has to be turned on
  41298. * @param fogEnabled defines if fog has to be turned on
  41299. * @param alphaTest defines if alpha testing has to be turned on
  41300. * @param defines defines the current list of defines
  41301. */
  41302. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41303. if (defines._areMiscDirty) {
  41304. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41305. defines["POINTSIZE"] = pointsCloud;
  41306. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41307. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41308. defines["ALPHATEST"] = alphaTest;
  41309. }
  41310. };
  41311. /**
  41312. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41313. * @param scene defines the current scene
  41314. * @param engine defines the current engine
  41315. * @param defines specifies the list of active defines
  41316. * @param useInstances defines if instances have to be turned on
  41317. * @param useClipPlane defines if clip plane have to be turned on
  41318. */
  41319. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41320. if (useClipPlane === void 0) { useClipPlane = null; }
  41321. var changed = false;
  41322. if (useClipPlane == null) {
  41323. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41324. }
  41325. if (defines["CLIPPLANE"] !== useClipPlane) {
  41326. defines["CLIPPLANE"] = useClipPlane;
  41327. changed = true;
  41328. }
  41329. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41330. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41331. changed = true;
  41332. }
  41333. if (defines["INSTANCES"] !== useInstances) {
  41334. defines["INSTANCES"] = useInstances;
  41335. changed = true;
  41336. }
  41337. if (changed) {
  41338. defines.markAsUnprocessed();
  41339. }
  41340. };
  41341. /**
  41342. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41343. * @param mesh The mesh containing the geometry data we will draw
  41344. * @param defines The defines to update
  41345. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41346. * @param useBones Precise whether bones should be used or not (override mesh info)
  41347. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41348. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41349. * @returns false if defines are considered not dirty and have not been checked
  41350. */
  41351. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41352. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41353. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41354. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41355. return false;
  41356. }
  41357. defines._normals = defines._needNormals;
  41358. defines._uvs = defines._needUVs;
  41359. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41360. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41361. defines["TANGENT"] = true;
  41362. }
  41363. if (defines._needUVs) {
  41364. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41365. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41366. }
  41367. else {
  41368. defines["UV1"] = false;
  41369. defines["UV2"] = false;
  41370. }
  41371. if (useVertexColor) {
  41372. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41373. defines["VERTEXCOLOR"] = hasVertexColors;
  41374. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41375. }
  41376. if (useBones) {
  41377. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41378. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41379. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41380. }
  41381. else {
  41382. defines["NUM_BONE_INFLUENCERS"] = 0;
  41383. defines["BonesPerMesh"] = 0;
  41384. }
  41385. }
  41386. if (useMorphTargets) {
  41387. var manager = mesh.morphTargetManager;
  41388. if (manager) {
  41389. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41390. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41391. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41392. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41393. }
  41394. else {
  41395. defines["MORPHTARGETS_TANGENT"] = false;
  41396. defines["MORPHTARGETS_NORMAL"] = false;
  41397. defines["MORPHTARGETS"] = false;
  41398. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41399. }
  41400. }
  41401. return true;
  41402. };
  41403. /**
  41404. * Prepares the defines related to the light information passed in parameter
  41405. * @param scene The scene we are intending to draw
  41406. * @param mesh The mesh the effect is compiling for
  41407. * @param defines The defines to update
  41408. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41409. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41410. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41411. * @returns true if normals will be required for the rest of the effect
  41412. */
  41413. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41414. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41415. if (disableLighting === void 0) { disableLighting = false; }
  41416. if (!defines._areLightsDirty) {
  41417. return defines._needNormals;
  41418. }
  41419. var lightIndex = 0;
  41420. var needNormals = false;
  41421. var needRebuild = false;
  41422. var lightmapMode = false;
  41423. var shadowEnabled = false;
  41424. var specularEnabled = false;
  41425. if (scene.lightsEnabled && !disableLighting) {
  41426. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41427. var light = _a[_i];
  41428. needNormals = true;
  41429. if (defines["LIGHT" + lightIndex] === undefined) {
  41430. needRebuild = true;
  41431. }
  41432. defines["LIGHT" + lightIndex] = true;
  41433. defines["SPOTLIGHT" + lightIndex] = false;
  41434. defines["HEMILIGHT" + lightIndex] = false;
  41435. defines["POINTLIGHT" + lightIndex] = false;
  41436. defines["DIRLIGHT" + lightIndex] = false;
  41437. var type;
  41438. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41439. type = "SPOTLIGHT" + lightIndex;
  41440. var spotLight = light;
  41441. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  41442. }
  41443. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41444. type = "HEMILIGHT" + lightIndex;
  41445. }
  41446. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41447. type = "POINTLIGHT" + lightIndex;
  41448. }
  41449. else {
  41450. type = "DIRLIGHT" + lightIndex;
  41451. }
  41452. defines[type] = true;
  41453. // Specular
  41454. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41455. specularEnabled = true;
  41456. }
  41457. // Shadows
  41458. defines["SHADOW" + lightIndex] = false;
  41459. defines["SHADOWPCF" + lightIndex] = false;
  41460. defines["SHADOWPCSS" + lightIndex] = false;
  41461. defines["SHADOWPOISSON" + lightIndex] = false;
  41462. defines["SHADOWESM" + lightIndex] = false;
  41463. defines["SHADOWCUBE" + lightIndex] = false;
  41464. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41465. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41466. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41467. var shadowGenerator = light.getShadowGenerator();
  41468. if (shadowGenerator) {
  41469. shadowEnabled = true;
  41470. shadowGenerator.prepareDefines(defines, lightIndex);
  41471. }
  41472. }
  41473. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41474. lightmapMode = true;
  41475. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41476. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41477. }
  41478. else {
  41479. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41480. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41481. }
  41482. lightIndex++;
  41483. if (lightIndex === maxSimultaneousLights)
  41484. break;
  41485. }
  41486. }
  41487. defines["SPECULARTERM"] = specularEnabled;
  41488. defines["SHADOWS"] = shadowEnabled;
  41489. // Resetting all other lights if any
  41490. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41491. if (defines["LIGHT" + index] !== undefined) {
  41492. defines["LIGHT" + index] = false;
  41493. defines["HEMILIGHT" + lightIndex] = false;
  41494. defines["POINTLIGHT" + lightIndex] = false;
  41495. defines["DIRLIGHT" + lightIndex] = false;
  41496. defines["SPOTLIGHT" + lightIndex] = false;
  41497. defines["SHADOW" + lightIndex] = false;
  41498. }
  41499. }
  41500. var caps = scene.getEngine().getCaps();
  41501. if (defines["SHADOWFLOAT"] === undefined) {
  41502. needRebuild = true;
  41503. }
  41504. defines["SHADOWFLOAT"] = shadowEnabled &&
  41505. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41506. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41507. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41508. if (needRebuild) {
  41509. defines.rebuild();
  41510. }
  41511. return needNormals;
  41512. };
  41513. /**
  41514. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41515. * that won t be acctive due to defines being turned off.
  41516. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41517. * @param samplersList The samplers list
  41518. * @param defines The defines helping in the list generation
  41519. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41520. */
  41521. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41522. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41523. var uniformsList;
  41524. var uniformBuffersList = null;
  41525. if (uniformsListOrOptions.uniformsNames) {
  41526. var options = uniformsListOrOptions;
  41527. uniformsList = options.uniformsNames;
  41528. uniformBuffersList = options.uniformBuffersNames;
  41529. samplersList = options.samplers;
  41530. defines = options.defines;
  41531. maxSimultaneousLights = options.maxSimultaneousLights;
  41532. }
  41533. else {
  41534. uniformsList = uniformsListOrOptions;
  41535. if (!samplersList) {
  41536. samplersList = [];
  41537. }
  41538. }
  41539. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41540. if (!defines["LIGHT" + lightIndex]) {
  41541. break;
  41542. }
  41543. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41544. if (uniformBuffersList) {
  41545. uniformBuffersList.push("Light" + lightIndex);
  41546. }
  41547. samplersList.push("shadowSampler" + lightIndex);
  41548. samplersList.push("depthSampler" + lightIndex);
  41549. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41550. samplersList.push("projectionLightSampler" + lightIndex);
  41551. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41552. }
  41553. }
  41554. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41555. uniformsList.push("morphTargetInfluences");
  41556. }
  41557. };
  41558. /**
  41559. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41560. * @param defines The defines to update while falling back
  41561. * @param fallbacks The authorized effect fallbacks
  41562. * @param maxSimultaneousLights The maximum number of lights allowed
  41563. * @param rank the current rank of the Effect
  41564. * @returns The newly affected rank
  41565. */
  41566. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41567. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41568. if (rank === void 0) { rank = 0; }
  41569. var lightFallbackRank = 0;
  41570. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41571. if (!defines["LIGHT" + lightIndex]) {
  41572. break;
  41573. }
  41574. if (lightIndex > 0) {
  41575. lightFallbackRank = rank + lightIndex;
  41576. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41577. }
  41578. if (!defines["SHADOWS"]) {
  41579. if (defines["SHADOW" + lightIndex]) {
  41580. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41581. }
  41582. if (defines["SHADOWPCF" + lightIndex]) {
  41583. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41584. }
  41585. if (defines["SHADOWPCSS" + lightIndex]) {
  41586. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41587. }
  41588. if (defines["SHADOWPOISSON" + lightIndex]) {
  41589. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41590. }
  41591. if (defines["SHADOWESM" + lightIndex]) {
  41592. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41593. }
  41594. }
  41595. }
  41596. return lightFallbackRank++;
  41597. };
  41598. /**
  41599. * Prepares the list of attributes required for morph targets according to the effect defines.
  41600. * @param attribs The current list of supported attribs
  41601. * @param mesh The mesh to prepare the morph targets attributes for
  41602. * @param defines The current Defines of the effect
  41603. */
  41604. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41605. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41606. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41607. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41608. var manager = mesh.morphTargetManager;
  41609. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41610. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41611. for (var index = 0; index < influencers; index++) {
  41612. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41613. if (normal) {
  41614. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41615. }
  41616. if (tangent) {
  41617. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41618. }
  41619. if (attribs.length > maxAttributesCount) {
  41620. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41621. }
  41622. }
  41623. }
  41624. };
  41625. /**
  41626. * Prepares the list of attributes required for bones according to the effect defines.
  41627. * @param attribs The current list of supported attribs
  41628. * @param mesh The mesh to prepare the bones attributes for
  41629. * @param defines The current Defines of the effect
  41630. * @param fallbacks The current efffect fallback strategy
  41631. */
  41632. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41633. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41634. fallbacks.addCPUSkinningFallback(0, mesh);
  41635. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41636. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41637. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41638. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41639. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41640. }
  41641. }
  41642. };
  41643. /**
  41644. * Prepares the list of attributes required for instances according to the effect defines.
  41645. * @param attribs The current list of supported attribs
  41646. * @param defines The current Defines of the effect
  41647. */
  41648. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41649. if (defines["INSTANCES"]) {
  41650. attribs.push("world0");
  41651. attribs.push("world1");
  41652. attribs.push("world2");
  41653. attribs.push("world3");
  41654. }
  41655. };
  41656. /**
  41657. * Binds the light shadow information to the effect for the given mesh.
  41658. * @param light The light containing the generator
  41659. * @param scene The scene the lights belongs to
  41660. * @param mesh The mesh we are binding the information to render
  41661. * @param lightIndex The light index in the effect used to render the mesh
  41662. * @param effect The effect we are binding the data to
  41663. */
  41664. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41665. if (light.shadowEnabled && mesh.receiveShadows) {
  41666. var shadowGenerator = light.getShadowGenerator();
  41667. if (shadowGenerator) {
  41668. shadowGenerator.bindShadowLight(lightIndex, effect);
  41669. }
  41670. }
  41671. };
  41672. /**
  41673. * Binds the light information to the effect.
  41674. * @param light The light containing the generator
  41675. * @param effect The effect we are binding the data to
  41676. * @param lightIndex The light index in the effect used to render
  41677. */
  41678. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41679. light.transferToEffect(effect, lightIndex + "");
  41680. };
  41681. /**
  41682. * Binds the lights information from the scene to the effect for the given mesh.
  41683. * @param scene The scene the lights belongs to
  41684. * @param mesh The mesh we are binding the information to render
  41685. * @param effect The effect we are binding the data to
  41686. * @param defines The generated defines for the effect
  41687. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41688. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41689. */
  41690. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41691. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41692. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41693. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41694. for (var i = 0; i < len; i++) {
  41695. var light = mesh._lightSources[i];
  41696. var iAsString = i.toString();
  41697. var scaledIntensity = light.getScaledIntensity();
  41698. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41699. MaterialHelper.BindLightProperties(light, effect, i);
  41700. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41701. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41702. if (defines["SPECULARTERM"]) {
  41703. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41704. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41705. }
  41706. // Shadows
  41707. if (scene.shadowsEnabled) {
  41708. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41709. }
  41710. light._uniformBuffer.update();
  41711. }
  41712. };
  41713. /**
  41714. * Binds the fog information from the scene to the effect for the given mesh.
  41715. * @param scene The scene the lights belongs to
  41716. * @param mesh The mesh we are binding the information to render
  41717. * @param effect The effect we are binding the data to
  41718. */
  41719. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41720. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41721. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41722. effect.setColor3("vFogColor", scene.fogColor);
  41723. }
  41724. };
  41725. /**
  41726. * Binds the bones information from the mesh to the effect.
  41727. * @param mesh The mesh we are binding the information to render
  41728. * @param effect The effect we are binding the data to
  41729. */
  41730. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41731. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41732. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41733. if (matrices && effect) {
  41734. effect.setMatrices("mBones", matrices);
  41735. }
  41736. }
  41737. };
  41738. /**
  41739. * Binds the morph targets information from the mesh to the effect.
  41740. * @param abstractMesh The mesh we are binding the information to render
  41741. * @param effect The effect we are binding the data to
  41742. */
  41743. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41744. var manager = abstractMesh.morphTargetManager;
  41745. if (!abstractMesh || !manager) {
  41746. return;
  41747. }
  41748. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41749. };
  41750. /**
  41751. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41752. * @param defines The generated defines used in the effect
  41753. * @param effect The effect we are binding the data to
  41754. * @param scene The scene we are willing to render with logarithmic scale for
  41755. */
  41756. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41757. if (defines["LOGARITHMICDEPTH"]) {
  41758. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41759. }
  41760. };
  41761. /**
  41762. * Binds the clip plane information from the scene to the effect.
  41763. * @param scene The scene the clip plane information are extracted from
  41764. * @param effect The effect we are binding the data to
  41765. */
  41766. MaterialHelper.BindClipPlane = function (effect, scene) {
  41767. if (scene.clipPlane) {
  41768. var clipPlane = scene.clipPlane;
  41769. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41770. }
  41771. };
  41772. return MaterialHelper;
  41773. }());
  41774. BABYLON.MaterialHelper = MaterialHelper;
  41775. })(BABYLON || (BABYLON = {}));
  41776. //# sourceMappingURL=babylon.materialHelper.js.map
  41777. "use strict";
  41778. var BABYLON;
  41779. (function (BABYLON) {
  41780. var PushMaterial = /** @class */ (function (_super) {
  41781. __extends(PushMaterial, _super);
  41782. function PushMaterial(name, scene) {
  41783. var _this = _super.call(this, name, scene) || this;
  41784. _this._normalMatrix = new BABYLON.Matrix();
  41785. _this.storeEffectOnSubMeshes = true;
  41786. return _this;
  41787. }
  41788. PushMaterial.prototype.getEffect = function () {
  41789. return this._activeEffect;
  41790. };
  41791. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41792. if (!mesh) {
  41793. return false;
  41794. }
  41795. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41796. return true;
  41797. }
  41798. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41799. };
  41800. /**
  41801. * Binds the given world matrix to the active effect
  41802. *
  41803. * @param world the matrix to bind
  41804. */
  41805. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41806. this._activeEffect.setMatrix("world", world);
  41807. };
  41808. /**
  41809. * Binds the given normal matrix to the active effect
  41810. *
  41811. * @param normalMatrix the matrix to bind
  41812. */
  41813. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41814. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41815. };
  41816. PushMaterial.prototype.bind = function (world, mesh) {
  41817. if (!mesh) {
  41818. return;
  41819. }
  41820. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41821. };
  41822. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41823. if (effect === void 0) { effect = null; }
  41824. _super.prototype._afterBind.call(this, mesh);
  41825. this.getScene()._cachedEffect = effect;
  41826. };
  41827. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41828. if (visibility === void 0) { visibility = 1; }
  41829. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41830. };
  41831. return PushMaterial;
  41832. }(BABYLON.Material));
  41833. BABYLON.PushMaterial = PushMaterial;
  41834. })(BABYLON || (BABYLON = {}));
  41835. //# sourceMappingURL=babylon.pushMaterial.js.map
  41836. "use strict";
  41837. var BABYLON;
  41838. (function (BABYLON) {
  41839. /** @ignore */
  41840. var StandardMaterialDefines = /** @class */ (function (_super) {
  41841. __extends(StandardMaterialDefines, _super);
  41842. function StandardMaterialDefines() {
  41843. var _this = _super.call(this) || this;
  41844. _this.MAINUV1 = false;
  41845. _this.MAINUV2 = false;
  41846. _this.DIFFUSE = false;
  41847. _this.DIFFUSEDIRECTUV = 0;
  41848. _this.AMBIENT = false;
  41849. _this.AMBIENTDIRECTUV = 0;
  41850. _this.OPACITY = false;
  41851. _this.OPACITYDIRECTUV = 0;
  41852. _this.OPACITYRGB = false;
  41853. _this.REFLECTION = false;
  41854. _this.EMISSIVE = false;
  41855. _this.EMISSIVEDIRECTUV = 0;
  41856. _this.SPECULAR = false;
  41857. _this.SPECULARDIRECTUV = 0;
  41858. _this.BUMP = false;
  41859. _this.BUMPDIRECTUV = 0;
  41860. _this.PARALLAX = false;
  41861. _this.PARALLAXOCCLUSION = false;
  41862. _this.SPECULAROVERALPHA = false;
  41863. _this.CLIPPLANE = false;
  41864. _this.ALPHATEST = false;
  41865. _this.DEPTHPREPASS = false;
  41866. _this.ALPHAFROMDIFFUSE = false;
  41867. _this.POINTSIZE = false;
  41868. _this.FOG = false;
  41869. _this.SPECULARTERM = false;
  41870. _this.DIFFUSEFRESNEL = false;
  41871. _this.OPACITYFRESNEL = false;
  41872. _this.REFLECTIONFRESNEL = false;
  41873. _this.REFRACTIONFRESNEL = false;
  41874. _this.EMISSIVEFRESNEL = false;
  41875. _this.FRESNEL = false;
  41876. _this.NORMAL = false;
  41877. _this.UV1 = false;
  41878. _this.UV2 = false;
  41879. _this.VERTEXCOLOR = false;
  41880. _this.VERTEXALPHA = false;
  41881. _this.NUM_BONE_INFLUENCERS = 0;
  41882. _this.BonesPerMesh = 0;
  41883. _this.INSTANCES = false;
  41884. _this.GLOSSINESS = false;
  41885. _this.ROUGHNESS = false;
  41886. _this.EMISSIVEASILLUMINATION = false;
  41887. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41888. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41889. _this.LIGHTMAP = false;
  41890. _this.LIGHTMAPDIRECTUV = 0;
  41891. _this.OBJECTSPACE_NORMALMAP = false;
  41892. _this.USELIGHTMAPASSHADOWMAP = false;
  41893. _this.REFLECTIONMAP_3D = false;
  41894. _this.REFLECTIONMAP_SPHERICAL = false;
  41895. _this.REFLECTIONMAP_PLANAR = false;
  41896. _this.REFLECTIONMAP_CUBIC = false;
  41897. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41898. _this.REFLECTIONMAP_PROJECTION = false;
  41899. _this.REFLECTIONMAP_SKYBOX = false;
  41900. _this.REFLECTIONMAP_EXPLICIT = false;
  41901. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41902. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41903. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41904. _this.INVERTCUBICMAP = false;
  41905. _this.LOGARITHMICDEPTH = false;
  41906. _this.REFRACTION = false;
  41907. _this.REFRACTIONMAP_3D = false;
  41908. _this.REFLECTIONOVERALPHA = false;
  41909. _this.TWOSIDEDLIGHTING = false;
  41910. _this.SHADOWFLOAT = false;
  41911. _this.MORPHTARGETS = false;
  41912. _this.MORPHTARGETS_NORMAL = false;
  41913. _this.MORPHTARGETS_TANGENT = false;
  41914. _this.NUM_MORPH_INFLUENCERS = 0;
  41915. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41916. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41917. _this.IMAGEPROCESSING = false;
  41918. _this.VIGNETTE = false;
  41919. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41920. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41921. _this.TONEMAPPING = false;
  41922. _this.CONTRAST = false;
  41923. _this.COLORCURVES = false;
  41924. _this.COLORGRADING = false;
  41925. _this.COLORGRADING3D = false;
  41926. _this.SAMPLER3DGREENDEPTH = false;
  41927. _this.SAMPLER3DBGRMAP = false;
  41928. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41929. _this.EXPOSURE = false;
  41930. _this.rebuild();
  41931. return _this;
  41932. }
  41933. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41934. var modes = [
  41935. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41936. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41937. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41938. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41939. ];
  41940. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41941. var mode = modes_1[_i];
  41942. this[mode] = (mode === modeToEnable);
  41943. }
  41944. };
  41945. return StandardMaterialDefines;
  41946. }(BABYLON.MaterialDefines));
  41947. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41948. var StandardMaterial = /** @class */ (function (_super) {
  41949. __extends(StandardMaterial, _super);
  41950. function StandardMaterial(name, scene) {
  41951. var _this = _super.call(this, name, scene) || this;
  41952. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41953. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41954. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41955. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41956. _this.specularPower = 64;
  41957. _this._useAlphaFromDiffuseTexture = false;
  41958. _this._useEmissiveAsIllumination = false;
  41959. _this._linkEmissiveWithDiffuse = false;
  41960. _this._useSpecularOverAlpha = false;
  41961. _this._useReflectionOverAlpha = false;
  41962. _this._disableLighting = false;
  41963. _this._useObjectSpaceNormalMap = false;
  41964. _this._useParallax = false;
  41965. _this._useParallaxOcclusion = false;
  41966. _this.parallaxScaleBias = 0.05;
  41967. _this._roughness = 0;
  41968. _this.indexOfRefraction = 0.98;
  41969. _this.invertRefractionY = true;
  41970. _this._useLightmapAsShadowmap = false;
  41971. _this._useReflectionFresnelFromSpecular = false;
  41972. _this._useGlossinessFromSpecularMapAlpha = false;
  41973. _this._maxSimultaneousLights = 4;
  41974. /**
  41975. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41976. */
  41977. _this._invertNormalMapX = false;
  41978. /**
  41979. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41980. */
  41981. _this._invertNormalMapY = false;
  41982. /**
  41983. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41984. */
  41985. _this._twoSidedLighting = false;
  41986. _this._renderTargets = new BABYLON.SmartArray(16);
  41987. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41988. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41989. // Setup the default processing configuration to the scene.
  41990. _this._attachImageProcessingConfiguration(null);
  41991. _this.getRenderTargetTextures = function () {
  41992. _this._renderTargets.reset();
  41993. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41994. _this._renderTargets.push(_this._reflectionTexture);
  41995. }
  41996. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41997. _this._renderTargets.push(_this._refractionTexture);
  41998. }
  41999. return _this._renderTargets;
  42000. };
  42001. return _this;
  42002. }
  42003. ;
  42004. ;
  42005. ;
  42006. ;
  42007. ;
  42008. ;
  42009. ;
  42010. ;
  42011. ;
  42012. ;
  42013. ;
  42014. ;
  42015. ;
  42016. ;
  42017. ;
  42018. ;
  42019. ;
  42020. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42021. /**
  42022. * Gets the image processing configuration used either in this material.
  42023. */
  42024. get: function () {
  42025. return this._imageProcessingConfiguration;
  42026. },
  42027. /**
  42028. * Sets the Default image processing configuration used either in the this material.
  42029. *
  42030. * If sets to null, the scene one is in use.
  42031. */
  42032. set: function (value) {
  42033. this._attachImageProcessingConfiguration(value);
  42034. // Ensure the effect will be rebuilt.
  42035. this._markAllSubMeshesAsTexturesDirty();
  42036. },
  42037. enumerable: true,
  42038. configurable: true
  42039. });
  42040. /**
  42041. * Attaches a new image processing configuration to the Standard Material.
  42042. * @param configuration
  42043. */
  42044. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42045. var _this = this;
  42046. if (configuration === this._imageProcessingConfiguration) {
  42047. return;
  42048. }
  42049. // Detaches observer.
  42050. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42051. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42052. }
  42053. // Pick the scene configuration if needed.
  42054. if (!configuration) {
  42055. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42056. }
  42057. else {
  42058. this._imageProcessingConfiguration = configuration;
  42059. }
  42060. // Attaches observer.
  42061. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42062. _this._markAllSubMeshesAsImageProcessingDirty();
  42063. });
  42064. };
  42065. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42066. /**
  42067. * Gets wether the color curves effect is enabled.
  42068. */
  42069. get: function () {
  42070. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42071. },
  42072. /**
  42073. * Sets wether the color curves effect is enabled.
  42074. */
  42075. set: function (value) {
  42076. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42077. },
  42078. enumerable: true,
  42079. configurable: true
  42080. });
  42081. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42082. /**
  42083. * Gets wether the color grading effect is enabled.
  42084. */
  42085. get: function () {
  42086. return this.imageProcessingConfiguration.colorGradingEnabled;
  42087. },
  42088. /**
  42089. * Gets wether the color grading effect is enabled.
  42090. */
  42091. set: function (value) {
  42092. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42093. },
  42094. enumerable: true,
  42095. configurable: true
  42096. });
  42097. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42098. /**
  42099. * Gets wether tonemapping is enabled or not.
  42100. */
  42101. get: function () {
  42102. return this._imageProcessingConfiguration.toneMappingEnabled;
  42103. },
  42104. /**
  42105. * Sets wether tonemapping is enabled or not
  42106. */
  42107. set: function (value) {
  42108. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42109. },
  42110. enumerable: true,
  42111. configurable: true
  42112. });
  42113. ;
  42114. ;
  42115. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42116. /**
  42117. * The camera exposure used on this material.
  42118. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42119. * This corresponds to a photographic exposure.
  42120. */
  42121. get: function () {
  42122. return this._imageProcessingConfiguration.exposure;
  42123. },
  42124. /**
  42125. * The camera exposure used on this material.
  42126. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42127. * This corresponds to a photographic exposure.
  42128. */
  42129. set: function (value) {
  42130. this._imageProcessingConfiguration.exposure = value;
  42131. },
  42132. enumerable: true,
  42133. configurable: true
  42134. });
  42135. ;
  42136. ;
  42137. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42138. /**
  42139. * Gets The camera contrast used on this material.
  42140. */
  42141. get: function () {
  42142. return this._imageProcessingConfiguration.contrast;
  42143. },
  42144. /**
  42145. * Sets The camera contrast used on this material.
  42146. */
  42147. set: function (value) {
  42148. this._imageProcessingConfiguration.contrast = value;
  42149. },
  42150. enumerable: true,
  42151. configurable: true
  42152. });
  42153. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42154. /**
  42155. * Gets the Color Grading 2D Lookup Texture.
  42156. */
  42157. get: function () {
  42158. return this._imageProcessingConfiguration.colorGradingTexture;
  42159. },
  42160. /**
  42161. * Sets the Color Grading 2D Lookup Texture.
  42162. */
  42163. set: function (value) {
  42164. this._imageProcessingConfiguration.colorGradingTexture = value;
  42165. },
  42166. enumerable: true,
  42167. configurable: true
  42168. });
  42169. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42170. /**
  42171. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42172. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42173. * 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;
  42174. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42175. */
  42176. get: function () {
  42177. return this._imageProcessingConfiguration.colorCurves;
  42178. },
  42179. /**
  42180. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42181. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42182. * 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;
  42183. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42184. */
  42185. set: function (value) {
  42186. this._imageProcessingConfiguration.colorCurves = value;
  42187. },
  42188. enumerable: true,
  42189. configurable: true
  42190. });
  42191. StandardMaterial.prototype.getClassName = function () {
  42192. return "StandardMaterial";
  42193. };
  42194. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42195. get: function () {
  42196. return this._useLogarithmicDepth;
  42197. },
  42198. set: function (value) {
  42199. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42200. this._markAllSubMeshesAsMiscDirty();
  42201. },
  42202. enumerable: true,
  42203. configurable: true
  42204. });
  42205. StandardMaterial.prototype.needAlphaBlending = function () {
  42206. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42207. };
  42208. StandardMaterial.prototype.needAlphaTesting = function () {
  42209. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42210. };
  42211. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42212. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42213. };
  42214. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42215. return this._diffuseTexture;
  42216. };
  42217. /**
  42218. * Child classes can use it to update shaders
  42219. */
  42220. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42221. if (useInstances === void 0) { useInstances = false; }
  42222. if (subMesh.effect && this.isFrozen) {
  42223. if (this._wasPreviouslyReady && subMesh.effect) {
  42224. return true;
  42225. }
  42226. }
  42227. if (!subMesh._materialDefines) {
  42228. subMesh._materialDefines = new StandardMaterialDefines();
  42229. }
  42230. var scene = this.getScene();
  42231. var defines = subMesh._materialDefines;
  42232. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42233. if (defines._renderId === scene.getRenderId()) {
  42234. return true;
  42235. }
  42236. }
  42237. var engine = scene.getEngine();
  42238. // Lights
  42239. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42240. // Textures
  42241. if (defines._areTexturesDirty) {
  42242. defines._needUVs = false;
  42243. defines.MAINUV1 = false;
  42244. defines.MAINUV2 = false;
  42245. if (scene.texturesEnabled) {
  42246. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42247. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42248. return false;
  42249. }
  42250. else {
  42251. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42252. }
  42253. }
  42254. else {
  42255. defines.DIFFUSE = false;
  42256. }
  42257. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42258. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42259. return false;
  42260. }
  42261. else {
  42262. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42263. }
  42264. }
  42265. else {
  42266. defines.AMBIENT = false;
  42267. }
  42268. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42269. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42270. return false;
  42271. }
  42272. else {
  42273. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42274. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42275. }
  42276. }
  42277. else {
  42278. defines.OPACITY = false;
  42279. }
  42280. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42281. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42282. return false;
  42283. }
  42284. else {
  42285. defines._needNormals = true;
  42286. defines.REFLECTION = true;
  42287. defines.ROUGHNESS = (this._roughness > 0);
  42288. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42289. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42290. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42291. switch (this._reflectionTexture.coordinatesMode) {
  42292. case BABYLON.Texture.CUBIC_MODE:
  42293. case BABYLON.Texture.INVCUBIC_MODE:
  42294. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42295. break;
  42296. case BABYLON.Texture.EXPLICIT_MODE:
  42297. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42298. break;
  42299. case BABYLON.Texture.PLANAR_MODE:
  42300. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42301. break;
  42302. case BABYLON.Texture.PROJECTION_MODE:
  42303. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42304. break;
  42305. case BABYLON.Texture.SKYBOX_MODE:
  42306. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42307. break;
  42308. case BABYLON.Texture.SPHERICAL_MODE:
  42309. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42310. break;
  42311. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42312. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42313. break;
  42314. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42315. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42316. break;
  42317. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42318. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42319. break;
  42320. }
  42321. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42322. }
  42323. }
  42324. else {
  42325. defines.REFLECTION = false;
  42326. }
  42327. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42328. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42329. return false;
  42330. }
  42331. else {
  42332. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42333. }
  42334. }
  42335. else {
  42336. defines.EMISSIVE = false;
  42337. }
  42338. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42339. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42340. return false;
  42341. }
  42342. else {
  42343. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42344. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42345. }
  42346. }
  42347. else {
  42348. defines.LIGHTMAP = false;
  42349. }
  42350. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42351. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42352. return false;
  42353. }
  42354. else {
  42355. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42356. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42357. }
  42358. }
  42359. else {
  42360. defines.SPECULAR = false;
  42361. }
  42362. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42363. // Bump texure can not be not blocking.
  42364. if (!this._bumpTexture.isReady()) {
  42365. return false;
  42366. }
  42367. else {
  42368. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42369. defines.PARALLAX = this._useParallax;
  42370. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42371. }
  42372. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42373. }
  42374. else {
  42375. defines.BUMP = false;
  42376. }
  42377. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42378. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42379. return false;
  42380. }
  42381. else {
  42382. defines._needUVs = true;
  42383. defines.REFRACTION = true;
  42384. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42385. }
  42386. }
  42387. else {
  42388. defines.REFRACTION = false;
  42389. }
  42390. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42391. }
  42392. else {
  42393. defines.DIFFUSE = false;
  42394. defines.AMBIENT = false;
  42395. defines.OPACITY = false;
  42396. defines.REFLECTION = false;
  42397. defines.EMISSIVE = false;
  42398. defines.LIGHTMAP = false;
  42399. defines.BUMP = false;
  42400. defines.REFRACTION = false;
  42401. }
  42402. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42403. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42404. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42405. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42406. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42407. }
  42408. if (defines._areImageProcessingDirty) {
  42409. if (!this._imageProcessingConfiguration.isReady()) {
  42410. return false;
  42411. }
  42412. this._imageProcessingConfiguration.prepareDefines(defines);
  42413. }
  42414. if (defines._areFresnelDirty) {
  42415. if (StandardMaterial.FresnelEnabled) {
  42416. // Fresnel
  42417. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42418. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42419. this._reflectionFresnelParameters) {
  42420. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42421. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42422. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42423. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42424. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42425. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42426. defines._needNormals = true;
  42427. defines.FRESNEL = true;
  42428. }
  42429. }
  42430. else {
  42431. defines.FRESNEL = false;
  42432. }
  42433. }
  42434. // Misc.
  42435. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42436. // Attribs
  42437. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42438. // Values that need to be evaluated on every frame
  42439. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42440. // Get correct effect
  42441. if (defines.isDirty) {
  42442. defines.markAsProcessed();
  42443. scene.resetCachedMaterial();
  42444. // Fallbacks
  42445. var fallbacks = new BABYLON.EffectFallbacks();
  42446. if (defines.REFLECTION) {
  42447. fallbacks.addFallback(0, "REFLECTION");
  42448. }
  42449. if (defines.SPECULAR) {
  42450. fallbacks.addFallback(0, "SPECULAR");
  42451. }
  42452. if (defines.BUMP) {
  42453. fallbacks.addFallback(0, "BUMP");
  42454. }
  42455. if (defines.PARALLAX) {
  42456. fallbacks.addFallback(1, "PARALLAX");
  42457. }
  42458. if (defines.PARALLAXOCCLUSION) {
  42459. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42460. }
  42461. if (defines.SPECULAROVERALPHA) {
  42462. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42463. }
  42464. if (defines.FOG) {
  42465. fallbacks.addFallback(1, "FOG");
  42466. }
  42467. if (defines.POINTSIZE) {
  42468. fallbacks.addFallback(0, "POINTSIZE");
  42469. }
  42470. if (defines.LOGARITHMICDEPTH) {
  42471. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42472. }
  42473. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42474. if (defines.SPECULARTERM) {
  42475. fallbacks.addFallback(0, "SPECULARTERM");
  42476. }
  42477. if (defines.DIFFUSEFRESNEL) {
  42478. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42479. }
  42480. if (defines.OPACITYFRESNEL) {
  42481. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42482. }
  42483. if (defines.REFLECTIONFRESNEL) {
  42484. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42485. }
  42486. if (defines.EMISSIVEFRESNEL) {
  42487. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42488. }
  42489. if (defines.FRESNEL) {
  42490. fallbacks.addFallback(4, "FRESNEL");
  42491. }
  42492. //Attributes
  42493. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42494. if (defines.NORMAL) {
  42495. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42496. }
  42497. if (defines.UV1) {
  42498. attribs.push(BABYLON.VertexBuffer.UVKind);
  42499. }
  42500. if (defines.UV2) {
  42501. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42502. }
  42503. if (defines.VERTEXCOLOR) {
  42504. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42505. }
  42506. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42507. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42508. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42509. var shaderName = "default";
  42510. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42511. "vFogInfos", "vFogColor", "pointSize",
  42512. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42513. "mBones",
  42514. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42515. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42516. "vReflectionPosition", "vReflectionSize",
  42517. "logarithmicDepthConstant", "vTangentSpaceParams"
  42518. ];
  42519. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42520. var uniformBuffers = ["Material", "Scene"];
  42521. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42522. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42523. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42524. uniformsNames: uniforms,
  42525. uniformBuffersNames: uniformBuffers,
  42526. samplers: samplers,
  42527. defines: defines,
  42528. maxSimultaneousLights: this._maxSimultaneousLights
  42529. });
  42530. if (this.customShaderNameResolve) {
  42531. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42532. }
  42533. var join = defines.toString();
  42534. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42535. attributes: attribs,
  42536. uniformsNames: uniforms,
  42537. uniformBuffersNames: uniformBuffers,
  42538. samplers: samplers,
  42539. defines: join,
  42540. fallbacks: fallbacks,
  42541. onCompiled: this.onCompiled,
  42542. onError: this.onError,
  42543. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42544. }, engine), defines);
  42545. this.buildUniformLayout();
  42546. }
  42547. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42548. return false;
  42549. }
  42550. defines._renderId = scene.getRenderId();
  42551. this._wasPreviouslyReady = true;
  42552. return true;
  42553. };
  42554. StandardMaterial.prototype.buildUniformLayout = function () {
  42555. // Order is important !
  42556. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42557. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42558. this._uniformBuffer.addUniform("opacityParts", 4);
  42559. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42560. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42561. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42562. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42563. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42564. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42565. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42566. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42567. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42568. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42569. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42570. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42571. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42572. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42573. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42574. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42575. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42576. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42577. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42578. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42579. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42580. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42581. this._uniformBuffer.addUniform("specularMatrix", 16);
  42582. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42583. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42584. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42585. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42586. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42587. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42588. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42589. this._uniformBuffer.addUniform("pointSize", 1);
  42590. this._uniformBuffer.create();
  42591. };
  42592. StandardMaterial.prototype.unbind = function () {
  42593. if (this._activeEffect) {
  42594. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42595. this._activeEffect.setTexture("reflection2DSampler", null);
  42596. }
  42597. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42598. this._activeEffect.setTexture("refraction2DSampler", null);
  42599. }
  42600. }
  42601. _super.prototype.unbind.call(this);
  42602. };
  42603. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42604. var scene = this.getScene();
  42605. var defines = subMesh._materialDefines;
  42606. if (!defines) {
  42607. return;
  42608. }
  42609. var effect = subMesh.effect;
  42610. if (!effect) {
  42611. return;
  42612. }
  42613. this._activeEffect = effect;
  42614. // Matrices
  42615. this.bindOnlyWorldMatrix(world);
  42616. // Normal Matrix
  42617. if (defines.OBJECTSPACE_NORMALMAP) {
  42618. world.toNormalMatrix(this._normalMatrix);
  42619. this.bindOnlyNormalMatrix(this._normalMatrix);
  42620. }
  42621. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42622. // Bones
  42623. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42624. if (mustRebind) {
  42625. this._uniformBuffer.bindToEffect(effect, "Material");
  42626. this.bindViewProjection(effect);
  42627. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42628. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42629. // Fresnel
  42630. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42631. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42632. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42633. }
  42634. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42635. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42636. }
  42637. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42638. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42639. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42640. }
  42641. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42642. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42643. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42644. }
  42645. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42646. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42647. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42648. }
  42649. }
  42650. // Textures
  42651. if (scene.texturesEnabled) {
  42652. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42653. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42654. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42655. }
  42656. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42657. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42658. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42659. }
  42660. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42661. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42662. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42663. }
  42664. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42665. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42666. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42667. if (this._reflectionTexture.boundingBoxSize) {
  42668. var cubeTexture = this._reflectionTexture;
  42669. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42670. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42671. }
  42672. }
  42673. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42674. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42675. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42676. }
  42677. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42678. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42679. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42680. }
  42681. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42682. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42683. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42684. }
  42685. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42686. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42687. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42688. if (scene._mirroredCameraPosition) {
  42689. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42690. }
  42691. else {
  42692. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42693. }
  42694. }
  42695. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42696. var depth = 1.0;
  42697. if (!this._refractionTexture.isCube) {
  42698. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42699. if (this._refractionTexture.depth) {
  42700. depth = this._refractionTexture.depth;
  42701. }
  42702. }
  42703. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42704. }
  42705. }
  42706. // Point size
  42707. if (this.pointsCloud) {
  42708. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42709. }
  42710. if (defines.SPECULARTERM) {
  42711. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42712. }
  42713. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42714. // Diffuse
  42715. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42716. }
  42717. // Textures
  42718. if (scene.texturesEnabled) {
  42719. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42720. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42721. }
  42722. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42723. effect.setTexture("ambientSampler", this._ambientTexture);
  42724. }
  42725. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42726. effect.setTexture("opacitySampler", this._opacityTexture);
  42727. }
  42728. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42729. if (this._reflectionTexture.isCube) {
  42730. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42731. }
  42732. else {
  42733. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42734. }
  42735. }
  42736. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42737. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42738. }
  42739. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42740. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42741. }
  42742. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42743. effect.setTexture("specularSampler", this._specularTexture);
  42744. }
  42745. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42746. effect.setTexture("bumpSampler", this._bumpTexture);
  42747. }
  42748. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42749. var depth = 1.0;
  42750. if (this._refractionTexture.isCube) {
  42751. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42752. }
  42753. else {
  42754. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42755. }
  42756. }
  42757. }
  42758. // Clip plane
  42759. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42760. // Colors
  42761. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42762. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42763. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42764. }
  42765. if (mustRebind || !this.isFrozen) {
  42766. // Lights
  42767. if (scene.lightsEnabled && !this._disableLighting) {
  42768. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42769. }
  42770. // View
  42771. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42772. this.bindView(effect);
  42773. }
  42774. // Fog
  42775. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42776. // Morph targets
  42777. if (defines.NUM_MORPH_INFLUENCERS) {
  42778. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42779. }
  42780. // Log. depth
  42781. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42782. // image processing
  42783. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  42784. this._imageProcessingConfiguration.bind(this._activeEffect);
  42785. }
  42786. }
  42787. this._uniformBuffer.update();
  42788. this._afterBind(mesh, this._activeEffect);
  42789. };
  42790. StandardMaterial.prototype.getAnimatables = function () {
  42791. var results = [];
  42792. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42793. results.push(this._diffuseTexture);
  42794. }
  42795. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42796. results.push(this._ambientTexture);
  42797. }
  42798. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42799. results.push(this._opacityTexture);
  42800. }
  42801. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42802. results.push(this._reflectionTexture);
  42803. }
  42804. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42805. results.push(this._emissiveTexture);
  42806. }
  42807. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42808. results.push(this._specularTexture);
  42809. }
  42810. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42811. results.push(this._bumpTexture);
  42812. }
  42813. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42814. results.push(this._lightmapTexture);
  42815. }
  42816. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42817. results.push(this._refractionTexture);
  42818. }
  42819. return results;
  42820. };
  42821. StandardMaterial.prototype.getActiveTextures = function () {
  42822. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42823. if (this._diffuseTexture) {
  42824. activeTextures.push(this._diffuseTexture);
  42825. }
  42826. if (this._ambientTexture) {
  42827. activeTextures.push(this._ambientTexture);
  42828. }
  42829. if (this._opacityTexture) {
  42830. activeTextures.push(this._opacityTexture);
  42831. }
  42832. if (this._reflectionTexture) {
  42833. activeTextures.push(this._reflectionTexture);
  42834. }
  42835. if (this._emissiveTexture) {
  42836. activeTextures.push(this._emissiveTexture);
  42837. }
  42838. if (this._specularTexture) {
  42839. activeTextures.push(this._specularTexture);
  42840. }
  42841. if (this._bumpTexture) {
  42842. activeTextures.push(this._bumpTexture);
  42843. }
  42844. if (this._lightmapTexture) {
  42845. activeTextures.push(this._lightmapTexture);
  42846. }
  42847. if (this._refractionTexture) {
  42848. activeTextures.push(this._refractionTexture);
  42849. }
  42850. return activeTextures;
  42851. };
  42852. StandardMaterial.prototype.hasTexture = function (texture) {
  42853. if (_super.prototype.hasTexture.call(this, texture)) {
  42854. return true;
  42855. }
  42856. if (this._diffuseTexture === texture) {
  42857. return true;
  42858. }
  42859. if (this._ambientTexture === texture) {
  42860. return true;
  42861. }
  42862. if (this._opacityTexture === texture) {
  42863. return true;
  42864. }
  42865. if (this._reflectionTexture === texture) {
  42866. return true;
  42867. }
  42868. if (this._emissiveTexture === texture) {
  42869. return true;
  42870. }
  42871. if (this._specularTexture === texture) {
  42872. return true;
  42873. }
  42874. if (this._bumpTexture === texture) {
  42875. return true;
  42876. }
  42877. if (this._lightmapTexture === texture) {
  42878. return true;
  42879. }
  42880. if (this._refractionTexture === texture) {
  42881. return true;
  42882. }
  42883. return false;
  42884. };
  42885. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42886. if (forceDisposeTextures) {
  42887. if (this._diffuseTexture) {
  42888. this._diffuseTexture.dispose();
  42889. }
  42890. if (this._ambientTexture) {
  42891. this._ambientTexture.dispose();
  42892. }
  42893. if (this._opacityTexture) {
  42894. this._opacityTexture.dispose();
  42895. }
  42896. if (this._reflectionTexture) {
  42897. this._reflectionTexture.dispose();
  42898. }
  42899. if (this._emissiveTexture) {
  42900. this._emissiveTexture.dispose();
  42901. }
  42902. if (this._specularTexture) {
  42903. this._specularTexture.dispose();
  42904. }
  42905. if (this._bumpTexture) {
  42906. this._bumpTexture.dispose();
  42907. }
  42908. if (this._lightmapTexture) {
  42909. this._lightmapTexture.dispose();
  42910. }
  42911. if (this._refractionTexture) {
  42912. this._refractionTexture.dispose();
  42913. }
  42914. }
  42915. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42916. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42917. }
  42918. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42919. };
  42920. StandardMaterial.prototype.clone = function (name) {
  42921. var _this = this;
  42922. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42923. result.name = name;
  42924. result.id = name;
  42925. return result;
  42926. };
  42927. StandardMaterial.prototype.serialize = function () {
  42928. return BABYLON.SerializationHelper.Serialize(this);
  42929. };
  42930. // Statics
  42931. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42932. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42933. };
  42934. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42935. get: function () {
  42936. return StandardMaterial._DiffuseTextureEnabled;
  42937. },
  42938. set: function (value) {
  42939. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42940. return;
  42941. }
  42942. StandardMaterial._DiffuseTextureEnabled = value;
  42943. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42944. },
  42945. enumerable: true,
  42946. configurable: true
  42947. });
  42948. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42949. get: function () {
  42950. return StandardMaterial._AmbientTextureEnabled;
  42951. },
  42952. set: function (value) {
  42953. if (StandardMaterial._AmbientTextureEnabled === value) {
  42954. return;
  42955. }
  42956. StandardMaterial._AmbientTextureEnabled = value;
  42957. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42958. },
  42959. enumerable: true,
  42960. configurable: true
  42961. });
  42962. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42963. get: function () {
  42964. return StandardMaterial._OpacityTextureEnabled;
  42965. },
  42966. set: function (value) {
  42967. if (StandardMaterial._OpacityTextureEnabled === value) {
  42968. return;
  42969. }
  42970. StandardMaterial._OpacityTextureEnabled = value;
  42971. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42972. },
  42973. enumerable: true,
  42974. configurable: true
  42975. });
  42976. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42977. get: function () {
  42978. return StandardMaterial._ReflectionTextureEnabled;
  42979. },
  42980. set: function (value) {
  42981. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42982. return;
  42983. }
  42984. StandardMaterial._ReflectionTextureEnabled = value;
  42985. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42986. },
  42987. enumerable: true,
  42988. configurable: true
  42989. });
  42990. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42991. get: function () {
  42992. return StandardMaterial._EmissiveTextureEnabled;
  42993. },
  42994. set: function (value) {
  42995. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42996. return;
  42997. }
  42998. StandardMaterial._EmissiveTextureEnabled = value;
  42999. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43000. },
  43001. enumerable: true,
  43002. configurable: true
  43003. });
  43004. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43005. get: function () {
  43006. return StandardMaterial._SpecularTextureEnabled;
  43007. },
  43008. set: function (value) {
  43009. if (StandardMaterial._SpecularTextureEnabled === value) {
  43010. return;
  43011. }
  43012. StandardMaterial._SpecularTextureEnabled = value;
  43013. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43014. },
  43015. enumerable: true,
  43016. configurable: true
  43017. });
  43018. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43019. get: function () {
  43020. return StandardMaterial._BumpTextureEnabled;
  43021. },
  43022. set: function (value) {
  43023. if (StandardMaterial._BumpTextureEnabled === value) {
  43024. return;
  43025. }
  43026. StandardMaterial._BumpTextureEnabled = value;
  43027. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43028. },
  43029. enumerable: true,
  43030. configurable: true
  43031. });
  43032. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43033. get: function () {
  43034. return StandardMaterial._LightmapTextureEnabled;
  43035. },
  43036. set: function (value) {
  43037. if (StandardMaterial._LightmapTextureEnabled === value) {
  43038. return;
  43039. }
  43040. StandardMaterial._LightmapTextureEnabled = value;
  43041. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43042. },
  43043. enumerable: true,
  43044. configurable: true
  43045. });
  43046. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43047. get: function () {
  43048. return StandardMaterial._RefractionTextureEnabled;
  43049. },
  43050. set: function (value) {
  43051. if (StandardMaterial._RefractionTextureEnabled === value) {
  43052. return;
  43053. }
  43054. StandardMaterial._RefractionTextureEnabled = value;
  43055. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43056. },
  43057. enumerable: true,
  43058. configurable: true
  43059. });
  43060. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43061. get: function () {
  43062. return StandardMaterial._ColorGradingTextureEnabled;
  43063. },
  43064. set: function (value) {
  43065. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43066. return;
  43067. }
  43068. StandardMaterial._ColorGradingTextureEnabled = value;
  43069. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43070. },
  43071. enumerable: true,
  43072. configurable: true
  43073. });
  43074. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43075. get: function () {
  43076. return StandardMaterial._FresnelEnabled;
  43077. },
  43078. set: function (value) {
  43079. if (StandardMaterial._FresnelEnabled === value) {
  43080. return;
  43081. }
  43082. StandardMaterial._FresnelEnabled = value;
  43083. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43084. },
  43085. enumerable: true,
  43086. configurable: true
  43087. });
  43088. // Flags used to enable or disable a type of texture for all Standard Materials
  43089. StandardMaterial._DiffuseTextureEnabled = true;
  43090. StandardMaterial._AmbientTextureEnabled = true;
  43091. StandardMaterial._OpacityTextureEnabled = true;
  43092. StandardMaterial._ReflectionTextureEnabled = true;
  43093. StandardMaterial._EmissiveTextureEnabled = true;
  43094. StandardMaterial._SpecularTextureEnabled = true;
  43095. StandardMaterial._BumpTextureEnabled = true;
  43096. StandardMaterial._LightmapTextureEnabled = true;
  43097. StandardMaterial._RefractionTextureEnabled = true;
  43098. StandardMaterial._ColorGradingTextureEnabled = true;
  43099. StandardMaterial._FresnelEnabled = true;
  43100. __decorate([
  43101. BABYLON.serializeAsTexture("diffuseTexture")
  43102. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43103. __decorate([
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43105. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43106. __decorate([
  43107. BABYLON.serializeAsTexture("ambientTexture")
  43108. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43109. __decorate([
  43110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43111. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43112. __decorate([
  43113. BABYLON.serializeAsTexture("opacityTexture")
  43114. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43115. __decorate([
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43117. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43118. __decorate([
  43119. BABYLON.serializeAsTexture("reflectionTexture")
  43120. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43121. __decorate([
  43122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43123. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43124. __decorate([
  43125. BABYLON.serializeAsTexture("emissiveTexture")
  43126. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43127. __decorate([
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43129. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43130. __decorate([
  43131. BABYLON.serializeAsTexture("specularTexture")
  43132. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43133. __decorate([
  43134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43135. ], StandardMaterial.prototype, "specularTexture", void 0);
  43136. __decorate([
  43137. BABYLON.serializeAsTexture("bumpTexture")
  43138. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43139. __decorate([
  43140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43141. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43142. __decorate([
  43143. BABYLON.serializeAsTexture("lightmapTexture")
  43144. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43145. __decorate([
  43146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43147. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43148. __decorate([
  43149. BABYLON.serializeAsTexture("refractionTexture")
  43150. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43151. __decorate([
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43154. __decorate([
  43155. BABYLON.serializeAsColor3("ambient")
  43156. ], StandardMaterial.prototype, "ambientColor", void 0);
  43157. __decorate([
  43158. BABYLON.serializeAsColor3("diffuse")
  43159. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43160. __decorate([
  43161. BABYLON.serializeAsColor3("specular")
  43162. ], StandardMaterial.prototype, "specularColor", void 0);
  43163. __decorate([
  43164. BABYLON.serializeAsColor3("emissive")
  43165. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43166. __decorate([
  43167. BABYLON.serialize()
  43168. ], StandardMaterial.prototype, "specularPower", void 0);
  43169. __decorate([
  43170. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43171. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43172. __decorate([
  43173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43174. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43175. __decorate([
  43176. BABYLON.serialize("useEmissiveAsIllumination")
  43177. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43178. __decorate([
  43179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43180. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43181. __decorate([
  43182. BABYLON.serialize("linkEmissiveWithDiffuse")
  43183. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43184. __decorate([
  43185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43186. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43187. __decorate([
  43188. BABYLON.serialize("useSpecularOverAlpha")
  43189. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43190. __decorate([
  43191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43192. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43193. __decorate([
  43194. BABYLON.serialize("useReflectionOverAlpha")
  43195. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43196. __decorate([
  43197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43198. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43199. __decorate([
  43200. BABYLON.serialize("disableLighting")
  43201. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43202. __decorate([
  43203. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43204. ], StandardMaterial.prototype, "disableLighting", void 0);
  43205. __decorate([
  43206. BABYLON.serialize("useObjectSpaceNormalMap")
  43207. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43208. __decorate([
  43209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43210. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43211. __decorate([
  43212. BABYLON.serialize("useParallax")
  43213. ], StandardMaterial.prototype, "_useParallax", void 0);
  43214. __decorate([
  43215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43216. ], StandardMaterial.prototype, "useParallax", void 0);
  43217. __decorate([
  43218. BABYLON.serialize("useParallaxOcclusion")
  43219. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43220. __decorate([
  43221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43222. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43223. __decorate([
  43224. BABYLON.serialize()
  43225. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43226. __decorate([
  43227. BABYLON.serialize("roughness")
  43228. ], StandardMaterial.prototype, "_roughness", void 0);
  43229. __decorate([
  43230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43231. ], StandardMaterial.prototype, "roughness", void 0);
  43232. __decorate([
  43233. BABYLON.serialize()
  43234. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43235. __decorate([
  43236. BABYLON.serialize()
  43237. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43238. __decorate([
  43239. BABYLON.serialize("useLightmapAsShadowmap")
  43240. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43241. __decorate([
  43242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43243. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43244. __decorate([
  43245. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43246. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43247. __decorate([
  43248. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43249. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43250. __decorate([
  43251. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43252. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43253. __decorate([
  43254. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43255. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43256. __decorate([
  43257. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43258. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43259. __decorate([
  43260. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43261. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43262. __decorate([
  43263. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43264. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43265. __decorate([
  43266. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43267. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43268. __decorate([
  43269. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43270. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43271. __decorate([
  43272. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43273. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43274. __decorate([
  43275. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43276. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43277. __decorate([
  43278. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43279. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43280. __decorate([
  43281. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43282. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43283. __decorate([
  43284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43285. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43286. __decorate([
  43287. BABYLON.serialize("maxSimultaneousLights")
  43288. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43289. __decorate([
  43290. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43291. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43292. __decorate([
  43293. BABYLON.serialize("invertNormalMapX")
  43294. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43295. __decorate([
  43296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43297. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43298. __decorate([
  43299. BABYLON.serialize("invertNormalMapY")
  43300. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43301. __decorate([
  43302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43303. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43304. __decorate([
  43305. BABYLON.serialize("twoSidedLighting")
  43306. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43307. __decorate([
  43308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43309. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43310. __decorate([
  43311. BABYLON.serialize()
  43312. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43313. return StandardMaterial;
  43314. }(BABYLON.PushMaterial));
  43315. BABYLON.StandardMaterial = StandardMaterial;
  43316. })(BABYLON || (BABYLON = {}));
  43317. //# sourceMappingURL=babylon.standardMaterial.js.map
  43318. "use strict";
  43319. var BABYLON;
  43320. (function (BABYLON) {
  43321. /**
  43322. * Manages the defines for the PBR Material.
  43323. * @ignoreChildren
  43324. */
  43325. var PBRMaterialDefines = /** @class */ (function (_super) {
  43326. __extends(PBRMaterialDefines, _super);
  43327. /**
  43328. * Initializes the PBR Material defines.
  43329. */
  43330. function PBRMaterialDefines() {
  43331. var _this = _super.call(this) || this;
  43332. _this.PBR = true;
  43333. _this.MAINUV1 = false;
  43334. _this.MAINUV2 = false;
  43335. _this.UV1 = false;
  43336. _this.UV2 = false;
  43337. _this.ALBEDO = false;
  43338. _this.ALBEDODIRECTUV = 0;
  43339. _this.VERTEXCOLOR = false;
  43340. _this.AMBIENT = false;
  43341. _this.AMBIENTDIRECTUV = 0;
  43342. _this.AMBIENTINGRAYSCALE = false;
  43343. _this.OPACITY = false;
  43344. _this.VERTEXALPHA = false;
  43345. _this.OPACITYDIRECTUV = 0;
  43346. _this.OPACITYRGB = false;
  43347. _this.ALPHATEST = false;
  43348. _this.DEPTHPREPASS = false;
  43349. _this.ALPHABLEND = false;
  43350. _this.ALPHAFROMALBEDO = false;
  43351. _this.ALPHATESTVALUE = "0.5";
  43352. _this.SPECULAROVERALPHA = false;
  43353. _this.RADIANCEOVERALPHA = false;
  43354. _this.ALPHAFRESNEL = false;
  43355. _this.LINEARALPHAFRESNEL = false;
  43356. _this.PREMULTIPLYALPHA = false;
  43357. _this.EMISSIVE = false;
  43358. _this.EMISSIVEDIRECTUV = 0;
  43359. _this.REFLECTIVITY = false;
  43360. _this.REFLECTIVITYDIRECTUV = 0;
  43361. _this.SPECULARTERM = false;
  43362. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43363. _this.MICROSURFACEAUTOMATIC = false;
  43364. _this.LODBASEDMICROSFURACE = false;
  43365. _this.MICROSURFACEMAP = false;
  43366. _this.MICROSURFACEMAPDIRECTUV = 0;
  43367. _this.METALLICWORKFLOW = false;
  43368. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43369. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43370. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43371. _this.AOSTOREINMETALMAPRED = false;
  43372. _this.ENVIRONMENTBRDF = false;
  43373. _this.NORMAL = false;
  43374. _this.TANGENT = false;
  43375. _this.BUMP = false;
  43376. _this.BUMPDIRECTUV = 0;
  43377. _this.OBJECTSPACE_NORMALMAP = false;
  43378. _this.PARALLAX = false;
  43379. _this.PARALLAXOCCLUSION = false;
  43380. _this.NORMALXYSCALE = true;
  43381. _this.LIGHTMAP = false;
  43382. _this.LIGHTMAPDIRECTUV = 0;
  43383. _this.USELIGHTMAPASSHADOWMAP = false;
  43384. _this.GAMMALIGHTMAP = false;
  43385. _this.REFLECTION = false;
  43386. _this.REFLECTIONMAP_3D = false;
  43387. _this.REFLECTIONMAP_SPHERICAL = false;
  43388. _this.REFLECTIONMAP_PLANAR = false;
  43389. _this.REFLECTIONMAP_CUBIC = false;
  43390. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43391. _this.REFLECTIONMAP_PROJECTION = false;
  43392. _this.REFLECTIONMAP_SKYBOX = false;
  43393. _this.REFLECTIONMAP_EXPLICIT = false;
  43394. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43395. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43396. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43397. _this.INVERTCUBICMAP = false;
  43398. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43399. _this.USESPHERICALINVERTEX = false;
  43400. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43401. _this.LODINREFLECTIONALPHA = false;
  43402. _this.GAMMAREFLECTION = false;
  43403. _this.RADIANCEOCCLUSION = false;
  43404. _this.HORIZONOCCLUSION = false;
  43405. _this.REFRACTION = false;
  43406. _this.REFRACTIONMAP_3D = false;
  43407. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43408. _this.LODINREFRACTIONALPHA = false;
  43409. _this.GAMMAREFRACTION = false;
  43410. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43411. _this.INSTANCES = false;
  43412. _this.NUM_BONE_INFLUENCERS = 0;
  43413. _this.BonesPerMesh = 0;
  43414. _this.NONUNIFORMSCALING = false;
  43415. _this.MORPHTARGETS = false;
  43416. _this.MORPHTARGETS_NORMAL = false;
  43417. _this.MORPHTARGETS_TANGENT = false;
  43418. _this.NUM_MORPH_INFLUENCERS = 0;
  43419. _this.IMAGEPROCESSING = false;
  43420. _this.VIGNETTE = false;
  43421. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43422. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43423. _this.TONEMAPPING = false;
  43424. _this.CONTRAST = false;
  43425. _this.COLORCURVES = false;
  43426. _this.COLORGRADING = false;
  43427. _this.COLORGRADING3D = false;
  43428. _this.SAMPLER3DGREENDEPTH = false;
  43429. _this.SAMPLER3DBGRMAP = false;
  43430. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43431. _this.EXPOSURE = false;
  43432. _this.USEPHYSICALLIGHTFALLOFF = false;
  43433. _this.TWOSIDEDLIGHTING = false;
  43434. _this.SHADOWFLOAT = false;
  43435. _this.CLIPPLANE = false;
  43436. _this.POINTSIZE = false;
  43437. _this.FOG = false;
  43438. _this.LOGARITHMICDEPTH = false;
  43439. _this.FORCENORMALFORWARD = false;
  43440. _this.GEOMETRYAA = false;
  43441. _this.UNLIT = false;
  43442. _this.rebuild();
  43443. return _this;
  43444. }
  43445. /**
  43446. * Resets the PBR Material defines.
  43447. */
  43448. PBRMaterialDefines.prototype.reset = function () {
  43449. _super.prototype.reset.call(this);
  43450. this.ALPHATESTVALUE = "0.5";
  43451. this.PBR = true;
  43452. };
  43453. return PBRMaterialDefines;
  43454. }(BABYLON.MaterialDefines));
  43455. /**
  43456. * The Physically based material base class of BJS.
  43457. *
  43458. * This offers the main features of a standard PBR material.
  43459. * For more information, please refer to the documentation :
  43460. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43461. */
  43462. var PBRBaseMaterial = /** @class */ (function (_super) {
  43463. __extends(PBRBaseMaterial, _super);
  43464. /**
  43465. * Instantiates a new PBRMaterial instance.
  43466. *
  43467. * @param name The material name
  43468. * @param scene The scene the material will be use in.
  43469. */
  43470. function PBRBaseMaterial(name, scene) {
  43471. var _this = _super.call(this, name, scene) || this;
  43472. /**
  43473. * Intensity of the direct lights e.g. the four lights available in your scene.
  43474. * This impacts both the direct diffuse and specular highlights.
  43475. */
  43476. _this._directIntensity = 1.0;
  43477. /**
  43478. * Intensity of the emissive part of the material.
  43479. * This helps controlling the emissive effect without modifying the emissive color.
  43480. */
  43481. _this._emissiveIntensity = 1.0;
  43482. /**
  43483. * Intensity of the environment e.g. how much the environment will light the object
  43484. * either through harmonics for rough material or through the refelction for shiny ones.
  43485. */
  43486. _this._environmentIntensity = 1.0;
  43487. /**
  43488. * This is a special control allowing the reduction of the specular highlights coming from the
  43489. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43490. */
  43491. _this._specularIntensity = 1.0;
  43492. /**
  43493. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43494. */
  43495. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43496. /**
  43497. * Debug Control allowing disabling the bump map on this material.
  43498. */
  43499. _this._disableBumpMap = false;
  43500. /**
  43501. * AKA Occlusion Texture Intensity in other nomenclature.
  43502. */
  43503. _this._ambientTextureStrength = 1.0;
  43504. /**
  43505. * The color of a material in ambient lighting.
  43506. */
  43507. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43508. /**
  43509. * AKA Diffuse Color in other nomenclature.
  43510. */
  43511. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43512. /**
  43513. * AKA Specular Color in other nomenclature.
  43514. */
  43515. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43516. /**
  43517. * The color applied when light is reflected from a material.
  43518. */
  43519. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43520. /**
  43521. * The color applied when light is emitted from a material.
  43522. */
  43523. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43524. /**
  43525. * AKA Glossiness in other nomenclature.
  43526. */
  43527. _this._microSurface = 0.9;
  43528. /**
  43529. * source material index of refraction (IOR)' / 'destination material IOR.
  43530. */
  43531. _this._indexOfRefraction = 0.66;
  43532. /**
  43533. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43534. */
  43535. _this._invertRefractionY = false;
  43536. /**
  43537. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43538. * Materials half opaque for instance using refraction could benefit from this control.
  43539. */
  43540. _this._linkRefractionWithTransparency = false;
  43541. /**
  43542. * Specifies that the material will use the light map as a show map.
  43543. */
  43544. _this._useLightmapAsShadowmap = false;
  43545. /**
  43546. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43547. * makes the reflect vector face the model (under horizon).
  43548. */
  43549. _this._useHorizonOcclusion = true;
  43550. /**
  43551. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43552. * too much the area relying on ambient texture to define their ambient occlusion.
  43553. */
  43554. _this._useRadianceOcclusion = true;
  43555. /**
  43556. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43557. */
  43558. _this._useAlphaFromAlbedoTexture = false;
  43559. /**
  43560. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43561. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43562. */
  43563. _this._useSpecularOverAlpha = true;
  43564. /**
  43565. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43566. */
  43567. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43568. /**
  43569. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43570. */
  43571. _this._useRoughnessFromMetallicTextureAlpha = true;
  43572. /**
  43573. * Specifies if the metallic texture contains the roughness information in its green channel.
  43574. */
  43575. _this._useRoughnessFromMetallicTextureGreen = false;
  43576. /**
  43577. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43578. */
  43579. _this._useMetallnessFromMetallicTextureBlue = false;
  43580. /**
  43581. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43582. */
  43583. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43584. /**
  43585. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43586. */
  43587. _this._useAmbientInGrayScale = false;
  43588. /**
  43589. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43590. * The material will try to infer what glossiness each pixel should be.
  43591. */
  43592. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43593. /**
  43594. * BJS is using an harcoded light falloff based on a manually sets up range.
  43595. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43596. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43597. */
  43598. _this._usePhysicalLightFalloff = true;
  43599. /**
  43600. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43601. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43602. */
  43603. _this._useRadianceOverAlpha = true;
  43604. /**
  43605. * Allows using an object space normal map (instead of tangent space).
  43606. */
  43607. _this._useObjectSpaceNormalMap = false;
  43608. /**
  43609. * Allows using the bump map in parallax mode.
  43610. */
  43611. _this._useParallax = false;
  43612. /**
  43613. * Allows using the bump map in parallax occlusion mode.
  43614. */
  43615. _this._useParallaxOcclusion = false;
  43616. /**
  43617. * Controls the scale bias of the parallax mode.
  43618. */
  43619. _this._parallaxScaleBias = 0.05;
  43620. /**
  43621. * If sets to true, disables all the lights affecting the material.
  43622. */
  43623. _this._disableLighting = false;
  43624. /**
  43625. * Number of Simultaneous lights allowed on the material.
  43626. */
  43627. _this._maxSimultaneousLights = 4;
  43628. /**
  43629. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43630. */
  43631. _this._invertNormalMapX = false;
  43632. /**
  43633. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43634. */
  43635. _this._invertNormalMapY = false;
  43636. /**
  43637. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43638. */
  43639. _this._twoSidedLighting = false;
  43640. /**
  43641. * Defines the alpha limits in alpha test mode.
  43642. */
  43643. _this._alphaCutOff = 0.4;
  43644. /**
  43645. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43646. */
  43647. _this._forceAlphaTest = false;
  43648. /**
  43649. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43650. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43651. */
  43652. _this._useAlphaFresnel = false;
  43653. /**
  43654. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43655. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43656. */
  43657. _this._useLinearAlphaFresnel = false;
  43658. /**
  43659. * The transparency mode of the material.
  43660. */
  43661. _this._transparencyMode = null;
  43662. /**
  43663. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43664. * from cos thetav and roughness:
  43665. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43666. */
  43667. _this._environmentBRDFTexture = null;
  43668. /**
  43669. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43670. */
  43671. _this._forceIrradianceInFragment = false;
  43672. /**
  43673. * Force normal to face away from face.
  43674. */
  43675. _this._forceNormalForward = false;
  43676. /**
  43677. * Enables specular anti aliasing in the PBR shader.
  43678. * It will both interacts on the Geometry for analytical and IBL lighting.
  43679. * It also prefilter the roughness map based on the bump values.
  43680. */
  43681. _this._enableSpecularAntiAliasing = false;
  43682. /**
  43683. * Stores the available render targets.
  43684. */
  43685. _this._renderTargets = new BABYLON.SmartArray(16);
  43686. /**
  43687. * Sets the global ambient color for the material used in lighting calculations.
  43688. */
  43689. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43690. /**
  43691. * If set to true, no lighting calculations will be applied.
  43692. */
  43693. _this._unlit = false;
  43694. // Setup the default processing configuration to the scene.
  43695. _this._attachImageProcessingConfiguration(null);
  43696. _this.getRenderTargetTextures = function () {
  43697. _this._renderTargets.reset();
  43698. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43699. _this._renderTargets.push(_this._reflectionTexture);
  43700. }
  43701. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43702. _this._renderTargets.push(_this._refractionTexture);
  43703. }
  43704. return _this._renderTargets;
  43705. };
  43706. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43707. return _this;
  43708. }
  43709. /**
  43710. * Attaches a new image processing configuration to the PBR Material.
  43711. * @param configuration
  43712. */
  43713. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43714. var _this = this;
  43715. if (configuration === this._imageProcessingConfiguration) {
  43716. return;
  43717. }
  43718. // Detaches observer.
  43719. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43720. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43721. }
  43722. // Pick the scene configuration if needed.
  43723. if (!configuration) {
  43724. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43725. }
  43726. else {
  43727. this._imageProcessingConfiguration = configuration;
  43728. }
  43729. // Attaches observer.
  43730. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43731. _this._markAllSubMeshesAsImageProcessingDirty();
  43732. });
  43733. };
  43734. /**
  43735. * Gets the name of the material class.
  43736. */
  43737. PBRBaseMaterial.prototype.getClassName = function () {
  43738. return "PBRBaseMaterial";
  43739. };
  43740. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43741. /**
  43742. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43743. */
  43744. get: function () {
  43745. return this._useLogarithmicDepth;
  43746. },
  43747. /**
  43748. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43749. */
  43750. set: function (value) {
  43751. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43752. },
  43753. enumerable: true,
  43754. configurable: true
  43755. });
  43756. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43757. /**
  43758. * Gets the current transparency mode.
  43759. */
  43760. get: function () {
  43761. return this._transparencyMode;
  43762. },
  43763. /**
  43764. * Sets the transparency mode of the material.
  43765. */
  43766. set: function (value) {
  43767. if (this._transparencyMode === value) {
  43768. return;
  43769. }
  43770. this._transparencyMode = value;
  43771. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43772. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43773. },
  43774. enumerable: true,
  43775. configurable: true
  43776. });
  43777. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43778. /**
  43779. * Returns true if alpha blending should be disabled.
  43780. */
  43781. get: function () {
  43782. return (this._linkRefractionWithTransparency ||
  43783. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43784. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43785. },
  43786. enumerable: true,
  43787. configurable: true
  43788. });
  43789. /**
  43790. * Specifies whether or not this material should be rendered in alpha blend mode.
  43791. */
  43792. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43793. if (this._disableAlphaBlending) {
  43794. return false;
  43795. }
  43796. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43797. };
  43798. /**
  43799. * Specifies if the mesh will require alpha blending.
  43800. * @param mesh - BJS mesh.
  43801. */
  43802. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43803. if (this._disableAlphaBlending) {
  43804. return false;
  43805. }
  43806. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43807. };
  43808. /**
  43809. * Specifies whether or not this material should be rendered in alpha test mode.
  43810. */
  43811. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43812. if (this._forceAlphaTest) {
  43813. return true;
  43814. }
  43815. if (this._linkRefractionWithTransparency) {
  43816. return false;
  43817. }
  43818. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43819. };
  43820. /**
  43821. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43822. */
  43823. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43824. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43825. };
  43826. /**
  43827. * Gets the texture used for the alpha test.
  43828. */
  43829. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43830. return this._albedoTexture;
  43831. };
  43832. /**
  43833. * Specifies that the submesh is ready to be used.
  43834. * @param mesh - BJS mesh.
  43835. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43836. * @param useInstances - Specifies that instances should be used.
  43837. * @returns - boolean indicating that the submesh is ready or not.
  43838. */
  43839. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43840. if (subMesh.effect && this.isFrozen) {
  43841. if (this._wasPreviouslyReady) {
  43842. return true;
  43843. }
  43844. }
  43845. if (!subMesh._materialDefines) {
  43846. subMesh._materialDefines = new PBRMaterialDefines();
  43847. }
  43848. var defines = subMesh._materialDefines;
  43849. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43850. if (defines._renderId === this.getScene().getRenderId()) {
  43851. return true;
  43852. }
  43853. }
  43854. var scene = this.getScene();
  43855. var engine = scene.getEngine();
  43856. if (defines._areTexturesDirty) {
  43857. if (scene.texturesEnabled) {
  43858. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43859. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43860. return false;
  43861. }
  43862. }
  43863. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43864. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43865. return false;
  43866. }
  43867. }
  43868. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43869. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43870. return false;
  43871. }
  43872. }
  43873. var reflectionTexture = this._getReflectionTexture();
  43874. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43875. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43876. return false;
  43877. }
  43878. }
  43879. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43880. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43881. return false;
  43882. }
  43883. }
  43884. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43885. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43886. return false;
  43887. }
  43888. }
  43889. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43890. if (this._metallicTexture) {
  43891. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43892. return false;
  43893. }
  43894. }
  43895. else if (this._reflectivityTexture) {
  43896. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43897. return false;
  43898. }
  43899. }
  43900. if (this._microSurfaceTexture) {
  43901. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43902. return false;
  43903. }
  43904. }
  43905. }
  43906. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43907. // Bump texture cannot be not blocking.
  43908. if (!this._bumpTexture.isReady()) {
  43909. return false;
  43910. }
  43911. }
  43912. var refractionTexture = this._getRefractionTexture();
  43913. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43914. if (!refractionTexture.isReadyOrNotBlocking()) {
  43915. return false;
  43916. }
  43917. }
  43918. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43919. // This is blocking.
  43920. if (!this._environmentBRDFTexture.isReady()) {
  43921. return false;
  43922. }
  43923. }
  43924. }
  43925. }
  43926. if (defines._areImageProcessingDirty) {
  43927. if (!this._imageProcessingConfiguration.isReady()) {
  43928. return false;
  43929. }
  43930. }
  43931. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43932. mesh.createNormals(true);
  43933. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43934. }
  43935. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43936. if (effect) {
  43937. scene.resetCachedMaterial();
  43938. subMesh.setEffect(effect, defines);
  43939. this.buildUniformLayout();
  43940. }
  43941. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43942. return false;
  43943. }
  43944. defines._renderId = scene.getRenderId();
  43945. this._wasPreviouslyReady = true;
  43946. return true;
  43947. };
  43948. /**
  43949. * Specifies if the material uses metallic roughness workflow.
  43950. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43951. */
  43952. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43953. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43954. return true;
  43955. }
  43956. return false;
  43957. };
  43958. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43959. if (onCompiled === void 0) { onCompiled = null; }
  43960. if (onError === void 0) { onError = null; }
  43961. if (useInstances === void 0) { useInstances = null; }
  43962. if (useClipPlane === void 0) { useClipPlane = null; }
  43963. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43964. if (!defines.isDirty) {
  43965. return null;
  43966. }
  43967. defines.markAsProcessed();
  43968. var scene = this.getScene();
  43969. var engine = scene.getEngine();
  43970. // Fallbacks
  43971. var fallbacks = new BABYLON.EffectFallbacks();
  43972. var fallbackRank = 0;
  43973. if (defines.USESPHERICALINVERTEX) {
  43974. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43975. }
  43976. if (defines.FOG) {
  43977. fallbacks.addFallback(fallbackRank, "FOG");
  43978. }
  43979. if (defines.POINTSIZE) {
  43980. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43981. }
  43982. if (defines.LOGARITHMICDEPTH) {
  43983. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43984. }
  43985. if (defines.PARALLAX) {
  43986. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43987. }
  43988. if (defines.PARALLAXOCCLUSION) {
  43989. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43990. }
  43991. if (defines.ENVIRONMENTBRDF) {
  43992. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43993. }
  43994. if (defines.TANGENT) {
  43995. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43996. }
  43997. if (defines.BUMP) {
  43998. fallbacks.addFallback(fallbackRank++, "BUMP");
  43999. }
  44000. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44001. if (defines.SPECULARTERM) {
  44002. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44003. }
  44004. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44005. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44006. }
  44007. if (defines.LIGHTMAP) {
  44008. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44009. }
  44010. if (defines.NORMAL) {
  44011. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44012. }
  44013. if (defines.AMBIENT) {
  44014. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44015. }
  44016. if (defines.EMISSIVE) {
  44017. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44018. }
  44019. if (defines.VERTEXCOLOR) {
  44020. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44021. }
  44022. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44023. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44024. }
  44025. if (defines.MORPHTARGETS) {
  44026. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44027. }
  44028. //Attributes
  44029. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44030. if (defines.NORMAL) {
  44031. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44032. }
  44033. if (defines.TANGENT) {
  44034. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44035. }
  44036. if (defines.UV1) {
  44037. attribs.push(BABYLON.VertexBuffer.UVKind);
  44038. }
  44039. if (defines.UV2) {
  44040. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44041. }
  44042. if (defines.VERTEXCOLOR) {
  44043. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44044. }
  44045. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44046. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44047. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44048. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44049. "vFogInfos", "vFogColor", "pointSize",
  44050. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44051. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44052. "mBones",
  44053. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44054. "vLightingIntensity",
  44055. "logarithmicDepthConstant",
  44056. "vSphericalX", "vSphericalY", "vSphericalZ",
  44057. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44058. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44059. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44060. "vTangentSpaceParams"
  44061. ];
  44062. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44063. "bumpSampler", "lightmapSampler", "opacitySampler",
  44064. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44065. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44066. "microSurfaceSampler", "environmentBrdfSampler"];
  44067. var uniformBuffers = ["Material", "Scene"];
  44068. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44069. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44070. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44071. uniformsNames: uniforms,
  44072. uniformBuffersNames: uniformBuffers,
  44073. samplers: samplers,
  44074. defines: defines,
  44075. maxSimultaneousLights: this._maxSimultaneousLights
  44076. });
  44077. var join = defines.toString();
  44078. return engine.createEffect("pbr", {
  44079. attributes: attribs,
  44080. uniformsNames: uniforms,
  44081. uniformBuffersNames: uniformBuffers,
  44082. samplers: samplers,
  44083. defines: join,
  44084. fallbacks: fallbacks,
  44085. onCompiled: onCompiled,
  44086. onError: onError,
  44087. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44088. }, engine);
  44089. };
  44090. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44091. if (useInstances === void 0) { useInstances = null; }
  44092. if (useClipPlane === void 0) { useClipPlane = null; }
  44093. var scene = this.getScene();
  44094. var engine = scene.getEngine();
  44095. // Lights
  44096. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44097. defines._needNormals = true;
  44098. // Textures
  44099. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44100. if (defines._areTexturesDirty) {
  44101. defines._needUVs = false;
  44102. if (scene.texturesEnabled) {
  44103. if (scene.getEngine().getCaps().textureLOD) {
  44104. defines.LODBASEDMICROSFURACE = true;
  44105. }
  44106. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44107. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44108. }
  44109. else {
  44110. defines.ALBEDO = false;
  44111. }
  44112. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44113. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44114. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44115. }
  44116. else {
  44117. defines.AMBIENT = false;
  44118. }
  44119. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44120. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44121. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44122. }
  44123. else {
  44124. defines.OPACITY = false;
  44125. }
  44126. var reflectionTexture = this._getReflectionTexture();
  44127. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44128. defines.REFLECTION = true;
  44129. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44130. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44131. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44132. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44133. defines.INVERTCUBICMAP = true;
  44134. }
  44135. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44136. switch (reflectionTexture.coordinatesMode) {
  44137. case BABYLON.Texture.CUBIC_MODE:
  44138. case BABYLON.Texture.INVCUBIC_MODE:
  44139. defines.REFLECTIONMAP_CUBIC = true;
  44140. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44141. break;
  44142. case BABYLON.Texture.EXPLICIT_MODE:
  44143. defines.REFLECTIONMAP_EXPLICIT = true;
  44144. break;
  44145. case BABYLON.Texture.PLANAR_MODE:
  44146. defines.REFLECTIONMAP_PLANAR = true;
  44147. break;
  44148. case BABYLON.Texture.PROJECTION_MODE:
  44149. defines.REFLECTIONMAP_PROJECTION = true;
  44150. break;
  44151. case BABYLON.Texture.SKYBOX_MODE:
  44152. defines.REFLECTIONMAP_SKYBOX = true;
  44153. break;
  44154. case BABYLON.Texture.SPHERICAL_MODE:
  44155. defines.REFLECTIONMAP_SPHERICAL = true;
  44156. break;
  44157. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44158. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44159. break;
  44160. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44161. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44162. break;
  44163. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44164. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44165. break;
  44166. }
  44167. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44168. if (reflectionTexture.sphericalPolynomial) {
  44169. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44170. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44171. defines.USESPHERICALINVERTEX = false;
  44172. }
  44173. else {
  44174. defines.USESPHERICALINVERTEX = true;
  44175. }
  44176. }
  44177. }
  44178. }
  44179. else {
  44180. defines.REFLECTION = false;
  44181. defines.REFLECTIONMAP_3D = false;
  44182. defines.REFLECTIONMAP_SPHERICAL = false;
  44183. defines.REFLECTIONMAP_PLANAR = false;
  44184. defines.REFLECTIONMAP_CUBIC = false;
  44185. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44186. defines.REFLECTIONMAP_PROJECTION = false;
  44187. defines.REFLECTIONMAP_SKYBOX = false;
  44188. defines.REFLECTIONMAP_EXPLICIT = false;
  44189. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44190. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44191. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44192. defines.INVERTCUBICMAP = false;
  44193. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44194. defines.USESPHERICALINVERTEX = false;
  44195. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44196. defines.LODINREFLECTIONALPHA = false;
  44197. defines.GAMMAREFLECTION = false;
  44198. }
  44199. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44200. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44201. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44202. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44203. }
  44204. else {
  44205. defines.LIGHTMAP = false;
  44206. }
  44207. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44208. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44209. }
  44210. else {
  44211. defines.EMISSIVE = false;
  44212. }
  44213. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44214. if (this._metallicTexture) {
  44215. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44216. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44217. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44218. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44219. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44220. }
  44221. else if (this._reflectivityTexture) {
  44222. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44223. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44224. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44225. }
  44226. else {
  44227. defines.REFLECTIVITY = false;
  44228. }
  44229. if (this._microSurfaceTexture) {
  44230. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44231. }
  44232. else {
  44233. defines.MICROSURFACEMAP = false;
  44234. }
  44235. }
  44236. else {
  44237. defines.REFLECTIVITY = false;
  44238. defines.MICROSURFACEMAP = false;
  44239. }
  44240. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44241. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44242. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44243. defines.PARALLAX = true;
  44244. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44245. }
  44246. else {
  44247. defines.PARALLAX = false;
  44248. }
  44249. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44250. }
  44251. else {
  44252. defines.BUMP = false;
  44253. }
  44254. var refractionTexture = this._getRefractionTexture();
  44255. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44256. defines.REFRACTION = true;
  44257. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44258. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44259. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44260. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44261. if (this._linkRefractionWithTransparency) {
  44262. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44263. }
  44264. }
  44265. else {
  44266. defines.REFRACTION = false;
  44267. }
  44268. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44269. defines.ENVIRONMENTBRDF = true;
  44270. }
  44271. else {
  44272. defines.ENVIRONMENTBRDF = false;
  44273. }
  44274. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44275. defines.ALPHAFROMALBEDO = true;
  44276. }
  44277. else {
  44278. defines.ALPHAFROMALBEDO = false;
  44279. }
  44280. }
  44281. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44282. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44283. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44284. if (!this.backFaceCulling && this._twoSidedLighting) {
  44285. defines.TWOSIDEDLIGHTING = true;
  44286. }
  44287. else {
  44288. defines.TWOSIDEDLIGHTING = false;
  44289. }
  44290. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44291. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44292. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44293. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44294. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44295. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44296. }
  44297. if (defines._areImageProcessingDirty) {
  44298. this._imageProcessingConfiguration.prepareDefines(defines);
  44299. }
  44300. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44301. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44302. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44303. // Misc.
  44304. if (defines._areMiscDirty) {
  44305. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44306. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44307. }
  44308. // Values that need to be evaluated on every frame
  44309. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44310. // Attribs
  44311. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44312. };
  44313. /**
  44314. * Force shader compilation
  44315. */
  44316. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44317. var _this = this;
  44318. var localOptions = __assign({ clipPlane: false }, options);
  44319. var defines = new PBRMaterialDefines();
  44320. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44321. if (effect.isReady()) {
  44322. if (onCompiled) {
  44323. onCompiled(this);
  44324. }
  44325. }
  44326. else {
  44327. effect.onCompileObservable.add(function () {
  44328. if (onCompiled) {
  44329. onCompiled(_this);
  44330. }
  44331. });
  44332. }
  44333. };
  44334. /**
  44335. * Initializes the uniform buffer layout for the shader.
  44336. */
  44337. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44338. // Order is important !
  44339. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44340. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44341. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44342. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44343. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44344. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44345. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44346. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44347. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44348. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44349. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44350. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44351. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44352. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44353. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44354. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44355. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44356. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44357. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44358. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44359. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44360. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44361. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44362. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44363. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44364. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44365. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44366. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44367. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44368. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44369. this._uniformBuffer.addUniform("pointSize", 1);
  44370. this._uniformBuffer.create();
  44371. };
  44372. /**
  44373. * Unbinds the textures.
  44374. */
  44375. PBRBaseMaterial.prototype.unbind = function () {
  44376. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44377. this._uniformBuffer.setTexture("reflectionSampler", null);
  44378. }
  44379. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44380. this._uniformBuffer.setTexture("refractionSampler", null);
  44381. }
  44382. _super.prototype.unbind.call(this);
  44383. };
  44384. /**
  44385. * Binds the submesh data.
  44386. * @param world - The world matrix.
  44387. * @param mesh - The BJS mesh.
  44388. * @param subMesh - A submesh of the BJS mesh.
  44389. */
  44390. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44391. var scene = this.getScene();
  44392. var defines = subMesh._materialDefines;
  44393. if (!defines) {
  44394. return;
  44395. }
  44396. var effect = subMesh.effect;
  44397. if (!effect) {
  44398. return;
  44399. }
  44400. this._activeEffect = effect;
  44401. // Matrices
  44402. this.bindOnlyWorldMatrix(world);
  44403. // Normal Matrix
  44404. if (defines.OBJECTSPACE_NORMALMAP) {
  44405. world.toNormalMatrix(this._normalMatrix);
  44406. this.bindOnlyNormalMatrix(this._normalMatrix);
  44407. }
  44408. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44409. // Bones
  44410. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44411. var reflectionTexture = null;
  44412. if (mustRebind) {
  44413. this._uniformBuffer.bindToEffect(effect, "Material");
  44414. this.bindViewProjection(effect);
  44415. reflectionTexture = this._getReflectionTexture();
  44416. var refractionTexture = this._getRefractionTexture();
  44417. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44418. // Texture uniforms
  44419. if (scene.texturesEnabled) {
  44420. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44421. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44422. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44423. }
  44424. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44425. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44426. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44427. }
  44428. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44429. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44430. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44431. }
  44432. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44433. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44434. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44435. if (reflectionTexture.boundingBoxSize) {
  44436. var cubeTexture = reflectionTexture;
  44437. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44438. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44439. }
  44440. var polynomials = reflectionTexture.sphericalPolynomial;
  44441. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44442. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44443. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44444. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44445. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44446. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44447. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44448. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44449. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44450. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44451. }
  44452. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44453. }
  44454. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44455. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44456. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44457. }
  44458. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44459. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44460. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44461. }
  44462. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44463. if (this._metallicTexture) {
  44464. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44465. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44466. }
  44467. else if (this._reflectivityTexture) {
  44468. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44469. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44470. }
  44471. if (this._microSurfaceTexture) {
  44472. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44473. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44474. }
  44475. }
  44476. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44477. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44478. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44479. if (scene._mirroredCameraPosition) {
  44480. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44481. }
  44482. else {
  44483. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44484. }
  44485. }
  44486. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44487. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44488. var depth = 1.0;
  44489. if (!refractionTexture.isCube) {
  44490. if (refractionTexture.depth) {
  44491. depth = refractionTexture.depth;
  44492. }
  44493. }
  44494. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44495. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44496. }
  44497. }
  44498. // Point size
  44499. if (this.pointsCloud) {
  44500. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44501. }
  44502. // Colors
  44503. if (defines.METALLICWORKFLOW) {
  44504. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44505. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44506. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44507. }
  44508. else {
  44509. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44510. }
  44511. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44512. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44513. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44514. // Misc
  44515. this._lightingInfos.x = this._directIntensity;
  44516. this._lightingInfos.y = this._emissiveIntensity;
  44517. this._lightingInfos.z = this._environmentIntensity;
  44518. this._lightingInfos.w = this._specularIntensity;
  44519. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44520. }
  44521. // Textures
  44522. if (scene.texturesEnabled) {
  44523. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44524. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44525. }
  44526. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44527. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44528. }
  44529. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44530. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44531. }
  44532. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44533. if (defines.LODBASEDMICROSFURACE) {
  44534. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44535. }
  44536. else {
  44537. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44538. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44539. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44540. }
  44541. }
  44542. if (defines.ENVIRONMENTBRDF) {
  44543. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44544. }
  44545. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44546. if (defines.LODBASEDMICROSFURACE) {
  44547. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44548. }
  44549. else {
  44550. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44551. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44552. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44553. }
  44554. }
  44555. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44556. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44557. }
  44558. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44559. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44560. }
  44561. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44562. if (this._metallicTexture) {
  44563. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44564. }
  44565. else if (this._reflectivityTexture) {
  44566. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44567. }
  44568. if (this._microSurfaceTexture) {
  44569. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44570. }
  44571. }
  44572. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44573. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44574. }
  44575. }
  44576. // Clip plane
  44577. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44578. // Colors
  44579. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44580. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44581. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44582. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44583. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44584. }
  44585. if (mustRebind || !this.isFrozen) {
  44586. // Lights
  44587. if (scene.lightsEnabled && !this._disableLighting) {
  44588. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44589. }
  44590. // View
  44591. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44592. this.bindView(effect);
  44593. }
  44594. // Fog
  44595. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44596. // Morph targets
  44597. if (defines.NUM_MORPH_INFLUENCERS) {
  44598. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44599. }
  44600. // image processing
  44601. this._imageProcessingConfiguration.bind(this._activeEffect);
  44602. // Log. depth
  44603. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44604. }
  44605. this._uniformBuffer.update();
  44606. this._afterBind(mesh);
  44607. };
  44608. /**
  44609. * Returns the animatable textures.
  44610. * @returns - Array of animatable textures.
  44611. */
  44612. PBRBaseMaterial.prototype.getAnimatables = function () {
  44613. var results = [];
  44614. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44615. results.push(this._albedoTexture);
  44616. }
  44617. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44618. results.push(this._ambientTexture);
  44619. }
  44620. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44621. results.push(this._opacityTexture);
  44622. }
  44623. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44624. results.push(this._reflectionTexture);
  44625. }
  44626. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44627. results.push(this._emissiveTexture);
  44628. }
  44629. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44630. results.push(this._metallicTexture);
  44631. }
  44632. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44633. results.push(this._reflectivityTexture);
  44634. }
  44635. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44636. results.push(this._bumpTexture);
  44637. }
  44638. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44639. results.push(this._lightmapTexture);
  44640. }
  44641. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44642. results.push(this._refractionTexture);
  44643. }
  44644. return results;
  44645. };
  44646. /**
  44647. * Returns the texture used for reflections.
  44648. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44649. */
  44650. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44651. if (this._reflectionTexture) {
  44652. return this._reflectionTexture;
  44653. }
  44654. return this.getScene().environmentTexture;
  44655. };
  44656. /**
  44657. * Returns the texture used for refraction or null if none is used.
  44658. * @returns - Refection texture if present. If no refraction texture and refraction
  44659. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44660. */
  44661. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44662. if (this._refractionTexture) {
  44663. return this._refractionTexture;
  44664. }
  44665. if (this._linkRefractionWithTransparency) {
  44666. return this.getScene().environmentTexture;
  44667. }
  44668. return null;
  44669. };
  44670. /**
  44671. * Disposes the resources of the material.
  44672. * @param forceDisposeEffect - Forces the disposal of effects.
  44673. * @param forceDisposeTextures - Forces the disposal of all textures.
  44674. */
  44675. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44676. if (forceDisposeTextures) {
  44677. if (this._albedoTexture) {
  44678. this._albedoTexture.dispose();
  44679. }
  44680. if (this._ambientTexture) {
  44681. this._ambientTexture.dispose();
  44682. }
  44683. if (this._opacityTexture) {
  44684. this._opacityTexture.dispose();
  44685. }
  44686. if (this._reflectionTexture) {
  44687. this._reflectionTexture.dispose();
  44688. }
  44689. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44690. this._environmentBRDFTexture.dispose();
  44691. }
  44692. if (this._emissiveTexture) {
  44693. this._emissiveTexture.dispose();
  44694. }
  44695. if (this._metallicTexture) {
  44696. this._metallicTexture.dispose();
  44697. }
  44698. if (this._reflectivityTexture) {
  44699. this._reflectivityTexture.dispose();
  44700. }
  44701. if (this._bumpTexture) {
  44702. this._bumpTexture.dispose();
  44703. }
  44704. if (this._lightmapTexture) {
  44705. this._lightmapTexture.dispose();
  44706. }
  44707. if (this._refractionTexture) {
  44708. this._refractionTexture.dispose();
  44709. }
  44710. }
  44711. this._renderTargets.dispose();
  44712. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44713. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44714. }
  44715. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44716. };
  44717. /**
  44718. * Stores the reflectivity values based on metallic roughness workflow.
  44719. */
  44720. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44721. __decorate([
  44722. BABYLON.serializeAsImageProcessingConfiguration()
  44723. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44724. __decorate([
  44725. BABYLON.serialize()
  44726. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44727. __decorate([
  44728. BABYLON.serialize()
  44729. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44730. return PBRBaseMaterial;
  44731. }(BABYLON.PushMaterial));
  44732. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44733. })(BABYLON || (BABYLON = {}));
  44734. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44735. "use strict";
  44736. var BABYLON;
  44737. (function (BABYLON) {
  44738. /**
  44739. * The Physically based simple base material of BJS.
  44740. *
  44741. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44742. * It is used as the base class for both the specGloss and metalRough conventions.
  44743. */
  44744. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44745. __extends(PBRBaseSimpleMaterial, _super);
  44746. /**
  44747. * Instantiates a new PBRMaterial instance.
  44748. *
  44749. * @param name The material name
  44750. * @param scene The scene the material will be use in.
  44751. */
  44752. function PBRBaseSimpleMaterial(name, scene) {
  44753. var _this = _super.call(this, name, scene) || this;
  44754. /**
  44755. * Number of Simultaneous lights allowed on the material.
  44756. */
  44757. _this.maxSimultaneousLights = 4;
  44758. /**
  44759. * If sets to true, disables all the lights affecting the material.
  44760. */
  44761. _this.disableLighting = false;
  44762. /**
  44763. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44764. */
  44765. _this.invertNormalMapX = false;
  44766. /**
  44767. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44768. */
  44769. _this.invertNormalMapY = false;
  44770. /**
  44771. * Emissivie color used to self-illuminate the model.
  44772. */
  44773. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44774. /**
  44775. * Occlusion Channel Strenght.
  44776. */
  44777. _this.occlusionStrength = 1.0;
  44778. _this.useLightmapAsShadowmap = false;
  44779. _this._useAlphaFromAlbedoTexture = true;
  44780. _this._useAmbientInGrayScale = true;
  44781. return _this;
  44782. }
  44783. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44784. /**
  44785. * Gets the current double sided mode.
  44786. */
  44787. get: function () {
  44788. return this._twoSidedLighting;
  44789. },
  44790. /**
  44791. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44792. */
  44793. set: function (value) {
  44794. if (this._twoSidedLighting === value) {
  44795. return;
  44796. }
  44797. this._twoSidedLighting = value;
  44798. this.backFaceCulling = !value;
  44799. this._markAllSubMeshesAsTexturesDirty();
  44800. },
  44801. enumerable: true,
  44802. configurable: true
  44803. });
  44804. /**
  44805. * Return the active textures of the material.
  44806. */
  44807. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44808. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44809. if (this.environmentTexture) {
  44810. activeTextures.push(this.environmentTexture);
  44811. }
  44812. if (this.normalTexture) {
  44813. activeTextures.push(this.normalTexture);
  44814. }
  44815. if (this.emissiveTexture) {
  44816. activeTextures.push(this.emissiveTexture);
  44817. }
  44818. if (this.occlusionTexture) {
  44819. activeTextures.push(this.occlusionTexture);
  44820. }
  44821. if (this.lightmapTexture) {
  44822. activeTextures.push(this.lightmapTexture);
  44823. }
  44824. return activeTextures;
  44825. };
  44826. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44827. if (_super.prototype.hasTexture.call(this, texture)) {
  44828. return true;
  44829. }
  44830. if (this.lightmapTexture === texture) {
  44831. return true;
  44832. }
  44833. return false;
  44834. };
  44835. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44836. return "PBRBaseSimpleMaterial";
  44837. };
  44838. __decorate([
  44839. BABYLON.serialize(),
  44840. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44841. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44842. __decorate([
  44843. BABYLON.serialize(),
  44844. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44845. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44846. __decorate([
  44847. BABYLON.serializeAsTexture(),
  44848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44849. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44850. __decorate([
  44851. BABYLON.serialize(),
  44852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44853. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44854. __decorate([
  44855. BABYLON.serialize(),
  44856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44857. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44858. __decorate([
  44859. BABYLON.serializeAsTexture(),
  44860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44861. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44862. __decorate([
  44863. BABYLON.serializeAsColor3("emissive"),
  44864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44865. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44866. __decorate([
  44867. BABYLON.serializeAsTexture(),
  44868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44869. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44870. __decorate([
  44871. BABYLON.serialize(),
  44872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44873. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44874. __decorate([
  44875. BABYLON.serializeAsTexture(),
  44876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44877. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44878. __decorate([
  44879. BABYLON.serialize(),
  44880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44881. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44882. __decorate([
  44883. BABYLON.serialize()
  44884. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44885. __decorate([
  44886. BABYLON.serializeAsTexture(),
  44887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44888. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44889. __decorate([
  44890. BABYLON.serialize(),
  44891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44892. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44893. return PBRBaseSimpleMaterial;
  44894. }(BABYLON.PBRBaseMaterial));
  44895. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44896. })(BABYLON || (BABYLON = {}));
  44897. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44898. "use strict";
  44899. var BABYLON;
  44900. (function (BABYLON) {
  44901. /**
  44902. * The Physically based material of BJS.
  44903. *
  44904. * This offers the main features of a standard PBR material.
  44905. * For more information, please refer to the documentation :
  44906. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44907. */
  44908. var PBRMaterial = /** @class */ (function (_super) {
  44909. __extends(PBRMaterial, _super);
  44910. /**
  44911. * Instantiates a new PBRMaterial instance.
  44912. *
  44913. * @param name The material name
  44914. * @param scene The scene the material will be use in.
  44915. */
  44916. function PBRMaterial(name, scene) {
  44917. var _this = _super.call(this, name, scene) || this;
  44918. /**
  44919. * Intensity of the direct lights e.g. the four lights available in your scene.
  44920. * This impacts both the direct diffuse and specular highlights.
  44921. */
  44922. _this.directIntensity = 1.0;
  44923. /**
  44924. * Intensity of the emissive part of the material.
  44925. * This helps controlling the emissive effect without modifying the emissive color.
  44926. */
  44927. _this.emissiveIntensity = 1.0;
  44928. /**
  44929. * Intensity of the environment e.g. how much the environment will light the object
  44930. * either through harmonics for rough material or through the refelction for shiny ones.
  44931. */
  44932. _this.environmentIntensity = 1.0;
  44933. /**
  44934. * This is a special control allowing the reduction of the specular highlights coming from the
  44935. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44936. */
  44937. _this.specularIntensity = 1.0;
  44938. /**
  44939. * Debug Control allowing disabling the bump map on this material.
  44940. */
  44941. _this.disableBumpMap = false;
  44942. /**
  44943. * AKA Occlusion Texture Intensity in other nomenclature.
  44944. */
  44945. _this.ambientTextureStrength = 1.0;
  44946. /**
  44947. * The color of a material in ambient lighting.
  44948. */
  44949. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44950. /**
  44951. * AKA Diffuse Color in other nomenclature.
  44952. */
  44953. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44954. /**
  44955. * AKA Specular Color in other nomenclature.
  44956. */
  44957. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44958. /**
  44959. * The color reflected from the material.
  44960. */
  44961. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44962. /**
  44963. * The color emitted from the material.
  44964. */
  44965. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44966. /**
  44967. * AKA Glossiness in other nomenclature.
  44968. */
  44969. _this.microSurface = 1.0;
  44970. /**
  44971. * source material index of refraction (IOR)' / 'destination material IOR.
  44972. */
  44973. _this.indexOfRefraction = 0.66;
  44974. /**
  44975. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44976. */
  44977. _this.invertRefractionY = false;
  44978. /**
  44979. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44980. * Materials half opaque for instance using refraction could benefit from this control.
  44981. */
  44982. _this.linkRefractionWithTransparency = false;
  44983. _this.useLightmapAsShadowmap = false;
  44984. /**
  44985. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44986. */
  44987. _this.useAlphaFromAlbedoTexture = false;
  44988. /**
  44989. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44990. */
  44991. _this.forceAlphaTest = false;
  44992. /**
  44993. * Defines the alpha limits in alpha test mode.
  44994. */
  44995. _this.alphaCutOff = 0.4;
  44996. /**
  44997. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44998. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44999. */
  45000. _this.useSpecularOverAlpha = true;
  45001. /**
  45002. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45003. */
  45004. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45005. /**
  45006. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45007. */
  45008. _this.useRoughnessFromMetallicTextureAlpha = true;
  45009. /**
  45010. * Specifies if the metallic texture contains the roughness information in its green channel.
  45011. */
  45012. _this.useRoughnessFromMetallicTextureGreen = false;
  45013. /**
  45014. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45015. */
  45016. _this.useMetallnessFromMetallicTextureBlue = false;
  45017. /**
  45018. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45019. */
  45020. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45021. /**
  45022. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45023. */
  45024. _this.useAmbientInGrayScale = false;
  45025. /**
  45026. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45027. * The material will try to infer what glossiness each pixel should be.
  45028. */
  45029. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45030. /**
  45031. * BJS is using an harcoded light falloff based on a manually sets up range.
  45032. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45033. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45034. */
  45035. _this.usePhysicalLightFalloff = true;
  45036. /**
  45037. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45038. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45039. */
  45040. _this.useRadianceOverAlpha = true;
  45041. /**
  45042. * Allows using an object space normal map (instead of tangent space).
  45043. */
  45044. _this.useObjectSpaceNormalMap = false;
  45045. /**
  45046. * Allows using the bump map in parallax mode.
  45047. */
  45048. _this.useParallax = false;
  45049. /**
  45050. * Allows using the bump map in parallax occlusion mode.
  45051. */
  45052. _this.useParallaxOcclusion = false;
  45053. /**
  45054. * Controls the scale bias of the parallax mode.
  45055. */
  45056. _this.parallaxScaleBias = 0.05;
  45057. /**
  45058. * If sets to true, disables all the lights affecting the material.
  45059. */
  45060. _this.disableLighting = false;
  45061. /**
  45062. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45063. */
  45064. _this.forceIrradianceInFragment = false;
  45065. /**
  45066. * Number of Simultaneous lights allowed on the material.
  45067. */
  45068. _this.maxSimultaneousLights = 4;
  45069. /**
  45070. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45071. */
  45072. _this.invertNormalMapX = false;
  45073. /**
  45074. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45075. */
  45076. _this.invertNormalMapY = false;
  45077. /**
  45078. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45079. */
  45080. _this.twoSidedLighting = false;
  45081. /**
  45082. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45083. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45084. */
  45085. _this.useAlphaFresnel = false;
  45086. /**
  45087. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45088. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45089. */
  45090. _this.useLinearAlphaFresnel = false;
  45091. /**
  45092. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45093. * And/Or occlude the blended part.
  45094. */
  45095. _this.environmentBRDFTexture = null;
  45096. /**
  45097. * Force normal to face away from face.
  45098. */
  45099. _this.forceNormalForward = false;
  45100. /**
  45101. * Enables specular anti aliasing in the PBR shader.
  45102. * It will both interacts on the Geometry for analytical and IBL lighting.
  45103. * It also prefilter the roughness map based on the bump values.
  45104. */
  45105. _this.enableSpecularAntiAliasing = false;
  45106. /**
  45107. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45108. * makes the reflect vector face the model (under horizon).
  45109. */
  45110. _this.useHorizonOcclusion = true;
  45111. /**
  45112. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45113. * too much the area relying on ambient texture to define their ambient occlusion.
  45114. */
  45115. _this.useRadianceOcclusion = true;
  45116. /**
  45117. * If set to true, no lighting calculations will be applied.
  45118. */
  45119. _this.unlit = false;
  45120. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45121. return _this;
  45122. }
  45123. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45124. /**
  45125. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45126. */
  45127. get: function () {
  45128. return this._PBRMATERIAL_OPAQUE;
  45129. },
  45130. enumerable: true,
  45131. configurable: true
  45132. });
  45133. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45134. /**
  45135. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45136. */
  45137. get: function () {
  45138. return this._PBRMATERIAL_ALPHATEST;
  45139. },
  45140. enumerable: true,
  45141. configurable: true
  45142. });
  45143. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45144. /**
  45145. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45146. */
  45147. get: function () {
  45148. return this._PBRMATERIAL_ALPHABLEND;
  45149. },
  45150. enumerable: true,
  45151. configurable: true
  45152. });
  45153. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45154. /**
  45155. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45156. * They are also discarded below the alpha cutoff threshold to improve performances.
  45157. */
  45158. get: function () {
  45159. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45160. },
  45161. enumerable: true,
  45162. configurable: true
  45163. });
  45164. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45165. /**
  45166. * Gets the image processing configuration used either in this material.
  45167. */
  45168. get: function () {
  45169. return this._imageProcessingConfiguration;
  45170. },
  45171. /**
  45172. * Sets the Default image processing configuration used either in the this material.
  45173. *
  45174. * If sets to null, the scene one is in use.
  45175. */
  45176. set: function (value) {
  45177. this._attachImageProcessingConfiguration(value);
  45178. // Ensure the effect will be rebuilt.
  45179. this._markAllSubMeshesAsTexturesDirty();
  45180. },
  45181. enumerable: true,
  45182. configurable: true
  45183. });
  45184. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45185. /**
  45186. * Gets wether the color curves effect is enabled.
  45187. */
  45188. get: function () {
  45189. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45190. },
  45191. /**
  45192. * Sets wether the color curves effect is enabled.
  45193. */
  45194. set: function (value) {
  45195. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45196. },
  45197. enumerable: true,
  45198. configurable: true
  45199. });
  45200. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45201. /**
  45202. * Gets wether the color grading effect is enabled.
  45203. */
  45204. get: function () {
  45205. return this.imageProcessingConfiguration.colorGradingEnabled;
  45206. },
  45207. /**
  45208. * Gets wether the color grading effect is enabled.
  45209. */
  45210. set: function (value) {
  45211. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45212. },
  45213. enumerable: true,
  45214. configurable: true
  45215. });
  45216. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45217. /**
  45218. * Gets wether tonemapping is enabled or not.
  45219. */
  45220. get: function () {
  45221. return this._imageProcessingConfiguration.toneMappingEnabled;
  45222. },
  45223. /**
  45224. * Sets wether tonemapping is enabled or not
  45225. */
  45226. set: function (value) {
  45227. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45228. },
  45229. enumerable: true,
  45230. configurable: true
  45231. });
  45232. ;
  45233. ;
  45234. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45235. /**
  45236. * The camera exposure used on this material.
  45237. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45238. * This corresponds to a photographic exposure.
  45239. */
  45240. get: function () {
  45241. return this._imageProcessingConfiguration.exposure;
  45242. },
  45243. /**
  45244. * The camera exposure used on this material.
  45245. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45246. * This corresponds to a photographic exposure.
  45247. */
  45248. set: function (value) {
  45249. this._imageProcessingConfiguration.exposure = value;
  45250. },
  45251. enumerable: true,
  45252. configurable: true
  45253. });
  45254. ;
  45255. ;
  45256. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45257. /**
  45258. * Gets The camera contrast used on this material.
  45259. */
  45260. get: function () {
  45261. return this._imageProcessingConfiguration.contrast;
  45262. },
  45263. /**
  45264. * Sets The camera contrast used on this material.
  45265. */
  45266. set: function (value) {
  45267. this._imageProcessingConfiguration.contrast = value;
  45268. },
  45269. enumerable: true,
  45270. configurable: true
  45271. });
  45272. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45273. /**
  45274. * Gets the Color Grading 2D Lookup Texture.
  45275. */
  45276. get: function () {
  45277. return this._imageProcessingConfiguration.colorGradingTexture;
  45278. },
  45279. /**
  45280. * Sets the Color Grading 2D Lookup Texture.
  45281. */
  45282. set: function (value) {
  45283. this._imageProcessingConfiguration.colorGradingTexture = value;
  45284. },
  45285. enumerable: true,
  45286. configurable: true
  45287. });
  45288. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45289. /**
  45290. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45291. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45292. * 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;
  45293. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45294. */
  45295. get: function () {
  45296. return this._imageProcessingConfiguration.colorCurves;
  45297. },
  45298. /**
  45299. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45300. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45301. * 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;
  45302. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45303. */
  45304. set: function (value) {
  45305. this._imageProcessingConfiguration.colorCurves = value;
  45306. },
  45307. enumerable: true,
  45308. configurable: true
  45309. });
  45310. /**
  45311. * Returns the name of this material class.
  45312. */
  45313. PBRMaterial.prototype.getClassName = function () {
  45314. return "PBRMaterial";
  45315. };
  45316. /**
  45317. * Returns an array of the actively used textures.
  45318. * @returns - Array of BaseTextures
  45319. */
  45320. PBRMaterial.prototype.getActiveTextures = function () {
  45321. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45322. if (this._albedoTexture) {
  45323. activeTextures.push(this._albedoTexture);
  45324. }
  45325. if (this._ambientTexture) {
  45326. activeTextures.push(this._ambientTexture);
  45327. }
  45328. if (this._opacityTexture) {
  45329. activeTextures.push(this._opacityTexture);
  45330. }
  45331. if (this._reflectionTexture) {
  45332. activeTextures.push(this._reflectionTexture);
  45333. }
  45334. if (this._emissiveTexture) {
  45335. activeTextures.push(this._emissiveTexture);
  45336. }
  45337. if (this._reflectivityTexture) {
  45338. activeTextures.push(this._reflectivityTexture);
  45339. }
  45340. if (this._metallicTexture) {
  45341. activeTextures.push(this._metallicTexture);
  45342. }
  45343. if (this._microSurfaceTexture) {
  45344. activeTextures.push(this._microSurfaceTexture);
  45345. }
  45346. if (this._bumpTexture) {
  45347. activeTextures.push(this._bumpTexture);
  45348. }
  45349. if (this._lightmapTexture) {
  45350. activeTextures.push(this._lightmapTexture);
  45351. }
  45352. if (this._refractionTexture) {
  45353. activeTextures.push(this._refractionTexture);
  45354. }
  45355. return activeTextures;
  45356. };
  45357. /**
  45358. * Checks to see if a texture is used in the material.
  45359. * @param texture - Base texture to use.
  45360. * @returns - Boolean specifying if a texture is used in the material.
  45361. */
  45362. PBRMaterial.prototype.hasTexture = function (texture) {
  45363. if (_super.prototype.hasTexture.call(this, texture)) {
  45364. return true;
  45365. }
  45366. if (this._albedoTexture === texture) {
  45367. return true;
  45368. }
  45369. if (this._ambientTexture === texture) {
  45370. return true;
  45371. }
  45372. if (this._opacityTexture === texture) {
  45373. return true;
  45374. }
  45375. if (this._reflectionTexture === texture) {
  45376. return true;
  45377. }
  45378. if (this._reflectivityTexture === texture) {
  45379. return true;
  45380. }
  45381. if (this._metallicTexture === texture) {
  45382. return true;
  45383. }
  45384. if (this._microSurfaceTexture === texture) {
  45385. return true;
  45386. }
  45387. if (this._bumpTexture === texture) {
  45388. return true;
  45389. }
  45390. if (this._lightmapTexture === texture) {
  45391. return true;
  45392. }
  45393. if (this._refractionTexture === texture) {
  45394. return true;
  45395. }
  45396. return false;
  45397. };
  45398. /**
  45399. * Makes a duplicate of the current material.
  45400. * @param name - name to use for the new material.
  45401. */
  45402. PBRMaterial.prototype.clone = function (name) {
  45403. var _this = this;
  45404. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45405. clone.id = name;
  45406. clone.name = name;
  45407. return clone;
  45408. };
  45409. /**
  45410. * Serializes this PBR Material.
  45411. * @returns - An object with the serialized material.
  45412. */
  45413. PBRMaterial.prototype.serialize = function () {
  45414. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45415. serializationObject.customType = "BABYLON.PBRMaterial";
  45416. return serializationObject;
  45417. };
  45418. // Statics
  45419. /**
  45420. * Parses a PBR Material from a serialized object.
  45421. * @param source - Serialized object.
  45422. * @param scene - BJS scene instance.
  45423. * @param rootUrl - url for the scene object
  45424. * @returns - PBRMaterial
  45425. */
  45426. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45427. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45428. };
  45429. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45430. /**
  45431. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45432. */
  45433. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45434. /**
  45435. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45436. */
  45437. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45438. /**
  45439. * 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.
  45440. * They are also discarded below the alpha cutoff threshold to improve performances.
  45441. */
  45442. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45443. __decorate([
  45444. BABYLON.serialize(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45446. ], PBRMaterial.prototype, "directIntensity", void 0);
  45447. __decorate([
  45448. BABYLON.serialize(),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45450. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45451. __decorate([
  45452. BABYLON.serialize(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45455. __decorate([
  45456. BABYLON.serialize(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45459. __decorate([
  45460. BABYLON.serialize(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45463. __decorate([
  45464. BABYLON.serializeAsTexture(),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45467. __decorate([
  45468. BABYLON.serializeAsTexture(),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45471. __decorate([
  45472. BABYLON.serialize(),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45475. __decorate([
  45476. BABYLON.serializeAsTexture(),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45478. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45479. __decorate([
  45480. BABYLON.serializeAsTexture(),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45483. __decorate([
  45484. BABYLON.serializeAsTexture(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45487. __decorate([
  45488. BABYLON.serializeAsTexture(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45491. __decorate([
  45492. BABYLON.serializeAsTexture(),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45494. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45495. __decorate([
  45496. BABYLON.serialize(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45498. ], PBRMaterial.prototype, "metallic", void 0);
  45499. __decorate([
  45500. BABYLON.serialize(),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "roughness", void 0);
  45503. __decorate([
  45504. BABYLON.serializeAsTexture(),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45506. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45507. __decorate([
  45508. BABYLON.serializeAsTexture(),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45510. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45511. __decorate([
  45512. BABYLON.serializeAsTexture(),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45514. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45515. __decorate([
  45516. BABYLON.serializeAsTexture(),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45518. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45519. __decorate([
  45520. BABYLON.serializeAsColor3("ambient"),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45522. ], PBRMaterial.prototype, "ambientColor", void 0);
  45523. __decorate([
  45524. BABYLON.serializeAsColor3("albedo"),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "albedoColor", void 0);
  45527. __decorate([
  45528. BABYLON.serializeAsColor3("reflectivity"),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45531. __decorate([
  45532. BABYLON.serializeAsColor3("reflection"),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45535. __decorate([
  45536. BABYLON.serializeAsColor3("emissive"),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45539. __decorate([
  45540. BABYLON.serialize(),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "microSurface", void 0);
  45543. __decorate([
  45544. BABYLON.serialize(),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45550. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45551. __decorate([
  45552. BABYLON.serialize(),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45554. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45555. __decorate([
  45556. BABYLON.serialize(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45558. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45559. __decorate([
  45560. BABYLON.serialize(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45562. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45566. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45567. __decorate([
  45568. BABYLON.serialize(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45570. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45571. __decorate([
  45572. BABYLON.serialize(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45574. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45578. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45579. __decorate([
  45580. BABYLON.serialize(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45582. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45583. __decorate([
  45584. BABYLON.serialize(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45586. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45603. __decorate([
  45604. BABYLON.serialize(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45607. __decorate([
  45608. BABYLON.serialize(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45611. __decorate([
  45612. BABYLON.serialize(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "useParallax", void 0);
  45619. __decorate([
  45620. BABYLON.serialize(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45622. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45627. __decorate([
  45628. BABYLON.serialize(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45630. ], PBRMaterial.prototype, "disableLighting", void 0);
  45631. __decorate([
  45632. BABYLON.serialize(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45634. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45635. __decorate([
  45636. BABYLON.serialize(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45638. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45639. __decorate([
  45640. BABYLON.serialize(),
  45641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45642. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45643. __decorate([
  45644. BABYLON.serialize(),
  45645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45646. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45647. __decorate([
  45648. BABYLON.serialize(),
  45649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45650. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45651. __decorate([
  45652. BABYLON.serialize(),
  45653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45654. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45655. __decorate([
  45656. BABYLON.serialize(),
  45657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45658. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45659. __decorate([
  45660. BABYLON.serializeAsTexture(),
  45661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45662. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45663. __decorate([
  45664. BABYLON.serialize(),
  45665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45666. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45667. __decorate([
  45668. BABYLON.serialize(),
  45669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45670. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45671. __decorate([
  45672. BABYLON.serialize(),
  45673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45674. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45675. __decorate([
  45676. BABYLON.serialize(),
  45677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45678. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45679. __decorate([
  45680. BABYLON.serialize(),
  45681. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45682. ], PBRMaterial.prototype, "unlit", void 0);
  45683. return PBRMaterial;
  45684. }(BABYLON.PBRBaseMaterial));
  45685. BABYLON.PBRMaterial = PBRMaterial;
  45686. })(BABYLON || (BABYLON = {}));
  45687. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45688. "use strict";
  45689. var BABYLON;
  45690. (function (BABYLON) {
  45691. /**
  45692. * The PBR material of BJS following the metal roughness convention.
  45693. *
  45694. * This fits to the PBR convention in the GLTF definition:
  45695. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45696. */
  45697. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45698. __extends(PBRMetallicRoughnessMaterial, _super);
  45699. /**
  45700. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45701. *
  45702. * @param name The material name
  45703. * @param scene The scene the material will be use in.
  45704. */
  45705. function PBRMetallicRoughnessMaterial(name, scene) {
  45706. var _this = _super.call(this, name, scene) || this;
  45707. _this._useRoughnessFromMetallicTextureAlpha = false;
  45708. _this._useRoughnessFromMetallicTextureGreen = true;
  45709. _this._useMetallnessFromMetallicTextureBlue = true;
  45710. _this.metallic = 1.0;
  45711. _this.roughness = 1.0;
  45712. return _this;
  45713. }
  45714. /**
  45715. * Return the currrent class name of the material.
  45716. */
  45717. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45718. return "PBRMetallicRoughnessMaterial";
  45719. };
  45720. /**
  45721. * Return the active textures of the material.
  45722. */
  45723. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45724. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45725. if (this.baseTexture) {
  45726. activeTextures.push(this.baseTexture);
  45727. }
  45728. if (this.metallicRoughnessTexture) {
  45729. activeTextures.push(this.metallicRoughnessTexture);
  45730. }
  45731. return activeTextures;
  45732. };
  45733. /**
  45734. * Checks to see if a texture is used in the material.
  45735. * @param texture - Base texture to use.
  45736. * @returns - Boolean specifying if a texture is used in the material.
  45737. */
  45738. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45739. if (_super.prototype.hasTexture.call(this, texture)) {
  45740. return true;
  45741. }
  45742. if (this.baseTexture === texture) {
  45743. return true;
  45744. }
  45745. if (this.metallicRoughnessTexture === texture) {
  45746. return true;
  45747. }
  45748. return false;
  45749. };
  45750. /**
  45751. * Makes a duplicate of the current material.
  45752. * @param name - name to use for the new material.
  45753. */
  45754. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45755. var _this = this;
  45756. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45757. clone.id = name;
  45758. clone.name = name;
  45759. return clone;
  45760. };
  45761. /**
  45762. * Serialize the material to a parsable JSON object.
  45763. */
  45764. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45765. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45766. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45767. return serializationObject;
  45768. };
  45769. /**
  45770. * Parses a JSON object correponding to the serialize function.
  45771. */
  45772. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45773. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45774. };
  45775. __decorate([
  45776. BABYLON.serializeAsColor3(),
  45777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45778. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45779. __decorate([
  45780. BABYLON.serializeAsTexture(),
  45781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45782. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45783. __decorate([
  45784. BABYLON.serialize(),
  45785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45786. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45787. __decorate([
  45788. BABYLON.serialize(),
  45789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45790. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45791. __decorate([
  45792. BABYLON.serializeAsTexture(),
  45793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45794. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45795. return PBRMetallicRoughnessMaterial;
  45796. }(BABYLON.PBRBaseSimpleMaterial));
  45797. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45798. })(BABYLON || (BABYLON = {}));
  45799. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45800. "use strict";
  45801. var BABYLON;
  45802. (function (BABYLON) {
  45803. /**
  45804. * The PBR material of BJS following the specular glossiness convention.
  45805. *
  45806. * This fits to the PBR convention in the GLTF definition:
  45807. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45808. */
  45809. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45810. __extends(PBRSpecularGlossinessMaterial, _super);
  45811. /**
  45812. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45813. *
  45814. * @param name The material name
  45815. * @param scene The scene the material will be use in.
  45816. */
  45817. function PBRSpecularGlossinessMaterial(name, scene) {
  45818. var _this = _super.call(this, name, scene) || this;
  45819. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45820. return _this;
  45821. }
  45822. /**
  45823. * Return the currrent class name of the material.
  45824. */
  45825. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45826. return "PBRSpecularGlossinessMaterial";
  45827. };
  45828. /**
  45829. * Return the active textures of the material.
  45830. */
  45831. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45832. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45833. if (this.diffuseTexture) {
  45834. activeTextures.push(this.diffuseTexture);
  45835. }
  45836. if (this.specularGlossinessTexture) {
  45837. activeTextures.push(this.specularGlossinessTexture);
  45838. }
  45839. return activeTextures;
  45840. };
  45841. /**
  45842. * Checks to see if a texture is used in the material.
  45843. * @param texture - Base texture to use.
  45844. * @returns - Boolean specifying if a texture is used in the material.
  45845. */
  45846. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45847. if (_super.prototype.hasTexture.call(this, texture)) {
  45848. return true;
  45849. }
  45850. if (this.diffuseTexture === texture) {
  45851. return true;
  45852. }
  45853. if (this.specularGlossinessTexture === texture) {
  45854. return true;
  45855. }
  45856. return false;
  45857. };
  45858. /**
  45859. * Makes a duplicate of the current material.
  45860. * @param name - name to use for the new material.
  45861. */
  45862. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45863. var _this = this;
  45864. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45865. clone.id = name;
  45866. clone.name = name;
  45867. return clone;
  45868. };
  45869. /**
  45870. * Serialize the material to a parsable JSON object.
  45871. */
  45872. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45873. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45874. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45875. return serializationObject;
  45876. };
  45877. /**
  45878. * Parses a JSON object correponding to the serialize function.
  45879. */
  45880. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45881. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45882. };
  45883. __decorate([
  45884. BABYLON.serializeAsColor3("diffuse"),
  45885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45886. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45887. __decorate([
  45888. BABYLON.serializeAsTexture(),
  45889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45890. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45891. __decorate([
  45892. BABYLON.serializeAsColor3("specular"),
  45893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45894. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45895. __decorate([
  45896. BABYLON.serialize(),
  45897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45898. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45899. __decorate([
  45900. BABYLON.serializeAsTexture(),
  45901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45902. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45903. return PBRSpecularGlossinessMaterial;
  45904. }(BABYLON.PBRBaseSimpleMaterial));
  45905. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45906. })(BABYLON || (BABYLON = {}));
  45907. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45908. "use strict";
  45909. var BABYLON;
  45910. (function (BABYLON) {
  45911. BABYLON.CameraInputTypes = {};
  45912. var CameraInputsManager = /** @class */ (function () {
  45913. function CameraInputsManager(camera) {
  45914. this.attached = {};
  45915. this.camera = camera;
  45916. this.checkInputs = function () { };
  45917. }
  45918. /**
  45919. * Add an input method to a camera.
  45920. * builtin inputs example: camera.inputs.addGamepad();
  45921. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45922. * @param input camera input method
  45923. */
  45924. CameraInputsManager.prototype.add = function (input) {
  45925. var type = input.getSimpleName();
  45926. if (this.attached[type]) {
  45927. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45928. return;
  45929. }
  45930. this.attached[type] = input;
  45931. input.camera = this.camera;
  45932. //for checkInputs, we are dynamically creating a function
  45933. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45934. if (input.checkInputs) {
  45935. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45936. }
  45937. if (this.attachedElement) {
  45938. input.attachControl(this.attachedElement);
  45939. }
  45940. };
  45941. /**
  45942. * Remove a specific input method from a camera
  45943. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45944. * @param inputToRemove camera input method
  45945. */
  45946. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45947. for (var cam in this.attached) {
  45948. var input = this.attached[cam];
  45949. if (input === inputToRemove) {
  45950. input.detachControl(this.attachedElement);
  45951. input.camera = null;
  45952. delete this.attached[cam];
  45953. this.rebuildInputCheck();
  45954. }
  45955. }
  45956. };
  45957. CameraInputsManager.prototype.removeByType = function (inputType) {
  45958. for (var cam in this.attached) {
  45959. var input = this.attached[cam];
  45960. if (input.getClassName() === inputType) {
  45961. input.detachControl(this.attachedElement);
  45962. input.camera = null;
  45963. delete this.attached[cam];
  45964. this.rebuildInputCheck();
  45965. }
  45966. }
  45967. };
  45968. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45969. var current = this.checkInputs;
  45970. return function () {
  45971. current();
  45972. fn();
  45973. };
  45974. };
  45975. CameraInputsManager.prototype.attachInput = function (input) {
  45976. if (this.attachedElement) {
  45977. input.attachControl(this.attachedElement, this.noPreventDefault);
  45978. }
  45979. };
  45980. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45981. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45982. if (this.attachedElement) {
  45983. return;
  45984. }
  45985. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45986. this.attachedElement = element;
  45987. this.noPreventDefault = noPreventDefault;
  45988. for (var cam in this.attached) {
  45989. this.attached[cam].attachControl(element, noPreventDefault);
  45990. }
  45991. };
  45992. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45993. if (disconnect === void 0) { disconnect = false; }
  45994. if (this.attachedElement !== element) {
  45995. return;
  45996. }
  45997. for (var cam in this.attached) {
  45998. this.attached[cam].detachControl(element);
  45999. if (disconnect) {
  46000. this.attached[cam].camera = null;
  46001. }
  46002. }
  46003. this.attachedElement = null;
  46004. };
  46005. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46006. this.checkInputs = function () { };
  46007. for (var cam in this.attached) {
  46008. var input = this.attached[cam];
  46009. if (input.checkInputs) {
  46010. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46011. }
  46012. }
  46013. };
  46014. /**
  46015. * Remove all attached input methods from a camera
  46016. */
  46017. CameraInputsManager.prototype.clear = function () {
  46018. if (this.attachedElement) {
  46019. this.detachElement(this.attachedElement, true);
  46020. }
  46021. this.attached = {};
  46022. this.attachedElement = null;
  46023. this.checkInputs = function () { };
  46024. };
  46025. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46026. var inputs = {};
  46027. for (var cam in this.attached) {
  46028. var input = this.attached[cam];
  46029. var res = BABYLON.SerializationHelper.Serialize(input);
  46030. inputs[input.getClassName()] = res;
  46031. }
  46032. serializedCamera.inputsmgr = inputs;
  46033. };
  46034. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46035. var parsedInputs = parsedCamera.inputsmgr;
  46036. if (parsedInputs) {
  46037. this.clear();
  46038. for (var n in parsedInputs) {
  46039. var construct = BABYLON.CameraInputTypes[n];
  46040. if (construct) {
  46041. var parsedinput = parsedInputs[n];
  46042. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46043. this.add(input);
  46044. }
  46045. }
  46046. }
  46047. else {
  46048. //2016-03-08 this part is for managing backward compatibility
  46049. for (var n in this.attached) {
  46050. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46051. if (construct) {
  46052. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46053. this.remove(this.attached[n]);
  46054. this.add(input);
  46055. }
  46056. }
  46057. }
  46058. };
  46059. return CameraInputsManager;
  46060. }());
  46061. BABYLON.CameraInputsManager = CameraInputsManager;
  46062. })(BABYLON || (BABYLON = {}));
  46063. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46064. "use strict";
  46065. var BABYLON;
  46066. (function (BABYLON) {
  46067. var TargetCamera = /** @class */ (function (_super) {
  46068. __extends(TargetCamera, _super);
  46069. function TargetCamera(name, position, scene) {
  46070. var _this = _super.call(this, name, position, scene) || this;
  46071. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46072. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46073. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46074. _this.speed = 2.0;
  46075. _this.noRotationConstraint = false;
  46076. _this.lockedTarget = null;
  46077. _this._currentTarget = BABYLON.Vector3.Zero();
  46078. _this._viewMatrix = BABYLON.Matrix.Zero();
  46079. _this._camMatrix = BABYLON.Matrix.Zero();
  46080. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46081. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46082. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46083. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46084. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46085. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46086. _this._tempMatrix = BABYLON.Matrix.Zero();
  46087. return _this;
  46088. }
  46089. TargetCamera.prototype.getFrontPosition = function (distance) {
  46090. this.getWorldMatrix();
  46091. var direction = this.getTarget().subtract(this.position);
  46092. direction.normalize();
  46093. direction.scaleInPlace(distance);
  46094. return this.globalPosition.add(direction);
  46095. };
  46096. TargetCamera.prototype._getLockedTargetPosition = function () {
  46097. if (!this.lockedTarget) {
  46098. return null;
  46099. }
  46100. if (this.lockedTarget.absolutePosition) {
  46101. this.lockedTarget.computeWorldMatrix();
  46102. }
  46103. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46104. };
  46105. TargetCamera.prototype.storeState = function () {
  46106. this._storedPosition = this.position.clone();
  46107. this._storedRotation = this.rotation.clone();
  46108. if (this.rotationQuaternion) {
  46109. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46110. }
  46111. return _super.prototype.storeState.call(this);
  46112. };
  46113. /**
  46114. * Restored camera state. You must call storeState() first
  46115. */
  46116. TargetCamera.prototype._restoreStateValues = function () {
  46117. if (!_super.prototype._restoreStateValues.call(this)) {
  46118. return false;
  46119. }
  46120. this.position = this._storedPosition.clone();
  46121. this.rotation = this._storedRotation.clone();
  46122. if (this.rotationQuaternion) {
  46123. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46124. }
  46125. this.cameraDirection.copyFromFloats(0, 0, 0);
  46126. this.cameraRotation.copyFromFloats(0, 0);
  46127. return true;
  46128. };
  46129. // Cache
  46130. TargetCamera.prototype._initCache = function () {
  46131. _super.prototype._initCache.call(this);
  46132. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46133. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46134. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46135. };
  46136. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46137. if (!ignoreParentClass) {
  46138. _super.prototype._updateCache.call(this);
  46139. }
  46140. var lockedTargetPosition = this._getLockedTargetPosition();
  46141. if (!lockedTargetPosition) {
  46142. this._cache.lockedTarget = null;
  46143. }
  46144. else {
  46145. if (!this._cache.lockedTarget) {
  46146. this._cache.lockedTarget = lockedTargetPosition.clone();
  46147. }
  46148. else {
  46149. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46150. }
  46151. }
  46152. this._cache.rotation.copyFrom(this.rotation);
  46153. if (this.rotationQuaternion)
  46154. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46155. };
  46156. // Synchronized
  46157. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46158. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46159. return false;
  46160. }
  46161. var lockedTargetPosition = this._getLockedTargetPosition();
  46162. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46163. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46164. };
  46165. // Methods
  46166. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46167. var engine = this.getEngine();
  46168. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46169. };
  46170. // Target
  46171. TargetCamera.prototype.setTarget = function (target) {
  46172. this.upVector.normalize();
  46173. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46174. this._camMatrix.invert();
  46175. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46176. var vDir = target.subtract(this.position);
  46177. if (vDir.x >= 0.0) {
  46178. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46179. }
  46180. else {
  46181. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46182. }
  46183. this.rotation.z = 0;
  46184. if (isNaN(this.rotation.x)) {
  46185. this.rotation.x = 0;
  46186. }
  46187. if (isNaN(this.rotation.y)) {
  46188. this.rotation.y = 0;
  46189. }
  46190. if (isNaN(this.rotation.z)) {
  46191. this.rotation.z = 0;
  46192. }
  46193. if (this.rotationQuaternion) {
  46194. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46195. }
  46196. };
  46197. /**
  46198. * Return the current target position of the camera. This value is expressed in local space.
  46199. */
  46200. TargetCamera.prototype.getTarget = function () {
  46201. return this._currentTarget;
  46202. };
  46203. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46204. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46205. };
  46206. TargetCamera.prototype._updatePosition = function () {
  46207. if (this.parent) {
  46208. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46209. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46210. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46211. return;
  46212. }
  46213. this.position.addInPlace(this.cameraDirection);
  46214. };
  46215. TargetCamera.prototype._checkInputs = function () {
  46216. var needToMove = this._decideIfNeedsToMove();
  46217. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46218. // Move
  46219. if (needToMove) {
  46220. this._updatePosition();
  46221. }
  46222. // Rotate
  46223. if (needToRotate) {
  46224. this.rotation.x += this.cameraRotation.x;
  46225. this.rotation.y += this.cameraRotation.y;
  46226. //rotate, if quaternion is set and rotation was used
  46227. if (this.rotationQuaternion) {
  46228. var len = this.rotation.lengthSquared();
  46229. if (len) {
  46230. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46231. }
  46232. }
  46233. if (!this.noRotationConstraint) {
  46234. var limit = (Math.PI / 2) * 0.95;
  46235. if (this.rotation.x > limit)
  46236. this.rotation.x = limit;
  46237. if (this.rotation.x < -limit)
  46238. this.rotation.x = -limit;
  46239. }
  46240. }
  46241. // Inertia
  46242. if (needToMove) {
  46243. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46244. this.cameraDirection.x = 0;
  46245. }
  46246. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46247. this.cameraDirection.y = 0;
  46248. }
  46249. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46250. this.cameraDirection.z = 0;
  46251. }
  46252. this.cameraDirection.scaleInPlace(this.inertia);
  46253. }
  46254. if (needToRotate) {
  46255. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46256. this.cameraRotation.x = 0;
  46257. }
  46258. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46259. this.cameraRotation.y = 0;
  46260. }
  46261. this.cameraRotation.scaleInPlace(this.inertia);
  46262. }
  46263. _super.prototype._checkInputs.call(this);
  46264. };
  46265. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46266. if (this.rotationQuaternion) {
  46267. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46268. }
  46269. else {
  46270. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46271. }
  46272. //update the up vector!
  46273. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46274. };
  46275. TargetCamera.prototype._getViewMatrix = function () {
  46276. if (this.lockedTarget) {
  46277. this.setTarget(this._getLockedTargetPosition());
  46278. }
  46279. // Compute
  46280. this._updateCameraRotationMatrix();
  46281. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46282. // Computing target and final matrix
  46283. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46284. if (this.getScene().useRightHandedSystem) {
  46285. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46286. }
  46287. else {
  46288. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46289. }
  46290. return this._viewMatrix;
  46291. };
  46292. /**
  46293. * @override
  46294. * Override Camera.createRigCamera
  46295. */
  46296. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46297. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46298. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46299. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46300. if (!this.rotationQuaternion) {
  46301. this.rotationQuaternion = new BABYLON.Quaternion();
  46302. }
  46303. rigCamera._cameraRigParams = {};
  46304. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46305. }
  46306. return rigCamera;
  46307. }
  46308. return null;
  46309. };
  46310. /**
  46311. * @override
  46312. * Override Camera._updateRigCameras
  46313. */
  46314. TargetCamera.prototype._updateRigCameras = function () {
  46315. var camLeft = this._rigCameras[0];
  46316. var camRight = this._rigCameras[1];
  46317. switch (this.cameraRigMode) {
  46318. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46319. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46320. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46321. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46322. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46323. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46324. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46325. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46326. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46327. camLeft.setTarget(this.getTarget());
  46328. camRight.setTarget(this.getTarget());
  46329. break;
  46330. case BABYLON.Camera.RIG_MODE_VR:
  46331. if (camLeft.rotationQuaternion) {
  46332. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46333. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46334. }
  46335. else {
  46336. camLeft.rotation.copyFrom(this.rotation);
  46337. camRight.rotation.copyFrom(this.rotation);
  46338. }
  46339. camLeft.position.copyFrom(this.position);
  46340. camRight.position.copyFrom(this.position);
  46341. break;
  46342. }
  46343. _super.prototype._updateRigCameras.call(this);
  46344. };
  46345. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46346. if (!this._rigCamTransformMatrix) {
  46347. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46348. }
  46349. var target = this.getTarget();
  46350. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46351. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46352. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46353. };
  46354. TargetCamera.prototype.getClassName = function () {
  46355. return "TargetCamera";
  46356. };
  46357. __decorate([
  46358. BABYLON.serializeAsVector3()
  46359. ], TargetCamera.prototype, "rotation", void 0);
  46360. __decorate([
  46361. BABYLON.serialize()
  46362. ], TargetCamera.prototype, "speed", void 0);
  46363. __decorate([
  46364. BABYLON.serializeAsMeshReference("lockedTargetId")
  46365. ], TargetCamera.prototype, "lockedTarget", void 0);
  46366. return TargetCamera;
  46367. }(BABYLON.Camera));
  46368. BABYLON.TargetCamera = TargetCamera;
  46369. })(BABYLON || (BABYLON = {}));
  46370. //# sourceMappingURL=babylon.targetCamera.js.map
  46371. "use strict";
  46372. var BABYLON;
  46373. (function (BABYLON) {
  46374. var FreeCameraMouseInput = /** @class */ (function () {
  46375. function FreeCameraMouseInput(touchEnabled) {
  46376. if (touchEnabled === void 0) { touchEnabled = true; }
  46377. this.touchEnabled = touchEnabled;
  46378. this.buttons = [0, 1, 2];
  46379. this.angularSensibility = 2000.0;
  46380. this.previousPosition = null;
  46381. }
  46382. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46383. var _this = this;
  46384. var engine = this.camera.getEngine();
  46385. if (!this._pointerInput) {
  46386. this._pointerInput = function (p, s) {
  46387. var evt = p.event;
  46388. if (engine.isInVRExclusivePointerMode) {
  46389. return;
  46390. }
  46391. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46392. return;
  46393. }
  46394. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46395. return;
  46396. }
  46397. var srcElement = (evt.srcElement || evt.target);
  46398. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46399. try {
  46400. srcElement.setPointerCapture(evt.pointerId);
  46401. }
  46402. catch (e) {
  46403. //Nothing to do with the error. Execution will continue.
  46404. }
  46405. _this.previousPosition = {
  46406. x: evt.clientX,
  46407. y: evt.clientY
  46408. };
  46409. if (!noPreventDefault) {
  46410. evt.preventDefault();
  46411. element.focus();
  46412. }
  46413. }
  46414. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46415. try {
  46416. srcElement.releasePointerCapture(evt.pointerId);
  46417. }
  46418. catch (e) {
  46419. //Nothing to do with the error.
  46420. }
  46421. _this.previousPosition = null;
  46422. if (!noPreventDefault) {
  46423. evt.preventDefault();
  46424. }
  46425. }
  46426. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46427. if (!_this.previousPosition || engine.isPointerLock) {
  46428. return;
  46429. }
  46430. var offsetX = evt.clientX - _this.previousPosition.x;
  46431. var offsetY = evt.clientY - _this.previousPosition.y;
  46432. if (_this.camera.getScene().useRightHandedSystem) {
  46433. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46434. }
  46435. else {
  46436. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46437. }
  46438. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46439. _this.previousPosition = {
  46440. x: evt.clientX,
  46441. y: evt.clientY
  46442. };
  46443. if (!noPreventDefault) {
  46444. evt.preventDefault();
  46445. }
  46446. }
  46447. };
  46448. }
  46449. this._onMouseMove = function (evt) {
  46450. if (!engine.isPointerLock) {
  46451. return;
  46452. }
  46453. if (engine.isInVRExclusivePointerMode) {
  46454. return;
  46455. }
  46456. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46457. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46458. if (_this.camera.getScene().useRightHandedSystem) {
  46459. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46460. }
  46461. else {
  46462. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46463. }
  46464. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46465. _this.previousPosition = null;
  46466. if (!noPreventDefault) {
  46467. evt.preventDefault();
  46468. }
  46469. };
  46470. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46471. element.addEventListener("mousemove", this._onMouseMove, false);
  46472. };
  46473. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46474. if (this._observer && element) {
  46475. this.camera.getScene().onPointerObservable.remove(this._observer);
  46476. if (this._onMouseMove) {
  46477. element.removeEventListener("mousemove", this._onMouseMove);
  46478. }
  46479. this._observer = null;
  46480. this._onMouseMove = null;
  46481. this.previousPosition = null;
  46482. }
  46483. };
  46484. FreeCameraMouseInput.prototype.getClassName = function () {
  46485. return "FreeCameraMouseInput";
  46486. };
  46487. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46488. return "mouse";
  46489. };
  46490. __decorate([
  46491. BABYLON.serialize()
  46492. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46493. __decorate([
  46494. BABYLON.serialize()
  46495. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46496. return FreeCameraMouseInput;
  46497. }());
  46498. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46499. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46500. })(BABYLON || (BABYLON = {}));
  46501. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46502. "use strict";
  46503. var BABYLON;
  46504. (function (BABYLON) {
  46505. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46506. function FreeCameraKeyboardMoveInput() {
  46507. this._keys = new Array();
  46508. this.keysUp = [38];
  46509. this.keysDown = [40];
  46510. this.keysLeft = [37];
  46511. this.keysRight = [39];
  46512. }
  46513. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46514. var _this = this;
  46515. if (this._onCanvasBlurObserver) {
  46516. return;
  46517. }
  46518. this._scene = this.camera.getScene();
  46519. this._engine = this._scene.getEngine();
  46520. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46521. _this._keys = [];
  46522. });
  46523. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46524. var evt = info.event;
  46525. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46526. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46527. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46528. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46529. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46530. var index = _this._keys.indexOf(evt.keyCode);
  46531. if (index === -1) {
  46532. _this._keys.push(evt.keyCode);
  46533. }
  46534. if (!noPreventDefault) {
  46535. evt.preventDefault();
  46536. }
  46537. }
  46538. }
  46539. else {
  46540. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46541. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46542. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46543. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46544. var index = _this._keys.indexOf(evt.keyCode);
  46545. if (index >= 0) {
  46546. _this._keys.splice(index, 1);
  46547. }
  46548. if (!noPreventDefault) {
  46549. evt.preventDefault();
  46550. }
  46551. }
  46552. }
  46553. });
  46554. };
  46555. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46556. if (this._scene) {
  46557. if (this._onKeyboardObserver) {
  46558. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46559. }
  46560. if (this._onCanvasBlurObserver) {
  46561. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46562. }
  46563. this._onKeyboardObserver = null;
  46564. this._onCanvasBlurObserver = null;
  46565. }
  46566. this._keys = [];
  46567. };
  46568. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46569. if (this._onKeyboardObserver) {
  46570. var camera = this.camera;
  46571. // Keyboard
  46572. for (var index = 0; index < this._keys.length; index++) {
  46573. var keyCode = this._keys[index];
  46574. var speed = camera._computeLocalCameraSpeed();
  46575. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46576. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46577. }
  46578. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46579. camera._localDirection.copyFromFloats(0, 0, speed);
  46580. }
  46581. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46582. camera._localDirection.copyFromFloats(speed, 0, 0);
  46583. }
  46584. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46585. camera._localDirection.copyFromFloats(0, 0, -speed);
  46586. }
  46587. if (camera.getScene().useRightHandedSystem) {
  46588. camera._localDirection.z *= -1;
  46589. }
  46590. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46591. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46592. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46593. }
  46594. }
  46595. };
  46596. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46597. return "FreeCameraKeyboardMoveInput";
  46598. };
  46599. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46600. this._keys = [];
  46601. };
  46602. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46603. return "keyboard";
  46604. };
  46605. __decorate([
  46606. BABYLON.serialize()
  46607. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46608. __decorate([
  46609. BABYLON.serialize()
  46610. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46611. __decorate([
  46612. BABYLON.serialize()
  46613. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46614. __decorate([
  46615. BABYLON.serialize()
  46616. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46617. return FreeCameraKeyboardMoveInput;
  46618. }());
  46619. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46620. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46621. })(BABYLON || (BABYLON = {}));
  46622. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46623. "use strict";
  46624. var BABYLON;
  46625. (function (BABYLON) {
  46626. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46627. __extends(FreeCameraInputsManager, _super);
  46628. function FreeCameraInputsManager(camera) {
  46629. return _super.call(this, camera) || this;
  46630. }
  46631. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46632. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46633. return this;
  46634. };
  46635. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46636. if (touchEnabled === void 0) { touchEnabled = true; }
  46637. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46638. return this;
  46639. };
  46640. FreeCameraInputsManager.prototype.addGamepad = function () {
  46641. this.add(new BABYLON.FreeCameraGamepadInput());
  46642. return this;
  46643. };
  46644. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46645. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46646. return this;
  46647. };
  46648. FreeCameraInputsManager.prototype.addTouch = function () {
  46649. this.add(new BABYLON.FreeCameraTouchInput());
  46650. return this;
  46651. };
  46652. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46653. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46654. return this;
  46655. };
  46656. return FreeCameraInputsManager;
  46657. }(BABYLON.CameraInputsManager));
  46658. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46659. })(BABYLON || (BABYLON = {}));
  46660. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46661. "use strict";
  46662. var BABYLON;
  46663. (function (BABYLON) {
  46664. var FreeCamera = /** @class */ (function (_super) {
  46665. __extends(FreeCamera, _super);
  46666. function FreeCamera(name, position, scene) {
  46667. var _this = _super.call(this, name, position, scene) || this;
  46668. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46669. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46670. _this.checkCollisions = false;
  46671. _this.applyGravity = false;
  46672. _this._needMoveForGravity = false;
  46673. _this._oldPosition = BABYLON.Vector3.Zero();
  46674. _this._diffPosition = BABYLON.Vector3.Zero();
  46675. _this._newPosition = BABYLON.Vector3.Zero();
  46676. // Collisions
  46677. _this._collisionMask = -1;
  46678. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46679. if (collidedMesh === void 0) { collidedMesh = null; }
  46680. //TODO move this to the collision coordinator!
  46681. if (_this.getScene().workerCollisions)
  46682. newPosition.multiplyInPlace(_this._collider._radius);
  46683. var updatePosition = function (newPos) {
  46684. _this._newPosition.copyFrom(newPos);
  46685. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46686. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46687. _this.position.addInPlace(_this._diffPosition);
  46688. if (_this.onCollide && collidedMesh) {
  46689. _this.onCollide(collidedMesh);
  46690. }
  46691. }
  46692. };
  46693. updatePosition(newPosition);
  46694. };
  46695. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46696. _this.inputs.addKeyboard().addMouse();
  46697. return _this;
  46698. }
  46699. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46700. //-- begin properties for backward compatibility for inputs
  46701. /**
  46702. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46703. * Higher values reduce sensitivity.
  46704. */
  46705. get: function () {
  46706. var mouse = this.inputs.attached["mouse"];
  46707. if (mouse)
  46708. return mouse.angularSensibility;
  46709. return 0;
  46710. },
  46711. /**
  46712. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46713. * Higher values reduce sensitivity.
  46714. */
  46715. set: function (value) {
  46716. var mouse = this.inputs.attached["mouse"];
  46717. if (mouse)
  46718. mouse.angularSensibility = value;
  46719. },
  46720. enumerable: true,
  46721. configurable: true
  46722. });
  46723. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46724. get: function () {
  46725. var keyboard = this.inputs.attached["keyboard"];
  46726. if (keyboard)
  46727. return keyboard.keysUp;
  46728. return [];
  46729. },
  46730. set: function (value) {
  46731. var keyboard = this.inputs.attached["keyboard"];
  46732. if (keyboard)
  46733. keyboard.keysUp = value;
  46734. },
  46735. enumerable: true,
  46736. configurable: true
  46737. });
  46738. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46739. get: function () {
  46740. var keyboard = this.inputs.attached["keyboard"];
  46741. if (keyboard)
  46742. return keyboard.keysDown;
  46743. return [];
  46744. },
  46745. set: function (value) {
  46746. var keyboard = this.inputs.attached["keyboard"];
  46747. if (keyboard)
  46748. keyboard.keysDown = value;
  46749. },
  46750. enumerable: true,
  46751. configurable: true
  46752. });
  46753. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46754. get: function () {
  46755. var keyboard = this.inputs.attached["keyboard"];
  46756. if (keyboard)
  46757. return keyboard.keysLeft;
  46758. return [];
  46759. },
  46760. set: function (value) {
  46761. var keyboard = this.inputs.attached["keyboard"];
  46762. if (keyboard)
  46763. keyboard.keysLeft = value;
  46764. },
  46765. enumerable: true,
  46766. configurable: true
  46767. });
  46768. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46769. get: function () {
  46770. var keyboard = this.inputs.attached["keyboard"];
  46771. if (keyboard)
  46772. return keyboard.keysRight;
  46773. return [];
  46774. },
  46775. set: function (value) {
  46776. var keyboard = this.inputs.attached["keyboard"];
  46777. if (keyboard)
  46778. keyboard.keysRight = value;
  46779. },
  46780. enumerable: true,
  46781. configurable: true
  46782. });
  46783. // Controls
  46784. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46785. this.inputs.attachElement(element, noPreventDefault);
  46786. };
  46787. FreeCamera.prototype.detachControl = function (element) {
  46788. this.inputs.detachElement(element);
  46789. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46790. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46791. };
  46792. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46793. get: function () {
  46794. return this._collisionMask;
  46795. },
  46796. set: function (mask) {
  46797. this._collisionMask = !isNaN(mask) ? mask : -1;
  46798. },
  46799. enumerable: true,
  46800. configurable: true
  46801. });
  46802. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46803. var globalPosition;
  46804. if (this.parent) {
  46805. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46806. }
  46807. else {
  46808. globalPosition = this.position;
  46809. }
  46810. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46811. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46812. if (!this._collider) {
  46813. this._collider = new BABYLON.Collider();
  46814. }
  46815. this._collider._radius = this.ellipsoid;
  46816. this._collider.collisionMask = this._collisionMask;
  46817. //no need for clone, as long as gravity is not on.
  46818. var actualDisplacement = displacement;
  46819. //add gravity to the direction to prevent the dual-collision checking
  46820. if (this.applyGravity) {
  46821. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46822. actualDisplacement = displacement.add(this.getScene().gravity);
  46823. }
  46824. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46825. };
  46826. FreeCamera.prototype._checkInputs = function () {
  46827. if (!this._localDirection) {
  46828. this._localDirection = BABYLON.Vector3.Zero();
  46829. this._transformedDirection = BABYLON.Vector3.Zero();
  46830. }
  46831. this.inputs.checkInputs();
  46832. _super.prototype._checkInputs.call(this);
  46833. };
  46834. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46835. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46836. };
  46837. FreeCamera.prototype._updatePosition = function () {
  46838. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46839. this._collideWithWorld(this.cameraDirection);
  46840. }
  46841. else {
  46842. _super.prototype._updatePosition.call(this);
  46843. }
  46844. };
  46845. FreeCamera.prototype.dispose = function () {
  46846. this.inputs.clear();
  46847. _super.prototype.dispose.call(this);
  46848. };
  46849. FreeCamera.prototype.getClassName = function () {
  46850. return "FreeCamera";
  46851. };
  46852. __decorate([
  46853. BABYLON.serializeAsVector3()
  46854. ], FreeCamera.prototype, "ellipsoid", void 0);
  46855. __decorate([
  46856. BABYLON.serializeAsVector3()
  46857. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46858. __decorate([
  46859. BABYLON.serialize()
  46860. ], FreeCamera.prototype, "checkCollisions", void 0);
  46861. __decorate([
  46862. BABYLON.serialize()
  46863. ], FreeCamera.prototype, "applyGravity", void 0);
  46864. return FreeCamera;
  46865. }(BABYLON.TargetCamera));
  46866. BABYLON.FreeCamera = FreeCamera;
  46867. })(BABYLON || (BABYLON = {}));
  46868. //# sourceMappingURL=babylon.freeCamera.js.map
  46869. "use strict";
  46870. var BABYLON;
  46871. (function (BABYLON) {
  46872. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46873. function ArcRotateCameraKeyboardMoveInput() {
  46874. this._keys = new Array();
  46875. this.keysUp = [38];
  46876. this.keysDown = [40];
  46877. this.keysLeft = [37];
  46878. this.keysRight = [39];
  46879. this.keysReset = [220];
  46880. this.panningSensibility = 50.0;
  46881. this.zoomingSensibility = 25.0;
  46882. this.useAltToZoom = true;
  46883. }
  46884. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46885. var _this = this;
  46886. if (this._onCanvasBlurObserver) {
  46887. return;
  46888. }
  46889. this._scene = this.camera.getScene();
  46890. this._engine = this._scene.getEngine();
  46891. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46892. _this._keys = [];
  46893. });
  46894. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46895. var evt = info.event;
  46896. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46897. _this._ctrlPressed = evt.ctrlKey;
  46898. _this._altPressed = evt.altKey;
  46899. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46900. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46901. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46902. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46903. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46904. var index = _this._keys.indexOf(evt.keyCode);
  46905. if (index === -1) {
  46906. _this._keys.push(evt.keyCode);
  46907. }
  46908. if (evt.preventDefault) {
  46909. if (!noPreventDefault) {
  46910. evt.preventDefault();
  46911. }
  46912. }
  46913. }
  46914. }
  46915. else {
  46916. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46917. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46918. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46919. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46920. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46921. var index = _this._keys.indexOf(evt.keyCode);
  46922. if (index >= 0) {
  46923. _this._keys.splice(index, 1);
  46924. }
  46925. if (evt.preventDefault) {
  46926. if (!noPreventDefault) {
  46927. evt.preventDefault();
  46928. }
  46929. }
  46930. }
  46931. }
  46932. });
  46933. };
  46934. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46935. if (this._scene) {
  46936. if (this._onKeyboardObserver) {
  46937. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46938. }
  46939. if (this._onCanvasBlurObserver) {
  46940. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46941. }
  46942. this._onKeyboardObserver = null;
  46943. this._onCanvasBlurObserver = null;
  46944. }
  46945. this._keys = [];
  46946. };
  46947. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46948. if (this._onKeyboardObserver) {
  46949. var camera = this.camera;
  46950. for (var index = 0; index < this._keys.length; index++) {
  46951. var keyCode = this._keys[index];
  46952. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46953. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46954. camera.inertialPanningX -= 1 / this.panningSensibility;
  46955. }
  46956. else {
  46957. camera.inertialAlphaOffset -= 0.01;
  46958. }
  46959. }
  46960. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46961. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46962. camera.inertialPanningY += 1 / this.panningSensibility;
  46963. }
  46964. else if (this._altPressed && this.useAltToZoom) {
  46965. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46966. }
  46967. else {
  46968. camera.inertialBetaOffset -= 0.01;
  46969. }
  46970. }
  46971. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46972. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46973. camera.inertialPanningX += 1 / this.panningSensibility;
  46974. }
  46975. else {
  46976. camera.inertialAlphaOffset += 0.01;
  46977. }
  46978. }
  46979. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46980. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46981. camera.inertialPanningY -= 1 / this.panningSensibility;
  46982. }
  46983. else if (this._altPressed && this.useAltToZoom) {
  46984. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46985. }
  46986. else {
  46987. camera.inertialBetaOffset += 0.01;
  46988. }
  46989. }
  46990. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46991. camera.restoreState();
  46992. }
  46993. }
  46994. }
  46995. };
  46996. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46997. return "ArcRotateCameraKeyboardMoveInput";
  46998. };
  46999. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47000. return "keyboard";
  47001. };
  47002. __decorate([
  47003. BABYLON.serialize()
  47004. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47005. __decorate([
  47006. BABYLON.serialize()
  47007. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47008. __decorate([
  47009. BABYLON.serialize()
  47010. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47011. __decorate([
  47012. BABYLON.serialize()
  47013. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47014. __decorate([
  47015. BABYLON.serialize()
  47016. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47017. __decorate([
  47018. BABYLON.serialize()
  47019. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47020. __decorate([
  47021. BABYLON.serialize()
  47022. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47023. __decorate([
  47024. BABYLON.serialize()
  47025. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47026. return ArcRotateCameraKeyboardMoveInput;
  47027. }());
  47028. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47029. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47030. })(BABYLON || (BABYLON = {}));
  47031. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47032. "use strict";
  47033. var BABYLON;
  47034. (function (BABYLON) {
  47035. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47036. function ArcRotateCameraMouseWheelInput() {
  47037. this.wheelPrecision = 3.0;
  47038. /**
  47039. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47040. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47041. */
  47042. this.wheelDeltaPercentage = 0;
  47043. }
  47044. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47045. var _this = this;
  47046. this._wheel = function (p, s) {
  47047. //sanity check - this should be a PointerWheel event.
  47048. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47049. return;
  47050. var event = p.event;
  47051. var delta = 0;
  47052. if (event.wheelDelta) {
  47053. if (_this.wheelDeltaPercentage) {
  47054. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47055. if (event.wheelDelta > 0) {
  47056. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47057. }
  47058. else {
  47059. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47060. }
  47061. }
  47062. else {
  47063. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47064. }
  47065. }
  47066. else if (event.detail) {
  47067. delta = -event.detail / _this.wheelPrecision;
  47068. }
  47069. if (delta)
  47070. _this.camera.inertialRadiusOffset += delta;
  47071. if (event.preventDefault) {
  47072. if (!noPreventDefault) {
  47073. event.preventDefault();
  47074. }
  47075. }
  47076. };
  47077. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47078. };
  47079. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47080. if (this._observer && element) {
  47081. this.camera.getScene().onPointerObservable.remove(this._observer);
  47082. this._observer = null;
  47083. this._wheel = null;
  47084. }
  47085. };
  47086. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47087. return "ArcRotateCameraMouseWheelInput";
  47088. };
  47089. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47090. return "mousewheel";
  47091. };
  47092. __decorate([
  47093. BABYLON.serialize()
  47094. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47095. __decorate([
  47096. BABYLON.serialize()
  47097. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47098. return ArcRotateCameraMouseWheelInput;
  47099. }());
  47100. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47101. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47102. })(BABYLON || (BABYLON = {}));
  47103. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47104. "use strict";
  47105. var BABYLON;
  47106. (function (BABYLON) {
  47107. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47108. function ArcRotateCameraPointersInput() {
  47109. this.buttons = [0, 1, 2];
  47110. this.angularSensibilityX = 1000.0;
  47111. this.angularSensibilityY = 1000.0;
  47112. this.pinchPrecision = 12.0;
  47113. /**
  47114. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47115. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47116. */
  47117. this.pinchDeltaPercentage = 0;
  47118. this.panningSensibility = 1000.0;
  47119. this.multiTouchPanning = true;
  47120. this.multiTouchPanAndZoom = true;
  47121. this._isPanClick = false;
  47122. this.pinchInwards = true;
  47123. }
  47124. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47125. var _this = this;
  47126. var engine = this.camera.getEngine();
  47127. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47128. var pointA = null;
  47129. var pointB = null;
  47130. var previousPinchSquaredDistance = 0;
  47131. var initialDistance = 0;
  47132. var twoFingerActivityCount = 0;
  47133. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47134. this._pointerInput = function (p, s) {
  47135. var evt = p.event;
  47136. var isTouch = p.event.pointerType === "touch";
  47137. if (engine.isInVRExclusivePointerMode) {
  47138. return;
  47139. }
  47140. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47141. return;
  47142. }
  47143. var srcElement = (evt.srcElement || evt.target);
  47144. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47145. try {
  47146. srcElement.setPointerCapture(evt.pointerId);
  47147. }
  47148. catch (e) {
  47149. //Nothing to do with the error. Execution will continue.
  47150. }
  47151. // Manage panning with pan button click
  47152. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47153. // manage pointers
  47154. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47155. if (pointA === null) {
  47156. pointA = cacheSoloPointer;
  47157. }
  47158. else if (pointB === null) {
  47159. pointB = cacheSoloPointer;
  47160. }
  47161. if (!noPreventDefault) {
  47162. evt.preventDefault();
  47163. element.focus();
  47164. }
  47165. }
  47166. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47167. _this.camera.restoreState();
  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. cacheSoloPointer = null;
  47177. previousPinchSquaredDistance = 0;
  47178. previousMultiTouchPanPosition.isPaning = false;
  47179. previousMultiTouchPanPosition.isPinching = false;
  47180. twoFingerActivityCount = 0;
  47181. initialDistance = 0;
  47182. if (!isTouch) {
  47183. pointB = null; // Mouse and pen are mono pointer
  47184. }
  47185. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47186. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47187. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47188. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47189. if (engine._badOS) {
  47190. pointA = pointB = null;
  47191. }
  47192. else {
  47193. //only remove the impacted pointer in case of multitouch allowing on most
  47194. //platforms switching from rotate to zoom and pan seamlessly.
  47195. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47196. pointA = pointB;
  47197. pointB = null;
  47198. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47199. }
  47200. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47201. pointB = null;
  47202. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47203. }
  47204. else {
  47205. pointA = pointB = null;
  47206. }
  47207. }
  47208. if (!noPreventDefault) {
  47209. evt.preventDefault();
  47210. }
  47211. }
  47212. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47213. if (!noPreventDefault) {
  47214. evt.preventDefault();
  47215. }
  47216. // One button down
  47217. if (pointA && pointB === null && cacheSoloPointer) {
  47218. if (_this.panningSensibility !== 0 &&
  47219. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47220. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47221. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47222. }
  47223. else {
  47224. var offsetX = evt.clientX - cacheSoloPointer.x;
  47225. var offsetY = evt.clientY - cacheSoloPointer.y;
  47226. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47227. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47228. }
  47229. cacheSoloPointer.x = evt.clientX;
  47230. cacheSoloPointer.y = evt.clientY;
  47231. }
  47232. else if (pointA && pointB) {
  47233. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47234. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47235. ed.x = evt.clientX;
  47236. ed.y = evt.clientY;
  47237. var direction = _this.pinchInwards ? 1 : -1;
  47238. var distX = pointA.x - pointB.x;
  47239. var distY = pointA.y - pointB.y;
  47240. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47241. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47242. if (previousPinchSquaredDistance === 0) {
  47243. initialDistance = pinchDistance;
  47244. previousPinchSquaredDistance = pinchSquaredDistance;
  47245. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47246. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47247. return;
  47248. }
  47249. if (_this.multiTouchPanAndZoom) {
  47250. if (_this.pinchDeltaPercentage) {
  47251. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47252. }
  47253. else {
  47254. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47255. (_this.pinchPrecision *
  47256. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47257. direction);
  47258. }
  47259. if (_this.panningSensibility !== 0) {
  47260. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47261. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47262. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47263. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47264. previousMultiTouchPanPosition.x = pointersCenterX;
  47265. previousMultiTouchPanPosition.y = pointersCenterY;
  47266. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47267. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47268. }
  47269. }
  47270. else {
  47271. twoFingerActivityCount++;
  47272. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47273. if (_this.pinchDeltaPercentage) {
  47274. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47275. }
  47276. else {
  47277. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47278. (_this.pinchPrecision *
  47279. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47280. direction);
  47281. }
  47282. previousMultiTouchPanPosition.isPaning = false;
  47283. previousMultiTouchPanPosition.isPinching = true;
  47284. }
  47285. else {
  47286. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47287. if (!previousMultiTouchPanPosition.isPaning) {
  47288. previousMultiTouchPanPosition.isPaning = true;
  47289. previousMultiTouchPanPosition.isPinching = false;
  47290. previousMultiTouchPanPosition.x = ed.x;
  47291. previousMultiTouchPanPosition.y = ed.y;
  47292. return;
  47293. }
  47294. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47295. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47296. }
  47297. }
  47298. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47299. previousMultiTouchPanPosition.x = ed.x;
  47300. previousMultiTouchPanPosition.y = ed.y;
  47301. }
  47302. }
  47303. previousPinchSquaredDistance = pinchSquaredDistance;
  47304. }
  47305. }
  47306. };
  47307. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47308. this._onContextMenu = function (evt) {
  47309. evt.preventDefault();
  47310. };
  47311. if (!this.camera._useCtrlForPanning) {
  47312. element.addEventListener("contextmenu", this._onContextMenu, false);
  47313. }
  47314. this._onLostFocus = function () {
  47315. //this._keys = [];
  47316. pointA = pointB = null;
  47317. previousPinchSquaredDistance = 0;
  47318. previousMultiTouchPanPosition.isPaning = false;
  47319. previousMultiTouchPanPosition.isPinching = false;
  47320. twoFingerActivityCount = 0;
  47321. cacheSoloPointer = null;
  47322. initialDistance = 0;
  47323. };
  47324. this._onMouseMove = function (evt) {
  47325. if (!engine.isPointerLock) {
  47326. return;
  47327. }
  47328. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47329. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47330. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47331. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47332. if (!noPreventDefault) {
  47333. evt.preventDefault();
  47334. }
  47335. };
  47336. this._onGestureStart = function (e) {
  47337. if (window.MSGesture === undefined) {
  47338. return;
  47339. }
  47340. if (!_this._MSGestureHandler) {
  47341. _this._MSGestureHandler = new MSGesture();
  47342. _this._MSGestureHandler.target = element;
  47343. }
  47344. _this._MSGestureHandler.addPointer(e.pointerId);
  47345. };
  47346. this._onGesture = function (e) {
  47347. _this.camera.radius *= e.scale;
  47348. if (e.preventDefault) {
  47349. if (!noPreventDefault) {
  47350. e.stopPropagation();
  47351. e.preventDefault();
  47352. }
  47353. }
  47354. };
  47355. element.addEventListener("mousemove", this._onMouseMove, false);
  47356. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47357. element.addEventListener("MSGestureChange", this._onGesture, false);
  47358. BABYLON.Tools.RegisterTopRootEvents([
  47359. { name: "blur", handler: this._onLostFocus }
  47360. ]);
  47361. };
  47362. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47363. if (this._onLostFocus) {
  47364. BABYLON.Tools.UnregisterTopRootEvents([
  47365. { name: "blur", handler: this._onLostFocus }
  47366. ]);
  47367. }
  47368. if (element && this._observer) {
  47369. this.camera.getScene().onPointerObservable.remove(this._observer);
  47370. this._observer = null;
  47371. if (this._onContextMenu) {
  47372. element.removeEventListener("contextmenu", this._onContextMenu);
  47373. }
  47374. if (this._onMouseMove) {
  47375. element.removeEventListener("mousemove", this._onMouseMove);
  47376. }
  47377. if (this._onGestureStart) {
  47378. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47379. }
  47380. if (this._onGesture) {
  47381. element.removeEventListener("MSGestureChange", this._onGesture);
  47382. }
  47383. this._isPanClick = false;
  47384. this.pinchInwards = true;
  47385. this._onMouseMove = null;
  47386. this._onGestureStart = null;
  47387. this._onGesture = null;
  47388. this._MSGestureHandler = null;
  47389. this._onLostFocus = null;
  47390. this._onContextMenu = null;
  47391. }
  47392. };
  47393. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47394. return "ArcRotateCameraPointersInput";
  47395. };
  47396. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47397. return "pointers";
  47398. };
  47399. __decorate([
  47400. BABYLON.serialize()
  47401. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47402. __decorate([
  47403. BABYLON.serialize()
  47404. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47405. __decorate([
  47406. BABYLON.serialize()
  47407. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47408. __decorate([
  47409. BABYLON.serialize()
  47410. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47411. __decorate([
  47412. BABYLON.serialize()
  47413. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47414. __decorate([
  47415. BABYLON.serialize()
  47416. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47417. __decorate([
  47418. BABYLON.serialize()
  47419. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47420. __decorate([
  47421. BABYLON.serialize()
  47422. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47423. return ArcRotateCameraPointersInput;
  47424. }());
  47425. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47426. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47427. })(BABYLON || (BABYLON = {}));
  47428. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47429. "use strict";
  47430. var BABYLON;
  47431. (function (BABYLON) {
  47432. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47433. __extends(ArcRotateCameraInputsManager, _super);
  47434. function ArcRotateCameraInputsManager(camera) {
  47435. return _super.call(this, camera) || this;
  47436. }
  47437. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47438. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47439. return this;
  47440. };
  47441. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47442. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47443. return this;
  47444. };
  47445. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47446. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47447. return this;
  47448. };
  47449. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47450. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47451. return this;
  47452. };
  47453. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47454. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47455. return this;
  47456. };
  47457. return ArcRotateCameraInputsManager;
  47458. }(BABYLON.CameraInputsManager));
  47459. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47460. })(BABYLON || (BABYLON = {}));
  47461. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47462. "use strict";
  47463. var BABYLON;
  47464. (function (BABYLON) {
  47465. var ArcRotateCamera = /** @class */ (function (_super) {
  47466. __extends(ArcRotateCamera, _super);
  47467. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47468. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47469. _this.inertialAlphaOffset = 0;
  47470. _this.inertialBetaOffset = 0;
  47471. _this.inertialRadiusOffset = 0;
  47472. _this.lowerAlphaLimit = null;
  47473. _this.upperAlphaLimit = null;
  47474. _this.lowerBetaLimit = 0.01;
  47475. _this.upperBetaLimit = Math.PI;
  47476. _this.lowerRadiusLimit = null;
  47477. _this.upperRadiusLimit = null;
  47478. _this.inertialPanningX = 0;
  47479. _this.inertialPanningY = 0;
  47480. _this.pinchToPanMaxDistance = 20;
  47481. _this.panningDistanceLimit = null;
  47482. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47483. _this.panningInertia = 0.9;
  47484. //-- end properties for backward compatibility for inputs
  47485. _this.zoomOnFactor = 1;
  47486. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47487. _this.allowUpsideDown = true;
  47488. _this._viewMatrix = new BABYLON.Matrix();
  47489. // Panning
  47490. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47491. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47492. _this.checkCollisions = false;
  47493. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47494. _this._previousPosition = BABYLON.Vector3.Zero();
  47495. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47496. _this._newPosition = BABYLON.Vector3.Zero();
  47497. _this._computationVector = BABYLON.Vector3.Zero();
  47498. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47499. if (collidedMesh === void 0) { collidedMesh = null; }
  47500. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47501. newPosition.multiplyInPlace(_this._collider._radius);
  47502. }
  47503. if (!collidedMesh) {
  47504. _this._previousPosition.copyFrom(_this.position);
  47505. }
  47506. else {
  47507. _this.setPosition(newPosition);
  47508. if (_this.onCollide) {
  47509. _this.onCollide(collidedMesh);
  47510. }
  47511. }
  47512. // Recompute because of constraints
  47513. var cosa = Math.cos(_this.alpha);
  47514. var sina = Math.sin(_this.alpha);
  47515. var cosb = Math.cos(_this.beta);
  47516. var sinb = Math.sin(_this.beta);
  47517. if (sinb === 0) {
  47518. sinb = 0.0001;
  47519. }
  47520. var target = _this._getTargetPosition();
  47521. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47522. target.addToRef(_this._computationVector, _this._newPosition);
  47523. _this.position.copyFrom(_this._newPosition);
  47524. var up = _this.upVector;
  47525. if (_this.allowUpsideDown && _this.beta < 0) {
  47526. up = up.clone();
  47527. up = up.negate();
  47528. }
  47529. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  47530. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47531. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47532. _this._collisionTriggered = false;
  47533. };
  47534. _this._target = BABYLON.Vector3.Zero();
  47535. if (target) {
  47536. _this.setTarget(target);
  47537. }
  47538. _this.alpha = alpha;
  47539. _this.beta = beta;
  47540. _this.radius = radius;
  47541. _this.getViewMatrix();
  47542. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47543. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47544. return _this;
  47545. }
  47546. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47547. get: function () {
  47548. return this._target;
  47549. },
  47550. set: function (value) {
  47551. this.setTarget(value);
  47552. },
  47553. enumerable: true,
  47554. configurable: true
  47555. });
  47556. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47557. //-- begin properties for backward compatibility for inputs
  47558. get: function () {
  47559. var pointers = this.inputs.attached["pointers"];
  47560. if (pointers)
  47561. return pointers.angularSensibilityX;
  47562. return 0;
  47563. },
  47564. set: function (value) {
  47565. var pointers = this.inputs.attached["pointers"];
  47566. if (pointers) {
  47567. pointers.angularSensibilityX = value;
  47568. }
  47569. },
  47570. enumerable: true,
  47571. configurable: true
  47572. });
  47573. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47574. get: function () {
  47575. var pointers = this.inputs.attached["pointers"];
  47576. if (pointers)
  47577. return pointers.angularSensibilityY;
  47578. return 0;
  47579. },
  47580. set: function (value) {
  47581. var pointers = this.inputs.attached["pointers"];
  47582. if (pointers) {
  47583. pointers.angularSensibilityY = value;
  47584. }
  47585. },
  47586. enumerable: true,
  47587. configurable: true
  47588. });
  47589. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47590. get: function () {
  47591. var pointers = this.inputs.attached["pointers"];
  47592. if (pointers)
  47593. return pointers.pinchPrecision;
  47594. return 0;
  47595. },
  47596. set: function (value) {
  47597. var pointers = this.inputs.attached["pointers"];
  47598. if (pointers) {
  47599. pointers.pinchPrecision = value;
  47600. }
  47601. },
  47602. enumerable: true,
  47603. configurable: true
  47604. });
  47605. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47606. get: function () {
  47607. var pointers = this.inputs.attached["pointers"];
  47608. if (pointers)
  47609. return pointers.pinchDeltaPercentage;
  47610. return 0;
  47611. },
  47612. set: function (value) {
  47613. var pointers = this.inputs.attached["pointers"];
  47614. if (pointers) {
  47615. pointers.pinchDeltaPercentage = value;
  47616. }
  47617. },
  47618. enumerable: true,
  47619. configurable: true
  47620. });
  47621. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47622. get: function () {
  47623. var pointers = this.inputs.attached["pointers"];
  47624. if (pointers)
  47625. return pointers.panningSensibility;
  47626. return 0;
  47627. },
  47628. set: function (value) {
  47629. var pointers = this.inputs.attached["pointers"];
  47630. if (pointers) {
  47631. pointers.panningSensibility = value;
  47632. }
  47633. },
  47634. enumerable: true,
  47635. configurable: true
  47636. });
  47637. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47638. get: function () {
  47639. var keyboard = this.inputs.attached["keyboard"];
  47640. if (keyboard)
  47641. return keyboard.keysUp;
  47642. return [];
  47643. },
  47644. set: function (value) {
  47645. var keyboard = this.inputs.attached["keyboard"];
  47646. if (keyboard)
  47647. keyboard.keysUp = value;
  47648. },
  47649. enumerable: true,
  47650. configurable: true
  47651. });
  47652. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47653. get: function () {
  47654. var keyboard = this.inputs.attached["keyboard"];
  47655. if (keyboard)
  47656. return keyboard.keysDown;
  47657. return [];
  47658. },
  47659. set: function (value) {
  47660. var keyboard = this.inputs.attached["keyboard"];
  47661. if (keyboard)
  47662. keyboard.keysDown = value;
  47663. },
  47664. enumerable: true,
  47665. configurable: true
  47666. });
  47667. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47668. get: function () {
  47669. var keyboard = this.inputs.attached["keyboard"];
  47670. if (keyboard)
  47671. return keyboard.keysLeft;
  47672. return [];
  47673. },
  47674. set: function (value) {
  47675. var keyboard = this.inputs.attached["keyboard"];
  47676. if (keyboard)
  47677. keyboard.keysLeft = value;
  47678. },
  47679. enumerable: true,
  47680. configurable: true
  47681. });
  47682. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47683. get: function () {
  47684. var keyboard = this.inputs.attached["keyboard"];
  47685. if (keyboard)
  47686. return keyboard.keysRight;
  47687. return [];
  47688. },
  47689. set: function (value) {
  47690. var keyboard = this.inputs.attached["keyboard"];
  47691. if (keyboard)
  47692. keyboard.keysRight = value;
  47693. },
  47694. enumerable: true,
  47695. configurable: true
  47696. });
  47697. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47698. get: function () {
  47699. var mousewheel = this.inputs.attached["mousewheel"];
  47700. if (mousewheel)
  47701. return mousewheel.wheelPrecision;
  47702. return 0;
  47703. },
  47704. set: function (value) {
  47705. var mousewheel = this.inputs.attached["mousewheel"];
  47706. if (mousewheel)
  47707. mousewheel.wheelPrecision = value;
  47708. },
  47709. enumerable: true,
  47710. configurable: true
  47711. });
  47712. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47713. get: function () {
  47714. var mousewheel = this.inputs.attached["mousewheel"];
  47715. if (mousewheel)
  47716. return mousewheel.wheelDeltaPercentage;
  47717. return 0;
  47718. },
  47719. set: function (value) {
  47720. var mousewheel = this.inputs.attached["mousewheel"];
  47721. if (mousewheel)
  47722. mousewheel.wheelDeltaPercentage = value;
  47723. },
  47724. enumerable: true,
  47725. configurable: true
  47726. });
  47727. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47728. get: function () {
  47729. return this._bouncingBehavior;
  47730. },
  47731. enumerable: true,
  47732. configurable: true
  47733. });
  47734. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47735. get: function () {
  47736. return this._bouncingBehavior != null;
  47737. },
  47738. set: function (value) {
  47739. if (value === this.useBouncingBehavior) {
  47740. return;
  47741. }
  47742. if (value) {
  47743. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47744. this.addBehavior(this._bouncingBehavior);
  47745. }
  47746. else if (this._bouncingBehavior) {
  47747. this.removeBehavior(this._bouncingBehavior);
  47748. this._bouncingBehavior = null;
  47749. }
  47750. },
  47751. enumerable: true,
  47752. configurable: true
  47753. });
  47754. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47755. get: function () {
  47756. return this._framingBehavior;
  47757. },
  47758. enumerable: true,
  47759. configurable: true
  47760. });
  47761. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47762. get: function () {
  47763. return this._framingBehavior != null;
  47764. },
  47765. set: function (value) {
  47766. if (value === this.useFramingBehavior) {
  47767. return;
  47768. }
  47769. if (value) {
  47770. this._framingBehavior = new BABYLON.FramingBehavior();
  47771. this.addBehavior(this._framingBehavior);
  47772. }
  47773. else if (this._framingBehavior) {
  47774. this.removeBehavior(this._framingBehavior);
  47775. this._framingBehavior = null;
  47776. }
  47777. },
  47778. enumerable: true,
  47779. configurable: true
  47780. });
  47781. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47782. get: function () {
  47783. return this._autoRotationBehavior;
  47784. },
  47785. enumerable: true,
  47786. configurable: true
  47787. });
  47788. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47789. get: function () {
  47790. return this._autoRotationBehavior != null;
  47791. },
  47792. set: function (value) {
  47793. if (value === this.useAutoRotationBehavior) {
  47794. return;
  47795. }
  47796. if (value) {
  47797. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47798. this.addBehavior(this._autoRotationBehavior);
  47799. }
  47800. else if (this._autoRotationBehavior) {
  47801. this.removeBehavior(this._autoRotationBehavior);
  47802. this._autoRotationBehavior = null;
  47803. }
  47804. },
  47805. enumerable: true,
  47806. configurable: true
  47807. });
  47808. // Cache
  47809. ArcRotateCamera.prototype._initCache = function () {
  47810. _super.prototype._initCache.call(this);
  47811. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47812. this._cache.alpha = undefined;
  47813. this._cache.beta = undefined;
  47814. this._cache.radius = undefined;
  47815. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47816. };
  47817. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47818. if (!ignoreParentClass) {
  47819. _super.prototype._updateCache.call(this);
  47820. }
  47821. this._cache._target.copyFrom(this._getTargetPosition());
  47822. this._cache.alpha = this.alpha;
  47823. this._cache.beta = this.beta;
  47824. this._cache.radius = this.radius;
  47825. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47826. };
  47827. ArcRotateCamera.prototype._getTargetPosition = function () {
  47828. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47829. var pos = this._targetHost.getAbsolutePosition();
  47830. if (this._targetBoundingCenter) {
  47831. pos.addToRef(this._targetBoundingCenter, this._target);
  47832. }
  47833. else {
  47834. this._target.copyFrom(pos);
  47835. }
  47836. }
  47837. var lockedTargetPosition = this._getLockedTargetPosition();
  47838. if (lockedTargetPosition) {
  47839. return lockedTargetPosition;
  47840. }
  47841. return this._target;
  47842. };
  47843. ArcRotateCamera.prototype.storeState = function () {
  47844. this._storedAlpha = this.alpha;
  47845. this._storedBeta = this.beta;
  47846. this._storedRadius = this.radius;
  47847. this._storedTarget = this._getTargetPosition().clone();
  47848. return _super.prototype.storeState.call(this);
  47849. };
  47850. /**
  47851. * Restored camera state. You must call storeState() first
  47852. */
  47853. ArcRotateCamera.prototype._restoreStateValues = function () {
  47854. if (!_super.prototype._restoreStateValues.call(this)) {
  47855. return false;
  47856. }
  47857. this.alpha = this._storedAlpha;
  47858. this.beta = this._storedBeta;
  47859. this.radius = this._storedRadius;
  47860. this.setTarget(this._storedTarget.clone());
  47861. this.inertialAlphaOffset = 0;
  47862. this.inertialBetaOffset = 0;
  47863. this.inertialRadiusOffset = 0;
  47864. this.inertialPanningX = 0;
  47865. this.inertialPanningY = 0;
  47866. return true;
  47867. };
  47868. // Synchronized
  47869. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47870. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47871. return false;
  47872. return this._cache._target.equals(this._getTargetPosition())
  47873. && this._cache.alpha === this.alpha
  47874. && this._cache.beta === this.beta
  47875. && this._cache.radius === this.radius
  47876. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47877. };
  47878. // Methods
  47879. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47880. var _this = this;
  47881. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47882. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47883. this._useCtrlForPanning = useCtrlForPanning;
  47884. this._panningMouseButton = panningMouseButton;
  47885. this.inputs.attachElement(element, noPreventDefault);
  47886. this._reset = function () {
  47887. _this.inertialAlphaOffset = 0;
  47888. _this.inertialBetaOffset = 0;
  47889. _this.inertialRadiusOffset = 0;
  47890. _this.inertialPanningX = 0;
  47891. _this.inertialPanningY = 0;
  47892. };
  47893. };
  47894. ArcRotateCamera.prototype.detachControl = function (element) {
  47895. this.inputs.detachElement(element);
  47896. if (this._reset) {
  47897. this._reset();
  47898. }
  47899. };
  47900. ArcRotateCamera.prototype._checkInputs = function () {
  47901. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47902. if (this._collisionTriggered) {
  47903. return;
  47904. }
  47905. this.inputs.checkInputs();
  47906. // Inertia
  47907. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47908. if (this.getScene().useRightHandedSystem) {
  47909. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  47910. }
  47911. else {
  47912. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  47913. }
  47914. this.beta += this.inertialBetaOffset;
  47915. this.radius -= this.inertialRadiusOffset;
  47916. this.inertialAlphaOffset *= this.inertia;
  47917. this.inertialBetaOffset *= this.inertia;
  47918. this.inertialRadiusOffset *= this.inertia;
  47919. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47920. this.inertialAlphaOffset = 0;
  47921. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47922. this.inertialBetaOffset = 0;
  47923. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47924. this.inertialRadiusOffset = 0;
  47925. }
  47926. // Panning inertia
  47927. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47928. if (!this._localDirection) {
  47929. this._localDirection = BABYLON.Vector3.Zero();
  47930. this._transformedDirection = BABYLON.Vector3.Zero();
  47931. }
  47932. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47933. this._localDirection.multiplyInPlace(this.panningAxis);
  47934. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47935. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47936. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47937. if (!this.panningAxis.y) {
  47938. this._transformedDirection.y = 0;
  47939. }
  47940. if (!this._targetHost) {
  47941. if (this.panningDistanceLimit) {
  47942. this._transformedDirection.addInPlace(this._target);
  47943. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47944. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47945. this._target.copyFrom(this._transformedDirection);
  47946. }
  47947. }
  47948. else {
  47949. this._target.addInPlace(this._transformedDirection);
  47950. }
  47951. }
  47952. this.inertialPanningX *= this.panningInertia;
  47953. this.inertialPanningY *= this.panningInertia;
  47954. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47955. this.inertialPanningX = 0;
  47956. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47957. this.inertialPanningY = 0;
  47958. }
  47959. // Limits
  47960. this._checkLimits();
  47961. _super.prototype._checkInputs.call(this);
  47962. };
  47963. ArcRotateCamera.prototype._checkLimits = function () {
  47964. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47965. if (this.allowUpsideDown && this.beta > Math.PI) {
  47966. this.beta = this.beta - (2 * Math.PI);
  47967. }
  47968. }
  47969. else {
  47970. if (this.beta < this.lowerBetaLimit) {
  47971. this.beta = this.lowerBetaLimit;
  47972. }
  47973. }
  47974. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47975. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47976. this.beta = this.beta + (2 * Math.PI);
  47977. }
  47978. }
  47979. else {
  47980. if (this.beta > this.upperBetaLimit) {
  47981. this.beta = this.upperBetaLimit;
  47982. }
  47983. }
  47984. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47985. this.alpha = this.lowerAlphaLimit;
  47986. }
  47987. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47988. this.alpha = this.upperAlphaLimit;
  47989. }
  47990. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47991. this.radius = this.lowerRadiusLimit;
  47992. }
  47993. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47994. this.radius = this.upperRadiusLimit;
  47995. }
  47996. };
  47997. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47998. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47999. this.radius = this._computationVector.length();
  48000. if (this.radius === 0) {
  48001. this.radius = 0.0001; // Just to avoid division by zero
  48002. }
  48003. // Alpha
  48004. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48005. if (this._computationVector.z < 0) {
  48006. this.alpha = 2 * Math.PI - this.alpha;
  48007. }
  48008. // Beta
  48009. this.beta = Math.acos(this._computationVector.y / this.radius);
  48010. this._checkLimits();
  48011. };
  48012. ArcRotateCamera.prototype.setPosition = function (position) {
  48013. if (this.position.equals(position)) {
  48014. return;
  48015. }
  48016. this.position.copyFrom(position);
  48017. this.rebuildAnglesAndRadius();
  48018. };
  48019. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48020. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48021. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48022. if (target.getBoundingInfo) {
  48023. if (toBoundingCenter) {
  48024. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48025. }
  48026. else {
  48027. this._targetBoundingCenter = null;
  48028. }
  48029. this._targetHost = target;
  48030. this._target = this._getTargetPosition();
  48031. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48032. }
  48033. else {
  48034. var newTarget = target;
  48035. var currentTarget = this._getTargetPosition();
  48036. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48037. return;
  48038. }
  48039. this._targetHost = null;
  48040. this._target = newTarget;
  48041. this._targetBoundingCenter = null;
  48042. this.onMeshTargetChangedObservable.notifyObservers(null);
  48043. }
  48044. this.rebuildAnglesAndRadius();
  48045. };
  48046. ArcRotateCamera.prototype._getViewMatrix = function () {
  48047. // Compute
  48048. var cosa = Math.cos(this.alpha);
  48049. var sina = Math.sin(this.alpha);
  48050. var cosb = Math.cos(this.beta);
  48051. var sinb = Math.sin(this.beta);
  48052. if (sinb === 0) {
  48053. sinb = 0.0001;
  48054. }
  48055. var target = this._getTargetPosition();
  48056. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48057. target.addToRef(this._computationVector, this._newPosition);
  48058. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48059. if (!this._collider) {
  48060. this._collider = new BABYLON.Collider();
  48061. }
  48062. this._collider._radius = this.collisionRadius;
  48063. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48064. this._collisionTriggered = true;
  48065. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48066. }
  48067. else {
  48068. this.position.copyFrom(this._newPosition);
  48069. var up = this.upVector;
  48070. if (this.allowUpsideDown && sinb < 0) {
  48071. up = up.clone();
  48072. up = up.negate();
  48073. }
  48074. if (this.getScene().useRightHandedSystem) {
  48075. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48076. }
  48077. else {
  48078. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48079. }
  48080. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48081. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48082. }
  48083. this._currentTarget = target;
  48084. return this._viewMatrix;
  48085. };
  48086. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48087. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48088. meshes = meshes || this.getScene().meshes;
  48089. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48090. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48091. this.radius = distance * this.zoomOnFactor;
  48092. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48093. };
  48094. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48095. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48096. var meshesOrMinMaxVector;
  48097. var distance;
  48098. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  48099. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48100. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48101. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48102. }
  48103. else {
  48104. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48105. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48106. distance = minMaxVectorAndDistance.distance;
  48107. }
  48108. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48109. if (!doNotUpdateMaxZ) {
  48110. this.maxZ = distance * 2;
  48111. }
  48112. };
  48113. /**
  48114. * @override
  48115. * Override Camera.createRigCamera
  48116. */
  48117. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48118. var alphaShift = 0;
  48119. switch (this.cameraRigMode) {
  48120. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48121. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48122. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48123. case BABYLON.Camera.RIG_MODE_VR:
  48124. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48125. break;
  48126. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48127. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48128. break;
  48129. }
  48130. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48131. rigCam._cameraRigParams = {};
  48132. return rigCam;
  48133. };
  48134. /**
  48135. * @override
  48136. * Override Camera._updateRigCameras
  48137. */
  48138. ArcRotateCamera.prototype._updateRigCameras = function () {
  48139. var camLeft = this._rigCameras[0];
  48140. var camRight = this._rigCameras[1];
  48141. camLeft.beta = camRight.beta = this.beta;
  48142. camLeft.radius = camRight.radius = this.radius;
  48143. switch (this.cameraRigMode) {
  48144. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48145. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48146. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48147. case BABYLON.Camera.RIG_MODE_VR:
  48148. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48149. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48150. break;
  48151. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48152. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48153. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48154. break;
  48155. }
  48156. _super.prototype._updateRigCameras.call(this);
  48157. };
  48158. ArcRotateCamera.prototype.dispose = function () {
  48159. this.inputs.clear();
  48160. _super.prototype.dispose.call(this);
  48161. };
  48162. ArcRotateCamera.prototype.getClassName = function () {
  48163. return "ArcRotateCamera";
  48164. };
  48165. __decorate([
  48166. BABYLON.serialize()
  48167. ], ArcRotateCamera.prototype, "alpha", void 0);
  48168. __decorate([
  48169. BABYLON.serialize()
  48170. ], ArcRotateCamera.prototype, "beta", void 0);
  48171. __decorate([
  48172. BABYLON.serialize()
  48173. ], ArcRotateCamera.prototype, "radius", void 0);
  48174. __decorate([
  48175. BABYLON.serializeAsVector3("target")
  48176. ], ArcRotateCamera.prototype, "_target", void 0);
  48177. __decorate([
  48178. BABYLON.serialize()
  48179. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48180. __decorate([
  48181. BABYLON.serialize()
  48182. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48183. __decorate([
  48184. BABYLON.serialize()
  48185. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48186. __decorate([
  48187. BABYLON.serialize()
  48188. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48189. __decorate([
  48190. BABYLON.serialize()
  48191. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48192. __decorate([
  48193. BABYLON.serialize()
  48194. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48195. __decorate([
  48196. BABYLON.serialize()
  48197. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48198. __decorate([
  48199. BABYLON.serialize()
  48200. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48201. __decorate([
  48202. BABYLON.serialize()
  48203. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48204. __decorate([
  48205. BABYLON.serialize()
  48206. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48207. __decorate([
  48208. BABYLON.serialize()
  48209. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48210. __decorate([
  48211. BABYLON.serialize()
  48212. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48213. __decorate([
  48214. BABYLON.serialize()
  48215. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48216. __decorate([
  48217. BABYLON.serializeAsVector3()
  48218. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48219. __decorate([
  48220. BABYLON.serialize()
  48221. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48222. __decorate([
  48223. BABYLON.serialize()
  48224. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48225. __decorate([
  48226. BABYLON.serialize()
  48227. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48228. return ArcRotateCamera;
  48229. }(BABYLON.TargetCamera));
  48230. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48231. })(BABYLON || (BABYLON = {}));
  48232. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48233. "use strict";
  48234. var BABYLON;
  48235. (function (BABYLON) {
  48236. /**
  48237. * The HemisphericLight simulates the ambient environment light,
  48238. * so the passed direction is the light reflection direction, not the incoming direction.
  48239. */
  48240. var HemisphericLight = /** @class */ (function (_super) {
  48241. __extends(HemisphericLight, _super);
  48242. /**
  48243. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48244. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48245. * The HemisphericLight can't cast shadows.
  48246. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48247. * @param name The friendly name of the light
  48248. * @param direction The direction of the light reflection
  48249. * @param scene The scene the light belongs to
  48250. */
  48251. function HemisphericLight(name, direction, scene) {
  48252. var _this = _super.call(this, name, scene) || this;
  48253. /**
  48254. * The groundColor is the light in the opposite direction to the one specified during creation.
  48255. * 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.
  48256. */
  48257. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48258. _this.direction = direction || BABYLON.Vector3.Up();
  48259. return _this;
  48260. }
  48261. HemisphericLight.prototype._buildUniformLayout = function () {
  48262. this._uniformBuffer.addUniform("vLightData", 4);
  48263. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48264. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48265. this._uniformBuffer.addUniform("vLightGround", 3);
  48266. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48267. this._uniformBuffer.addUniform("depthValues", 2);
  48268. this._uniformBuffer.create();
  48269. };
  48270. /**
  48271. * Returns the string "HemisphericLight".
  48272. * @return The class name
  48273. */
  48274. HemisphericLight.prototype.getClassName = function () {
  48275. return "HemisphericLight";
  48276. };
  48277. /**
  48278. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48279. * Returns the updated direction.
  48280. * @param target The target the direction should point to
  48281. * @return The computed direction
  48282. */
  48283. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48284. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48285. return this.direction;
  48286. };
  48287. /**
  48288. * Returns the shadow generator associated to the light.
  48289. * @returns Always null for hemispheric lights because it does not support shadows.
  48290. */
  48291. HemisphericLight.prototype.getShadowGenerator = function () {
  48292. return null;
  48293. };
  48294. /**
  48295. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48296. * @param effect The effect to update
  48297. * @param lightIndex The index of the light in the effect to update
  48298. * @returns The hemispheric light
  48299. */
  48300. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48301. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48302. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48303. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48304. return this;
  48305. };
  48306. /**
  48307. * @ignore internal use only.
  48308. */
  48309. HemisphericLight.prototype._getWorldMatrix = function () {
  48310. if (!this._worldMatrix) {
  48311. this._worldMatrix = BABYLON.Matrix.Identity();
  48312. }
  48313. return this._worldMatrix;
  48314. };
  48315. /**
  48316. * Returns the integer 3.
  48317. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48318. */
  48319. HemisphericLight.prototype.getTypeID = function () {
  48320. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48321. };
  48322. __decorate([
  48323. BABYLON.serializeAsColor3()
  48324. ], HemisphericLight.prototype, "groundColor", void 0);
  48325. __decorate([
  48326. BABYLON.serializeAsVector3()
  48327. ], HemisphericLight.prototype, "direction", void 0);
  48328. return HemisphericLight;
  48329. }(BABYLON.Light));
  48330. BABYLON.HemisphericLight = HemisphericLight;
  48331. })(BABYLON || (BABYLON = {}));
  48332. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48333. "use strict";
  48334. var BABYLON;
  48335. (function (BABYLON) {
  48336. /**
  48337. * Base implementation IShadowLight
  48338. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48339. */
  48340. var ShadowLight = /** @class */ (function (_super) {
  48341. __extends(ShadowLight, _super);
  48342. function ShadowLight() {
  48343. var _this = _super !== null && _super.apply(this, arguments) || this;
  48344. _this._needProjectionMatrixCompute = true;
  48345. return _this;
  48346. }
  48347. ShadowLight.prototype._setPosition = function (value) {
  48348. this._position = value;
  48349. };
  48350. Object.defineProperty(ShadowLight.prototype, "position", {
  48351. /**
  48352. * Sets the position the shadow will be casted from. Also use as the light position for both
  48353. * point and spot lights.
  48354. */
  48355. get: function () {
  48356. return this._position;
  48357. },
  48358. /**
  48359. * Sets the position the shadow will be casted from. Also use as the light position for both
  48360. * point and spot lights.
  48361. */
  48362. set: function (value) {
  48363. this._setPosition(value);
  48364. },
  48365. enumerable: true,
  48366. configurable: true
  48367. });
  48368. ShadowLight.prototype._setDirection = function (value) {
  48369. this._direction = value;
  48370. };
  48371. Object.defineProperty(ShadowLight.prototype, "direction", {
  48372. /**
  48373. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48374. * Also use as the light direction on spot and directional lights.
  48375. */
  48376. get: function () {
  48377. return this._direction;
  48378. },
  48379. /**
  48380. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48381. * Also use as the light direction on spot and directional lights.
  48382. */
  48383. set: function (value) {
  48384. this._setDirection(value);
  48385. },
  48386. enumerable: true,
  48387. configurable: true
  48388. });
  48389. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48390. /**
  48391. * Gets the shadow projection clipping minimum z value.
  48392. */
  48393. get: function () {
  48394. return this._shadowMinZ;
  48395. },
  48396. /**
  48397. * Sets the shadow projection clipping minimum z value.
  48398. */
  48399. set: function (value) {
  48400. this._shadowMinZ = value;
  48401. this.forceProjectionMatrixCompute();
  48402. },
  48403. enumerable: true,
  48404. configurable: true
  48405. });
  48406. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48407. /**
  48408. * Sets the shadow projection clipping maximum z value.
  48409. */
  48410. get: function () {
  48411. return this._shadowMaxZ;
  48412. },
  48413. /**
  48414. * Gets the shadow projection clipping maximum z value.
  48415. */
  48416. set: function (value) {
  48417. this._shadowMaxZ = value;
  48418. this.forceProjectionMatrixCompute();
  48419. },
  48420. enumerable: true,
  48421. configurable: true
  48422. });
  48423. /**
  48424. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48425. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48426. */
  48427. ShadowLight.prototype.computeTransformedInformation = function () {
  48428. if (this.parent && this.parent.getWorldMatrix) {
  48429. if (!this.transformedPosition) {
  48430. this.transformedPosition = BABYLON.Vector3.Zero();
  48431. }
  48432. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48433. // In case the direction is present.
  48434. if (this.direction) {
  48435. if (!this.transformedDirection) {
  48436. this.transformedDirection = BABYLON.Vector3.Zero();
  48437. }
  48438. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48439. }
  48440. return true;
  48441. }
  48442. return false;
  48443. };
  48444. /**
  48445. * Return the depth scale used for the shadow map.
  48446. * @returns the depth scale.
  48447. */
  48448. ShadowLight.prototype.getDepthScale = function () {
  48449. return 50.0;
  48450. };
  48451. /**
  48452. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48453. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48454. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48455. */
  48456. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48457. return this.transformedDirection ? this.transformedDirection : this.direction;
  48458. };
  48459. /**
  48460. * Returns the ShadowLight absolute position in the World.
  48461. * @returns the position vector in world space
  48462. */
  48463. ShadowLight.prototype.getAbsolutePosition = function () {
  48464. return this.transformedPosition ? this.transformedPosition : this.position;
  48465. };
  48466. /**
  48467. * Sets the ShadowLight direction toward the passed target.
  48468. * @param target The point tot target in local space
  48469. * @returns the updated ShadowLight direction
  48470. */
  48471. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48472. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48473. return this.direction;
  48474. };
  48475. /**
  48476. * Returns the light rotation in euler definition.
  48477. * @returns the x y z rotation in local space.
  48478. */
  48479. ShadowLight.prototype.getRotation = function () {
  48480. this.direction.normalize();
  48481. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48482. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48483. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48484. };
  48485. /**
  48486. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48487. * @returns true if a cube texture needs to be use
  48488. */
  48489. ShadowLight.prototype.needCube = function () {
  48490. return false;
  48491. };
  48492. /**
  48493. * Detects if the projection matrix requires to be recomputed this frame.
  48494. * @returns true if it requires to be recomputed otherwise, false.
  48495. */
  48496. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48497. return this._needProjectionMatrixCompute;
  48498. };
  48499. /**
  48500. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48501. */
  48502. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48503. this._needProjectionMatrixCompute = true;
  48504. };
  48505. /**
  48506. * Get the world matrix of the sahdow lights.
  48507. * @ignore Internal Use Only
  48508. */
  48509. ShadowLight.prototype._getWorldMatrix = function () {
  48510. if (!this._worldMatrix) {
  48511. this._worldMatrix = BABYLON.Matrix.Identity();
  48512. }
  48513. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48514. return this._worldMatrix;
  48515. };
  48516. /**
  48517. * Gets the minZ used for shadow according to both the scene and the light.
  48518. * @param activeCamera The camera we are returning the min for
  48519. * @returns the depth min z
  48520. */
  48521. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48522. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48523. };
  48524. /**
  48525. * Gets the maxZ used for shadow according to both the scene and the light.
  48526. * @param activeCamera The camera we are returning the max for
  48527. * @returns the depth max z
  48528. */
  48529. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48530. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48531. };
  48532. /**
  48533. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48534. * @param matrix The materix to updated with the projection information
  48535. * @param viewMatrix The transform matrix of the light
  48536. * @param renderList The list of mesh to render in the map
  48537. * @returns The current light
  48538. */
  48539. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48540. if (this.customProjectionMatrixBuilder) {
  48541. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48542. }
  48543. else {
  48544. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48545. }
  48546. return this;
  48547. };
  48548. __decorate([
  48549. BABYLON.serializeAsVector3()
  48550. ], ShadowLight.prototype, "position", null);
  48551. __decorate([
  48552. BABYLON.serializeAsVector3()
  48553. ], ShadowLight.prototype, "direction", null);
  48554. __decorate([
  48555. BABYLON.serialize()
  48556. ], ShadowLight.prototype, "shadowMinZ", null);
  48557. __decorate([
  48558. BABYLON.serialize()
  48559. ], ShadowLight.prototype, "shadowMaxZ", null);
  48560. return ShadowLight;
  48561. }(BABYLON.Light));
  48562. BABYLON.ShadowLight = ShadowLight;
  48563. })(BABYLON || (BABYLON = {}));
  48564. //# sourceMappingURL=babylon.shadowLight.js.map
  48565. "use strict";
  48566. var BABYLON;
  48567. (function (BABYLON) {
  48568. /**
  48569. * A point light is a light defined by an unique point in world space.
  48570. * The light is emitted in every direction from this point.
  48571. * A good example of a point light is a standard light bulb.
  48572. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48573. */
  48574. var PointLight = /** @class */ (function (_super) {
  48575. __extends(PointLight, _super);
  48576. /**
  48577. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48578. * A PointLight emits the light in every direction.
  48579. * It can cast shadows.
  48580. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48581. * ```javascript
  48582. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48583. * ```
  48584. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48585. * @param name The light friendly name
  48586. * @param position The position of the point light in the scene
  48587. * @param scene The scene the lights belongs to
  48588. */
  48589. function PointLight(name, position, scene) {
  48590. var _this = _super.call(this, name, scene) || this;
  48591. _this._shadowAngle = Math.PI / 2;
  48592. _this.position = position;
  48593. return _this;
  48594. }
  48595. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48596. /**
  48597. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48598. * This specifies what angle the shadow will use to be created.
  48599. *
  48600. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48601. */
  48602. get: function () {
  48603. return this._shadowAngle;
  48604. },
  48605. /**
  48606. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48607. * This specifies what angle the shadow will use to be created.
  48608. *
  48609. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48610. */
  48611. set: function (value) {
  48612. this._shadowAngle = value;
  48613. this.forceProjectionMatrixCompute();
  48614. },
  48615. enumerable: true,
  48616. configurable: true
  48617. });
  48618. Object.defineProperty(PointLight.prototype, "direction", {
  48619. /**
  48620. * Gets the direction if it has been set.
  48621. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48622. */
  48623. get: function () {
  48624. return this._direction;
  48625. },
  48626. /**
  48627. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48628. */
  48629. set: function (value) {
  48630. var previousNeedCube = this.needCube();
  48631. this._direction = value;
  48632. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48633. this._shadowGenerator.recreateShadowMap();
  48634. }
  48635. },
  48636. enumerable: true,
  48637. configurable: true
  48638. });
  48639. /**
  48640. * Returns the string "PointLight"
  48641. * @returns the class name
  48642. */
  48643. PointLight.prototype.getClassName = function () {
  48644. return "PointLight";
  48645. };
  48646. /**
  48647. * Returns the integer 0.
  48648. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48649. */
  48650. PointLight.prototype.getTypeID = function () {
  48651. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48652. };
  48653. /**
  48654. * Specifies wether or not the shadowmap should be a cube texture.
  48655. * @returns true if the shadowmap needs to be a cube texture.
  48656. */
  48657. PointLight.prototype.needCube = function () {
  48658. return !this.direction;
  48659. };
  48660. /**
  48661. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48662. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48663. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48664. */
  48665. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48666. if (this.direction) {
  48667. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48668. }
  48669. else {
  48670. switch (faceIndex) {
  48671. case 0:
  48672. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48673. case 1:
  48674. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48675. case 2:
  48676. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48677. case 3:
  48678. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48679. case 4:
  48680. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48681. case 5:
  48682. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48683. }
  48684. }
  48685. return BABYLON.Vector3.Zero();
  48686. };
  48687. /**
  48688. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48689. * - fov = PI / 2
  48690. * - aspect ratio : 1.0
  48691. * - z-near and far equal to the active camera minZ and maxZ.
  48692. * Returns the PointLight.
  48693. */
  48694. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48695. var activeCamera = this.getScene().activeCamera;
  48696. if (!activeCamera) {
  48697. return;
  48698. }
  48699. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48700. };
  48701. PointLight.prototype._buildUniformLayout = function () {
  48702. this._uniformBuffer.addUniform("vLightData", 4);
  48703. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48704. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48705. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48706. this._uniformBuffer.addUniform("depthValues", 2);
  48707. this._uniformBuffer.create();
  48708. };
  48709. /**
  48710. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48711. * @param effect The effect to update
  48712. * @param lightIndex The index of the light in the effect to update
  48713. * @returns The point light
  48714. */
  48715. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48716. if (this.computeTransformedInformation()) {
  48717. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48718. return this;
  48719. }
  48720. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48721. return this;
  48722. };
  48723. __decorate([
  48724. BABYLON.serialize()
  48725. ], PointLight.prototype, "shadowAngle", null);
  48726. return PointLight;
  48727. }(BABYLON.ShadowLight));
  48728. BABYLON.PointLight = PointLight;
  48729. })(BABYLON || (BABYLON = {}));
  48730. //# sourceMappingURL=babylon.pointLight.js.map
  48731. "use strict";
  48732. var BABYLON;
  48733. (function (BABYLON) {
  48734. /**
  48735. * A directional light is defined by a direction (what a surprise!).
  48736. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48737. * 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.
  48738. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48739. */
  48740. var DirectionalLight = /** @class */ (function (_super) {
  48741. __extends(DirectionalLight, _super);
  48742. /**
  48743. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48744. * The directional light is emitted from everywhere in the given direction.
  48745. * It can cast shawdows.
  48746. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48747. * @param name The friendly name of the light
  48748. * @param direction The direction of the light
  48749. * @param scene The scene the light belongs to
  48750. */
  48751. function DirectionalLight(name, direction, scene) {
  48752. var _this = _super.call(this, name, scene) || this;
  48753. _this._shadowFrustumSize = 0;
  48754. _this._shadowOrthoScale = 0.1;
  48755. /**
  48756. * Automatically compute the projection matrix to best fit (including all the casters)
  48757. * on each frame.
  48758. */
  48759. _this.autoUpdateExtends = true;
  48760. // Cache
  48761. _this._orthoLeft = Number.MAX_VALUE;
  48762. _this._orthoRight = Number.MIN_VALUE;
  48763. _this._orthoTop = Number.MIN_VALUE;
  48764. _this._orthoBottom = Number.MAX_VALUE;
  48765. _this.position = direction.scale(-1.0);
  48766. _this.direction = direction;
  48767. return _this;
  48768. }
  48769. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48770. /**
  48771. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48772. */
  48773. get: function () {
  48774. return this._shadowFrustumSize;
  48775. },
  48776. /**
  48777. * Specifies a fix frustum size for the shadow generation.
  48778. */
  48779. set: function (value) {
  48780. this._shadowFrustumSize = value;
  48781. this.forceProjectionMatrixCompute();
  48782. },
  48783. enumerable: true,
  48784. configurable: true
  48785. });
  48786. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48787. /**
  48788. * Gets the shadow projection scale against the optimal computed one.
  48789. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48790. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48791. */
  48792. get: function () {
  48793. return this._shadowOrthoScale;
  48794. },
  48795. /**
  48796. * Sets the shadow projection scale against the optimal computed one.
  48797. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48798. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48799. */
  48800. set: function (value) {
  48801. this._shadowOrthoScale = value;
  48802. this.forceProjectionMatrixCompute();
  48803. },
  48804. enumerable: true,
  48805. configurable: true
  48806. });
  48807. /**
  48808. * Returns the string "DirectionalLight".
  48809. * @return The class name
  48810. */
  48811. DirectionalLight.prototype.getClassName = function () {
  48812. return "DirectionalLight";
  48813. };
  48814. /**
  48815. * Returns the integer 1.
  48816. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48817. */
  48818. DirectionalLight.prototype.getTypeID = function () {
  48819. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48820. };
  48821. /**
  48822. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48823. * Returns the DirectionalLight Shadow projection matrix.
  48824. */
  48825. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48826. if (this.shadowFrustumSize > 0) {
  48827. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48828. }
  48829. else {
  48830. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48831. }
  48832. };
  48833. /**
  48834. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48835. * Returns the DirectionalLight Shadow projection matrix.
  48836. */
  48837. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48838. var activeCamera = this.getScene().activeCamera;
  48839. if (!activeCamera) {
  48840. return;
  48841. }
  48842. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48843. };
  48844. /**
  48845. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48846. * Returns the DirectionalLight Shadow projection matrix.
  48847. */
  48848. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48849. var activeCamera = this.getScene().activeCamera;
  48850. if (!activeCamera) {
  48851. return;
  48852. }
  48853. // Check extends
  48854. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48855. var tempVector3 = BABYLON.Vector3.Zero();
  48856. this._orthoLeft = Number.MAX_VALUE;
  48857. this._orthoRight = Number.MIN_VALUE;
  48858. this._orthoTop = Number.MIN_VALUE;
  48859. this._orthoBottom = Number.MAX_VALUE;
  48860. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48861. var mesh = renderList[meshIndex];
  48862. if (!mesh) {
  48863. continue;
  48864. }
  48865. var boundingInfo = mesh.getBoundingInfo();
  48866. var boundingBox = boundingInfo.boundingBox;
  48867. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48868. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48869. if (tempVector3.x < this._orthoLeft)
  48870. this._orthoLeft = tempVector3.x;
  48871. if (tempVector3.y < this._orthoBottom)
  48872. this._orthoBottom = tempVector3.y;
  48873. if (tempVector3.x > this._orthoRight)
  48874. this._orthoRight = tempVector3.x;
  48875. if (tempVector3.y > this._orthoTop)
  48876. this._orthoTop = tempVector3.y;
  48877. }
  48878. }
  48879. }
  48880. var xOffset = this._orthoRight - this._orthoLeft;
  48881. var yOffset = this._orthoTop - this._orthoBottom;
  48882. 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);
  48883. };
  48884. DirectionalLight.prototype._buildUniformLayout = function () {
  48885. this._uniformBuffer.addUniform("vLightData", 4);
  48886. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48887. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48888. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48889. this._uniformBuffer.addUniform("depthValues", 2);
  48890. this._uniformBuffer.create();
  48891. };
  48892. /**
  48893. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48894. * @param effect The effect to update
  48895. * @param lightIndex The index of the light in the effect to update
  48896. * @returns The directional light
  48897. */
  48898. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48899. if (this.computeTransformedInformation()) {
  48900. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48901. return this;
  48902. }
  48903. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48904. return this;
  48905. };
  48906. /**
  48907. * Gets the minZ used for shadow according to both the scene and the light.
  48908. *
  48909. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48910. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48911. * @param activeCamera The camera we are returning the min for
  48912. * @returns the depth min z
  48913. */
  48914. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48915. return 1;
  48916. };
  48917. /**
  48918. * Gets the maxZ used for shadow according to both the scene and the light.
  48919. *
  48920. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48921. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48922. * @param activeCamera The camera we are returning the max for
  48923. * @returns the depth max z
  48924. */
  48925. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48926. return 1;
  48927. };
  48928. __decorate([
  48929. BABYLON.serialize()
  48930. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48931. __decorate([
  48932. BABYLON.serialize()
  48933. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48934. __decorate([
  48935. BABYLON.serialize()
  48936. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48937. return DirectionalLight;
  48938. }(BABYLON.ShadowLight));
  48939. BABYLON.DirectionalLight = DirectionalLight;
  48940. })(BABYLON || (BABYLON = {}));
  48941. //# sourceMappingURL=babylon.directionalLight.js.map
  48942. "use strict";
  48943. var BABYLON;
  48944. (function (BABYLON) {
  48945. /**
  48946. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48947. * These values define a cone of light starting from the position, emitting toward the direction.
  48948. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48949. * and the exponent defines the speed of the decay of the light with distance (reach).
  48950. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48951. */
  48952. var SpotLight = /** @class */ (function (_super) {
  48953. __extends(SpotLight, _super);
  48954. /**
  48955. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48956. * It can cast shadows.
  48957. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48958. * @param name The light friendly name
  48959. * @param position The position of the spot light in the scene
  48960. * @param direction The direction of the light in the scene
  48961. * @param angle The cone angle of the light in Radians
  48962. * @param exponent The light decay speed with the distance from the emission spot
  48963. * @param scene The scene the lights belongs to
  48964. */
  48965. function SpotLight(name, position, direction, angle, exponent, scene) {
  48966. var _this = _super.call(this, name, scene) || this;
  48967. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48968. _this._projectionTextureLightNear = 1e-6;
  48969. _this._projectionTextureLightFar = 1000.0;
  48970. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48971. _this._projectionTextureViewLightDirty = true;
  48972. _this._projectionTextureProjectionLightDirty = true;
  48973. _this._projectionTextureDirty = true;
  48974. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48975. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48976. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48977. _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);
  48978. _this.position = position;
  48979. _this.direction = direction;
  48980. _this.angle = angle;
  48981. _this.exponent = exponent;
  48982. return _this;
  48983. }
  48984. Object.defineProperty(SpotLight.prototype, "angle", {
  48985. /**
  48986. * Gets the cone angle of the spot light in Radians.
  48987. */
  48988. get: function () {
  48989. return this._angle;
  48990. },
  48991. /**
  48992. * Sets the cone angle of the spot light in Radians.
  48993. */
  48994. set: function (value) {
  48995. this._angle = value;
  48996. this._projectionTextureProjectionLightDirty = true;
  48997. this.forceProjectionMatrixCompute();
  48998. },
  48999. enumerable: true,
  49000. configurable: true
  49001. });
  49002. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49003. /**
  49004. * Allows scaling the angle of the light for shadow generation only.
  49005. */
  49006. get: function () {
  49007. return this._shadowAngleScale;
  49008. },
  49009. /**
  49010. * Allows scaling the angle of the light for shadow generation only.
  49011. */
  49012. set: function (value) {
  49013. this._shadowAngleScale = value;
  49014. this.forceProjectionMatrixCompute();
  49015. },
  49016. enumerable: true,
  49017. configurable: true
  49018. });
  49019. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49020. /**
  49021. * Allows reading the projecton texture
  49022. */
  49023. get: function () {
  49024. return this._projectionTextureMatrix;
  49025. },
  49026. enumerable: true,
  49027. configurable: true
  49028. });
  49029. ;
  49030. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49031. /**
  49032. * Gets the near clip of the Spotlight for texture projection.
  49033. */
  49034. get: function () {
  49035. return this._projectionTextureLightNear;
  49036. },
  49037. /**
  49038. * Sets the near clip of the Spotlight for texture projection.
  49039. */
  49040. set: function (value) {
  49041. this._projectionTextureLightNear = value;
  49042. this._projectionTextureProjectionLightDirty = true;
  49043. },
  49044. enumerable: true,
  49045. configurable: true
  49046. });
  49047. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49048. /**
  49049. * Gets the far clip of the Spotlight for texture projection.
  49050. */
  49051. get: function () {
  49052. return this._projectionTextureLightFar;
  49053. },
  49054. /**
  49055. * Sets the far clip of the Spotlight for texture projection.
  49056. */
  49057. set: function (value) {
  49058. this._projectionTextureLightFar = value;
  49059. this._projectionTextureProjectionLightDirty = true;
  49060. },
  49061. enumerable: true,
  49062. configurable: true
  49063. });
  49064. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49065. /**
  49066. * Gets the Up vector of the Spotlight for texture projection.
  49067. */
  49068. get: function () {
  49069. return this._projectionTextureUpDirection;
  49070. },
  49071. /**
  49072. * Sets the Up vector of the Spotlight for texture projection.
  49073. */
  49074. set: function (value) {
  49075. this._projectionTextureUpDirection = value;
  49076. this._projectionTextureProjectionLightDirty = true;
  49077. },
  49078. enumerable: true,
  49079. configurable: true
  49080. });
  49081. ;
  49082. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49083. /**
  49084. * Gets the projection texture of the light.
  49085. */
  49086. get: function () {
  49087. return this._projectionTexture;
  49088. },
  49089. /**
  49090. * Sets the projection texture of the light.
  49091. */
  49092. set: function (value) {
  49093. this._projectionTexture = value;
  49094. this._projectionTextureDirty = true;
  49095. },
  49096. enumerable: true,
  49097. configurable: true
  49098. });
  49099. /**
  49100. * Returns the string "SpotLight".
  49101. * @returns the class name
  49102. */
  49103. SpotLight.prototype.getClassName = function () {
  49104. return "SpotLight";
  49105. };
  49106. /**
  49107. * Returns the integer 2.
  49108. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49109. */
  49110. SpotLight.prototype.getTypeID = function () {
  49111. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49112. };
  49113. /**
  49114. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49115. */
  49116. SpotLight.prototype._setDirection = function (value) {
  49117. _super.prototype._setDirection.call(this, value);
  49118. this._projectionTextureViewLightDirty = true;
  49119. };
  49120. /**
  49121. * Overrides the position setter to recompute the projection texture view light Matrix.
  49122. */
  49123. SpotLight.prototype._setPosition = function (value) {
  49124. _super.prototype._setPosition.call(this, value);
  49125. this._projectionTextureViewLightDirty = true;
  49126. };
  49127. /**
  49128. * 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.
  49129. * Returns the SpotLight.
  49130. */
  49131. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49132. var activeCamera = this.getScene().activeCamera;
  49133. if (!activeCamera) {
  49134. return;
  49135. }
  49136. this._shadowAngleScale = this._shadowAngleScale || 1;
  49137. var angle = this._shadowAngleScale * this._angle;
  49138. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49139. };
  49140. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49141. this._projectionTextureViewLightDirty = false;
  49142. this._projectionTextureDirty = true;
  49143. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49144. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49145. };
  49146. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49147. this._projectionTextureProjectionLightDirty = false;
  49148. this._projectionTextureDirty = true;
  49149. var light_far = this.projectionTextureLightFar;
  49150. var light_near = this.projectionTextureLightNear;
  49151. var P = light_far / (light_far - light_near);
  49152. var Q = -P * light_near;
  49153. var S = 1.0 / Math.tan(this._angle / 2.0);
  49154. var A = 1.0;
  49155. 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);
  49156. };
  49157. /**
  49158. * Main function for light texture projection matrix computing.
  49159. */
  49160. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49161. this._projectionTextureDirty = false;
  49162. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49163. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49164. };
  49165. SpotLight.prototype._buildUniformLayout = function () {
  49166. this._uniformBuffer.addUniform("vLightData", 4);
  49167. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49168. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49169. this._uniformBuffer.addUniform("vLightDirection", 3);
  49170. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49171. this._uniformBuffer.addUniform("depthValues", 2);
  49172. this._uniformBuffer.create();
  49173. };
  49174. /**
  49175. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49176. * @param effect The effect to update
  49177. * @param lightIndex The index of the light in the effect to update
  49178. * @returns The spot light
  49179. */
  49180. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49181. var normalizeDirection;
  49182. if (this.computeTransformedInformation()) {
  49183. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49184. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49185. }
  49186. else {
  49187. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49188. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49189. }
  49190. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49191. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49192. if (this._projectionTextureViewLightDirty) {
  49193. this._computeProjectionTextureViewLightMatrix();
  49194. }
  49195. if (this._projectionTextureProjectionLightDirty) {
  49196. this._computeProjectionTextureProjectionLightMatrix();
  49197. }
  49198. if (this._projectionTextureDirty) {
  49199. this._computeProjectionTextureMatrix();
  49200. }
  49201. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49202. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49203. }
  49204. return this;
  49205. };
  49206. /**
  49207. * Disposes the light and the associated resources.
  49208. */
  49209. SpotLight.prototype.dispose = function () {
  49210. _super.prototype.dispose.call(this);
  49211. if (this._projectionTexture) {
  49212. this._projectionTexture.dispose();
  49213. }
  49214. };
  49215. __decorate([
  49216. BABYLON.serialize()
  49217. ], SpotLight.prototype, "angle", null);
  49218. __decorate([
  49219. BABYLON.serialize()
  49220. ], SpotLight.prototype, "shadowAngleScale", null);
  49221. __decorate([
  49222. BABYLON.serialize()
  49223. ], SpotLight.prototype, "exponent", void 0);
  49224. __decorate([
  49225. BABYLON.serialize()
  49226. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49227. __decorate([
  49228. BABYLON.serialize()
  49229. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49230. __decorate([
  49231. BABYLON.serialize()
  49232. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49233. __decorate([
  49234. BABYLON.serializeAsTexture("projectedLightTexture")
  49235. ], SpotLight.prototype, "_projectionTexture", void 0);
  49236. return SpotLight;
  49237. }(BABYLON.ShadowLight));
  49238. BABYLON.SpotLight = SpotLight;
  49239. })(BABYLON || (BABYLON = {}));
  49240. //# sourceMappingURL=babylon.spotLight.js.map
  49241. "use strict";
  49242. var BABYLON;
  49243. (function (BABYLON) {
  49244. /**
  49245. * Class used to override all child animations of a given target
  49246. */
  49247. var AnimationPropertiesOverride = /** @class */ (function () {
  49248. function AnimationPropertiesOverride() {
  49249. /**
  49250. * Gets or sets a value indicating if animation blending must be used
  49251. */
  49252. this.enableBlending = false;
  49253. /**
  49254. * Gets or sets the blending speed to use when enableBlending is true
  49255. */
  49256. this.blendingSpeed = 0.01;
  49257. /**
  49258. * Gets or sets the default loop mode to use
  49259. */
  49260. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49261. }
  49262. return AnimationPropertiesOverride;
  49263. }());
  49264. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49265. })(BABYLON || (BABYLON = {}));
  49266. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49267. "use strict";
  49268. var BABYLON;
  49269. (function (BABYLON) {
  49270. var AnimationRange = /** @class */ (function () {
  49271. function AnimationRange(name, from, to) {
  49272. this.name = name;
  49273. this.from = from;
  49274. this.to = to;
  49275. }
  49276. AnimationRange.prototype.clone = function () {
  49277. return new AnimationRange(this.name, this.from, this.to);
  49278. };
  49279. return AnimationRange;
  49280. }());
  49281. BABYLON.AnimationRange = AnimationRange;
  49282. /**
  49283. * Composed of a frame, and an action function
  49284. */
  49285. var AnimationEvent = /** @class */ (function () {
  49286. function AnimationEvent(frame, action, onlyOnce) {
  49287. this.frame = frame;
  49288. this.action = action;
  49289. this.onlyOnce = onlyOnce;
  49290. this.isDone = false;
  49291. }
  49292. return AnimationEvent;
  49293. }());
  49294. BABYLON.AnimationEvent = AnimationEvent;
  49295. var PathCursor = /** @class */ (function () {
  49296. function PathCursor(path) {
  49297. this.path = path;
  49298. this._onchange = new Array();
  49299. this.value = 0;
  49300. this.animations = new Array();
  49301. }
  49302. PathCursor.prototype.getPoint = function () {
  49303. var point = this.path.getPointAtLengthPosition(this.value);
  49304. return new BABYLON.Vector3(point.x, 0, point.y);
  49305. };
  49306. PathCursor.prototype.moveAhead = function (step) {
  49307. if (step === void 0) { step = 0.002; }
  49308. this.move(step);
  49309. return this;
  49310. };
  49311. PathCursor.prototype.moveBack = function (step) {
  49312. if (step === void 0) { step = 0.002; }
  49313. this.move(-step);
  49314. return this;
  49315. };
  49316. PathCursor.prototype.move = function (step) {
  49317. if (Math.abs(step) > 1) {
  49318. throw "step size should be less than 1.";
  49319. }
  49320. this.value += step;
  49321. this.ensureLimits();
  49322. this.raiseOnChange();
  49323. return this;
  49324. };
  49325. PathCursor.prototype.ensureLimits = function () {
  49326. while (this.value > 1) {
  49327. this.value -= 1;
  49328. }
  49329. while (this.value < 0) {
  49330. this.value += 1;
  49331. }
  49332. return this;
  49333. };
  49334. // used by animation engine
  49335. PathCursor.prototype.raiseOnChange = function () {
  49336. var _this = this;
  49337. this._onchange.forEach(function (f) { return f(_this); });
  49338. return this;
  49339. };
  49340. PathCursor.prototype.onchange = function (f) {
  49341. this._onchange.push(f);
  49342. return this;
  49343. };
  49344. return PathCursor;
  49345. }());
  49346. BABYLON.PathCursor = PathCursor;
  49347. var AnimationKeyInterpolation;
  49348. (function (AnimationKeyInterpolation) {
  49349. /**
  49350. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  49351. */
  49352. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49353. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49354. var Animation = /** @class */ (function () {
  49355. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  49356. this.name = name;
  49357. this.targetProperty = targetProperty;
  49358. this.framePerSecond = framePerSecond;
  49359. this.dataType = dataType;
  49360. this.loopMode = loopMode;
  49361. this.enableBlending = enableBlending;
  49362. this._runtimeAnimations = new Array();
  49363. // The set of event that will be linked to this animation
  49364. this._events = new Array();
  49365. this.blendingSpeed = 0.01;
  49366. this._ranges = {};
  49367. this.targetPropertyPath = targetProperty.split(".");
  49368. this.dataType = dataType;
  49369. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49370. }
  49371. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49372. var dataType = undefined;
  49373. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49374. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49375. }
  49376. else if (from instanceof BABYLON.Quaternion) {
  49377. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49378. }
  49379. else if (from instanceof BABYLON.Vector3) {
  49380. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49381. }
  49382. else if (from instanceof BABYLON.Vector2) {
  49383. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49384. }
  49385. else if (from instanceof BABYLON.Color3) {
  49386. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49387. }
  49388. else if (from instanceof BABYLON.Size) {
  49389. dataType = Animation.ANIMATIONTYPE_SIZE;
  49390. }
  49391. if (dataType == undefined) {
  49392. return null;
  49393. }
  49394. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49395. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49396. animation.setKeys(keys);
  49397. if (easingFunction !== undefined) {
  49398. animation.setEasingFunction(easingFunction);
  49399. }
  49400. return animation;
  49401. };
  49402. /**
  49403. * Sets up an animation.
  49404. * @param property the property to animate
  49405. * @param animationType the animation type to apply
  49406. * @param easingFunction the easing function used in the animation
  49407. * @returns The created animation
  49408. */
  49409. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49410. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49411. animation.setEasingFunction(easingFunction);
  49412. return animation;
  49413. };
  49414. /**
  49415. * Create and start an animation on a node
  49416. * @param {string} name defines the name of the global animation that will be run on all nodes
  49417. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49418. * @param {string} targetProperty defines property to animate
  49419. * @param {number} framePerSecond defines the number of frame per second yo use
  49420. * @param {number} totalFrame defines the number of frames in total
  49421. * @param {any} from defines the initial value
  49422. * @param {any} to defines the final value
  49423. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49424. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49425. * @param onAnimationEnd defines the callback to call when animation end
  49426. * @returns the animatable created for this animation
  49427. */
  49428. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49429. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49430. if (!animation) {
  49431. return null;
  49432. }
  49433. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49434. };
  49435. /**
  49436. * Create and start an animation on a node and its descendants
  49437. * @param {string} name defines the name of the global animation that will be run on all nodes
  49438. * @param {BABYLON.Node} node defines the root node where the animation will take place
  49439. * @param {boolean} 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.
  49440. * @param {string} targetProperty defines property to animate
  49441. * @param {number} framePerSecond defines the number of frame per second yo use
  49442. * @param {number} totalFrame defines the number of frames in total
  49443. * @param {any} from defines the initial value
  49444. * @param {any} to defines the final value
  49445. * @param {number} loopMode defines which loop mode you want to use (off by default)
  49446. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  49447. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49448. * @returns the list of animatables created for all nodes
  49449. * @example https://www.babylonjs-playground.com/#MH0VLI
  49450. */
  49451. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49452. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49453. if (!animation) {
  49454. return null;
  49455. }
  49456. var scene = node.getScene();
  49457. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49458. };
  49459. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49460. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49461. if (!animation) {
  49462. return null;
  49463. }
  49464. node.animations.push(animation);
  49465. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49466. };
  49467. /**
  49468. * Transition property of the Camera to the target Value.
  49469. * @param property The property to transition
  49470. * @param targetValue The target Value of the property
  49471. * @param host The object where the property to animate belongs
  49472. * @param scene Scene used to run the animation
  49473. * @param frameRate Framerate (in frame/s) to use
  49474. * @param transition The transition type we want to use
  49475. * @param duration The duration of the animation, in milliseconds
  49476. * @param onAnimationEnd Call back trigger at the end of the animation.
  49477. */
  49478. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49479. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49480. if (duration <= 0) {
  49481. host[property] = targetValue;
  49482. if (onAnimationEnd) {
  49483. onAnimationEnd();
  49484. }
  49485. return null;
  49486. }
  49487. var endFrame = frameRate * (duration / 1000);
  49488. transition.setKeys([{
  49489. frame: 0,
  49490. value: host[property].clone ? host[property].clone() : host[property]
  49491. },
  49492. {
  49493. frame: endFrame,
  49494. value: targetValue
  49495. }]);
  49496. if (!host.animations) {
  49497. host.animations = [];
  49498. }
  49499. host.animations.push(transition);
  49500. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49501. animation.onAnimationEnd = onAnimationEnd;
  49502. return animation;
  49503. };
  49504. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49505. /**
  49506. * Return the array of runtime animations currently using this animation
  49507. */
  49508. get: function () {
  49509. return this._runtimeAnimations;
  49510. },
  49511. enumerable: true,
  49512. configurable: true
  49513. });
  49514. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49515. get: function () {
  49516. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49517. var runtimeAnimation = _a[_i];
  49518. if (!runtimeAnimation.isStopped) {
  49519. return true;
  49520. }
  49521. }
  49522. return false;
  49523. },
  49524. enumerable: true,
  49525. configurable: true
  49526. });
  49527. // Methods
  49528. /**
  49529. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  49530. */
  49531. Animation.prototype.toString = function (fullDetails) {
  49532. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49533. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49534. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49535. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49536. if (fullDetails) {
  49537. ret += ", Ranges: {";
  49538. var first = true;
  49539. for (var name in this._ranges) {
  49540. if (first) {
  49541. ret += ", ";
  49542. first = false;
  49543. }
  49544. ret += name;
  49545. }
  49546. ret += "}";
  49547. }
  49548. return ret;
  49549. };
  49550. /**
  49551. * Add an event to this animation.
  49552. */
  49553. Animation.prototype.addEvent = function (event) {
  49554. this._events.push(event);
  49555. };
  49556. /**
  49557. * Remove all events found at the given frame
  49558. * @param frame
  49559. */
  49560. Animation.prototype.removeEvents = function (frame) {
  49561. for (var index = 0; index < this._events.length; index++) {
  49562. if (this._events[index].frame === frame) {
  49563. this._events.splice(index, 1);
  49564. index--;
  49565. }
  49566. }
  49567. };
  49568. Animation.prototype.getEvents = function () {
  49569. return this._events;
  49570. };
  49571. Animation.prototype.createRange = function (name, from, to) {
  49572. // check name not already in use; could happen for bones after serialized
  49573. if (!this._ranges[name]) {
  49574. this._ranges[name] = new AnimationRange(name, from, to);
  49575. }
  49576. };
  49577. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49578. if (deleteFrames === void 0) { deleteFrames = true; }
  49579. var range = this._ranges[name];
  49580. if (!range) {
  49581. return;
  49582. }
  49583. if (deleteFrames) {
  49584. var from = range.from;
  49585. var to = range.to;
  49586. // this loop MUST go high to low for multiple splices to work
  49587. for (var key = this._keys.length - 1; key >= 0; key--) {
  49588. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49589. this._keys.splice(key, 1);
  49590. }
  49591. }
  49592. }
  49593. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49594. };
  49595. Animation.prototype.getRange = function (name) {
  49596. return this._ranges[name];
  49597. };
  49598. Animation.prototype.getKeys = function () {
  49599. return this._keys;
  49600. };
  49601. Animation.prototype.getHighestFrame = function () {
  49602. var ret = 0;
  49603. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49604. if (ret < this._keys[key].frame) {
  49605. ret = this._keys[key].frame;
  49606. }
  49607. }
  49608. return ret;
  49609. };
  49610. Animation.prototype.getEasingFunction = function () {
  49611. return this._easingFunction;
  49612. };
  49613. Animation.prototype.setEasingFunction = function (easingFunction) {
  49614. this._easingFunction = easingFunction;
  49615. };
  49616. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49617. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49618. };
  49619. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49620. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49621. };
  49622. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49623. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49624. };
  49625. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49626. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49627. };
  49628. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49629. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49630. };
  49631. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49632. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49633. };
  49634. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49635. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49636. };
  49637. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49638. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49639. };
  49640. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49641. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49642. };
  49643. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49644. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49645. };
  49646. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  49647. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49648. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49649. }
  49650. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49651. };
  49652. Animation.prototype.clone = function () {
  49653. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49654. clone.enableBlending = this.enableBlending;
  49655. clone.blendingSpeed = this.blendingSpeed;
  49656. if (this._keys) {
  49657. clone.setKeys(this._keys);
  49658. }
  49659. if (this._ranges) {
  49660. clone._ranges = {};
  49661. for (var name in this._ranges) {
  49662. var range = this._ranges[name];
  49663. if (!range) {
  49664. continue;
  49665. }
  49666. clone._ranges[name] = range.clone();
  49667. }
  49668. }
  49669. return clone;
  49670. };
  49671. Animation.prototype.setKeys = function (values) {
  49672. this._keys = values.slice(0);
  49673. };
  49674. Animation.prototype.serialize = function () {
  49675. var serializationObject = {};
  49676. serializationObject.name = this.name;
  49677. serializationObject.property = this.targetProperty;
  49678. serializationObject.framePerSecond = this.framePerSecond;
  49679. serializationObject.dataType = this.dataType;
  49680. serializationObject.loopBehavior = this.loopMode;
  49681. serializationObject.enableBlending = this.enableBlending;
  49682. serializationObject.blendingSpeed = this.blendingSpeed;
  49683. var dataType = this.dataType;
  49684. serializationObject.keys = [];
  49685. var keys = this.getKeys();
  49686. for (var index = 0; index < keys.length; index++) {
  49687. var animationKey = keys[index];
  49688. var key = {};
  49689. key.frame = animationKey.frame;
  49690. switch (dataType) {
  49691. case Animation.ANIMATIONTYPE_FLOAT:
  49692. key.values = [animationKey.value];
  49693. break;
  49694. case Animation.ANIMATIONTYPE_QUATERNION:
  49695. case Animation.ANIMATIONTYPE_MATRIX:
  49696. case Animation.ANIMATIONTYPE_VECTOR3:
  49697. case Animation.ANIMATIONTYPE_COLOR3:
  49698. key.values = animationKey.value.asArray();
  49699. break;
  49700. }
  49701. serializationObject.keys.push(key);
  49702. }
  49703. serializationObject.ranges = [];
  49704. for (var name in this._ranges) {
  49705. var source = this._ranges[name];
  49706. if (!source) {
  49707. continue;
  49708. }
  49709. var range = {};
  49710. range.name = name;
  49711. range.from = source.from;
  49712. range.to = source.to;
  49713. serializationObject.ranges.push(range);
  49714. }
  49715. return serializationObject;
  49716. };
  49717. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49718. get: function () {
  49719. return Animation._ANIMATIONTYPE_FLOAT;
  49720. },
  49721. enumerable: true,
  49722. configurable: true
  49723. });
  49724. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49725. get: function () {
  49726. return Animation._ANIMATIONTYPE_VECTOR3;
  49727. },
  49728. enumerable: true,
  49729. configurable: true
  49730. });
  49731. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49732. get: function () {
  49733. return Animation._ANIMATIONTYPE_VECTOR2;
  49734. },
  49735. enumerable: true,
  49736. configurable: true
  49737. });
  49738. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  49739. get: function () {
  49740. return Animation._ANIMATIONTYPE_SIZE;
  49741. },
  49742. enumerable: true,
  49743. configurable: true
  49744. });
  49745. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  49746. get: function () {
  49747. return Animation._ANIMATIONTYPE_QUATERNION;
  49748. },
  49749. enumerable: true,
  49750. configurable: true
  49751. });
  49752. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  49753. get: function () {
  49754. return Animation._ANIMATIONTYPE_MATRIX;
  49755. },
  49756. enumerable: true,
  49757. configurable: true
  49758. });
  49759. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  49760. get: function () {
  49761. return Animation._ANIMATIONTYPE_COLOR3;
  49762. },
  49763. enumerable: true,
  49764. configurable: true
  49765. });
  49766. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  49767. get: function () {
  49768. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  49769. },
  49770. enumerable: true,
  49771. configurable: true
  49772. });
  49773. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  49774. get: function () {
  49775. return Animation._ANIMATIONLOOPMODE_CYCLE;
  49776. },
  49777. enumerable: true,
  49778. configurable: true
  49779. });
  49780. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  49781. get: function () {
  49782. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  49783. },
  49784. enumerable: true,
  49785. configurable: true
  49786. });
  49787. Animation.Parse = function (parsedAnimation) {
  49788. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  49789. var dataType = parsedAnimation.dataType;
  49790. var keys = [];
  49791. var data;
  49792. var index;
  49793. if (parsedAnimation.enableBlending) {
  49794. animation.enableBlending = parsedAnimation.enableBlending;
  49795. }
  49796. if (parsedAnimation.blendingSpeed) {
  49797. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  49798. }
  49799. for (index = 0; index < parsedAnimation.keys.length; index++) {
  49800. var key = parsedAnimation.keys[index];
  49801. var inTangent;
  49802. var outTangent;
  49803. switch (dataType) {
  49804. case Animation.ANIMATIONTYPE_FLOAT:
  49805. data = key.values[0];
  49806. if (key.values.length >= 1) {
  49807. inTangent = key.values[1];
  49808. }
  49809. if (key.values.length >= 2) {
  49810. outTangent = key.values[2];
  49811. }
  49812. break;
  49813. case Animation.ANIMATIONTYPE_QUATERNION:
  49814. data = BABYLON.Quaternion.FromArray(key.values);
  49815. if (key.values.length >= 8) {
  49816. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  49817. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  49818. inTangent = _inTangent;
  49819. }
  49820. }
  49821. if (key.values.length >= 12) {
  49822. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  49823. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  49824. outTangent = _outTangent;
  49825. }
  49826. }
  49827. break;
  49828. case Animation.ANIMATIONTYPE_MATRIX:
  49829. data = BABYLON.Matrix.FromArray(key.values);
  49830. break;
  49831. case Animation.ANIMATIONTYPE_COLOR3:
  49832. data = BABYLON.Color3.FromArray(key.values);
  49833. break;
  49834. case Animation.ANIMATIONTYPE_VECTOR3:
  49835. default:
  49836. data = BABYLON.Vector3.FromArray(key.values);
  49837. break;
  49838. }
  49839. var keyData = {};
  49840. keyData.frame = key.frame;
  49841. keyData.value = data;
  49842. if (inTangent != undefined) {
  49843. keyData.inTangent = inTangent;
  49844. }
  49845. if (outTangent != undefined) {
  49846. keyData.outTangent = outTangent;
  49847. }
  49848. keys.push(keyData);
  49849. }
  49850. animation.setKeys(keys);
  49851. if (parsedAnimation.ranges) {
  49852. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  49853. data = parsedAnimation.ranges[index];
  49854. animation.createRange(data.name, data.from, data.to);
  49855. }
  49856. }
  49857. return animation;
  49858. };
  49859. Animation.AppendSerializedAnimations = function (source, destination) {
  49860. if (source.animations) {
  49861. destination.animations = [];
  49862. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  49863. var animation = source.animations[animationIndex];
  49864. destination.animations.push(animation.serialize());
  49865. }
  49866. }
  49867. };
  49868. /**
  49869. * Use matrix interpolation instead of using direct key value when animating matrices
  49870. */
  49871. Animation.AllowMatricesInterpolation = false;
  49872. /**
  49873. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  49874. */
  49875. Animation.AllowMatrixDecomposeForInterpolation = true;
  49876. // Statics
  49877. Animation._ANIMATIONTYPE_FLOAT = 0;
  49878. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  49879. Animation._ANIMATIONTYPE_QUATERNION = 2;
  49880. Animation._ANIMATIONTYPE_MATRIX = 3;
  49881. Animation._ANIMATIONTYPE_COLOR3 = 4;
  49882. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  49883. Animation._ANIMATIONTYPE_SIZE = 6;
  49884. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  49885. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  49886. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  49887. return Animation;
  49888. }());
  49889. BABYLON.Animation = Animation;
  49890. })(BABYLON || (BABYLON = {}));
  49891. //# sourceMappingURL=babylon.animation.js.map
  49892. "use strict";
  49893. var BABYLON;
  49894. (function (BABYLON) {
  49895. /**
  49896. * This class defines the direct association between an animation and a target
  49897. */
  49898. var TargetedAnimation = /** @class */ (function () {
  49899. function TargetedAnimation() {
  49900. }
  49901. return TargetedAnimation;
  49902. }());
  49903. BABYLON.TargetedAnimation = TargetedAnimation;
  49904. /**
  49905. * Use this class to create coordinated animations on multiple targets
  49906. */
  49907. var AnimationGroup = /** @class */ (function () {
  49908. function AnimationGroup(name, scene) {
  49909. if (scene === void 0) { scene = null; }
  49910. this.name = name;
  49911. this._targetedAnimations = new Array();
  49912. this._animatables = new Array();
  49913. this._from = Number.MAX_VALUE;
  49914. this._to = -Number.MAX_VALUE;
  49915. this._speedRatio = 1;
  49916. this.onAnimationEndObservable = new BABYLON.Observable();
  49917. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49918. this._scene.animationGroups.push(this);
  49919. }
  49920. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  49921. /**
  49922. * Define if the animations are started
  49923. */
  49924. get: function () {
  49925. return this._isStarted;
  49926. },
  49927. enumerable: true,
  49928. configurable: true
  49929. });
  49930. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  49931. /**
  49932. * Gets or sets the speed ratio to use for all animations
  49933. */
  49934. get: function () {
  49935. return this._speedRatio;
  49936. },
  49937. /**
  49938. * Gets or sets the speed ratio to use for all animations
  49939. */
  49940. set: function (value) {
  49941. if (this._speedRatio === value) {
  49942. return;
  49943. }
  49944. this._speedRatio = value;
  49945. for (var index = 0; index < this._animatables.length; index++) {
  49946. var animatable = this._animatables[index];
  49947. animatable.speedRatio = this._speedRatio;
  49948. }
  49949. },
  49950. enumerable: true,
  49951. configurable: true
  49952. });
  49953. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  49954. /**
  49955. * Gets the targeted animations for this animation group
  49956. */
  49957. get: function () {
  49958. return this._targetedAnimations;
  49959. },
  49960. enumerable: true,
  49961. configurable: true
  49962. });
  49963. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  49964. /**
  49965. * returning the list of animatables controlled by this animation group.
  49966. */
  49967. get: function () {
  49968. return this._animatables;
  49969. },
  49970. enumerable: true,
  49971. configurable: true
  49972. });
  49973. /**
  49974. * Add an animation (with its target) in the group
  49975. * @param animation defines the animation we want to add
  49976. * @param target defines the target of the animation
  49977. * @returns the {BABYLON.TargetedAnimation} object
  49978. */
  49979. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  49980. var targetedAnimation = {
  49981. animation: animation,
  49982. target: target
  49983. };
  49984. var keys = animation.getKeys();
  49985. if (this._from > keys[0].frame) {
  49986. this._from = keys[0].frame;
  49987. }
  49988. if (this._to < keys[keys.length - 1].frame) {
  49989. this._to = keys[keys.length - 1].frame;
  49990. }
  49991. this._targetedAnimations.push(targetedAnimation);
  49992. return targetedAnimation;
  49993. };
  49994. /**
  49995. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  49996. * It can add constant keys at begin or end
  49997. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  49998. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  49999. */
  50000. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50001. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  50002. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  50003. beginFrame = Math.max(beginFrame, this._from);
  50004. endFrame = Math.min(endFrame, this._to);
  50005. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50006. var targetedAnimation = this._targetedAnimations[index];
  50007. var keys = targetedAnimation.animation.getKeys();
  50008. var startKey = keys[0];
  50009. var endKey = keys[keys.length - 1];
  50010. if (startKey.frame > beginFrame) {
  50011. var newKey = {
  50012. frame: beginFrame,
  50013. value: startKey.value,
  50014. inTangent: startKey.inTangent,
  50015. outTangent: startKey.outTangent,
  50016. interpolation: startKey.interpolation
  50017. };
  50018. keys.splice(0, 0, newKey);
  50019. }
  50020. if (endKey.frame < endFrame) {
  50021. var newKey = {
  50022. frame: endFrame,
  50023. value: endKey.value,
  50024. inTangent: endKey.outTangent,
  50025. outTangent: endKey.outTangent,
  50026. interpolation: endKey.interpolation
  50027. };
  50028. keys.push(newKey);
  50029. }
  50030. }
  50031. return this;
  50032. };
  50033. /**
  50034. * Start all animations on given targets
  50035. * @param loop defines if animations must loop
  50036. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50037. * @param from defines the from key (optional)
  50038. * @param to defines the to key (optional)
  50039. * @returns the current animation group
  50040. */
  50041. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50042. var _this = this;
  50043. if (loop === void 0) { loop = false; }
  50044. if (speedRatio === void 0) { speedRatio = 1; }
  50045. if (this._isStarted || this._targetedAnimations.length === 0) {
  50046. return this;
  50047. }
  50048. var _loop_1 = function () {
  50049. var targetedAnimation = this_1._targetedAnimations[index];
  50050. if (!targetedAnimation.target.animations) {
  50051. targetedAnimation.target.animations = [];
  50052. }
  50053. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  50054. targetedAnimation.target.animations.push(targetedAnimation.animation);
  50055. }
  50056. 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 () {
  50057. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50058. }));
  50059. };
  50060. var this_1 = this;
  50061. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50062. _loop_1();
  50063. }
  50064. this._speedRatio = speedRatio;
  50065. this._isStarted = true;
  50066. return this;
  50067. };
  50068. /**
  50069. * Pause all animations
  50070. */
  50071. AnimationGroup.prototype.pause = function () {
  50072. if (!this._isStarted) {
  50073. return this;
  50074. }
  50075. for (var index = 0; index < this._animatables.length; index++) {
  50076. var animatable = this._animatables[index];
  50077. animatable.pause();
  50078. }
  50079. return this;
  50080. };
  50081. /**
  50082. * Play all animations to initial state
  50083. * This function will start() the animations if they were not started or will restart() them if they were paused
  50084. * @param loop defines if animations must loop
  50085. */
  50086. AnimationGroup.prototype.play = function (loop) {
  50087. if (this.isStarted) {
  50088. if (loop !== undefined) {
  50089. for (var index = 0; index < this._animatables.length; index++) {
  50090. var animatable = this._animatables[index];
  50091. animatable.loopAnimation = loop;
  50092. }
  50093. }
  50094. this.restart();
  50095. }
  50096. else {
  50097. this.start(loop, this._speedRatio);
  50098. }
  50099. return this;
  50100. };
  50101. /**
  50102. * Reset all animations to initial state
  50103. */
  50104. AnimationGroup.prototype.reset = function () {
  50105. if (!this._isStarted) {
  50106. return this;
  50107. }
  50108. for (var index = 0; index < this._animatables.length; index++) {
  50109. var animatable = this._animatables[index];
  50110. animatable.reset();
  50111. }
  50112. return this;
  50113. };
  50114. /**
  50115. * Restart animations from key 0
  50116. */
  50117. AnimationGroup.prototype.restart = function () {
  50118. if (!this._isStarted) {
  50119. return this;
  50120. }
  50121. for (var index = 0; index < this._animatables.length; index++) {
  50122. var animatable = this._animatables[index];
  50123. animatable.restart();
  50124. }
  50125. return this;
  50126. };
  50127. /**
  50128. * Stop all animations
  50129. */
  50130. AnimationGroup.prototype.stop = function () {
  50131. if (!this._isStarted) {
  50132. return this;
  50133. }
  50134. for (var index = 0; index < this._animatables.length; index++) {
  50135. var animatable = this._animatables[index];
  50136. animatable.stop();
  50137. }
  50138. this._isStarted = false;
  50139. return this;
  50140. };
  50141. /**
  50142. * Goes to a specific frame in this animation group
  50143. *
  50144. * @param frame the frame number to go to
  50145. * @return the animationGroup
  50146. */
  50147. AnimationGroup.prototype.goToFrame = function (frame) {
  50148. if (!this._isStarted) {
  50149. return this;
  50150. }
  50151. for (var index = 0; index < this._animatables.length; index++) {
  50152. var animatable = this._animatables[index];
  50153. animatable.goToFrame(frame);
  50154. }
  50155. return this;
  50156. };
  50157. /**
  50158. * Dispose all associated resources
  50159. */
  50160. AnimationGroup.prototype.dispose = function () {
  50161. this._targetedAnimations = [];
  50162. this._animatables = [];
  50163. var index = this._scene.animationGroups.indexOf(this);
  50164. if (index > -1) {
  50165. this._scene.animationGroups.splice(index, 1);
  50166. }
  50167. };
  50168. return AnimationGroup;
  50169. }());
  50170. BABYLON.AnimationGroup = AnimationGroup;
  50171. })(BABYLON || (BABYLON = {}));
  50172. //# sourceMappingURL=babylon.animationGroup.js.map
  50173. "use strict";
  50174. var BABYLON;
  50175. (function (BABYLON) {
  50176. var RuntimeAnimation = /** @class */ (function () {
  50177. /**
  50178. * Create a new RuntimeAnimation object
  50179. * @param target defines the target of the animation
  50180. * @param animation defines the source {BABYLON.Animation} object
  50181. * @param scene defines the hosting scene
  50182. * @param host defines the initiating Animatable
  50183. */
  50184. function RuntimeAnimation(target, animation, scene, host) {
  50185. this._currentFrame = 0;
  50186. this._offsetsCache = {};
  50187. this._highLimitsCache = {};
  50188. this._stopped = false;
  50189. this._blendingFactor = 0;
  50190. this._targetPath = "";
  50191. this._weight = 1.0;
  50192. this._ratioOffset = 0;
  50193. this._previousDelay = 0;
  50194. this._previousRatio = 0;
  50195. this._animation = animation;
  50196. this._target = target;
  50197. this._scene = scene;
  50198. this._host = host;
  50199. animation._runtimeAnimations.push(this);
  50200. }
  50201. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50202. /**
  50203. * Gets the current frame
  50204. */
  50205. get: function () {
  50206. return this._currentFrame;
  50207. },
  50208. enumerable: true,
  50209. configurable: true
  50210. });
  50211. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50212. /**
  50213. * Gets the weight of the runtime animation
  50214. */
  50215. get: function () {
  50216. return this._weight;
  50217. },
  50218. enumerable: true,
  50219. configurable: true
  50220. });
  50221. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  50222. /**
  50223. * Gets the original value of the runtime animation
  50224. */
  50225. get: function () {
  50226. return this._originalValue;
  50227. },
  50228. enumerable: true,
  50229. configurable: true
  50230. });
  50231. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50232. /**
  50233. * Gets the current value of the runtime animation
  50234. */
  50235. get: function () {
  50236. return this._currentValue;
  50237. },
  50238. enumerable: true,
  50239. configurable: true
  50240. });
  50241. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50242. /**
  50243. * Gets the path where to store the animated value in the target
  50244. */
  50245. get: function () {
  50246. return this._targetPath;
  50247. },
  50248. enumerable: true,
  50249. configurable: true
  50250. });
  50251. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50252. /**
  50253. * Gets the actual target of the runtime animation
  50254. */
  50255. get: function () {
  50256. return this._activeTarget;
  50257. },
  50258. enumerable: true,
  50259. configurable: true
  50260. });
  50261. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50262. get: function () {
  50263. return this._animation;
  50264. },
  50265. enumerable: true,
  50266. configurable: true
  50267. });
  50268. RuntimeAnimation.prototype.reset = function () {
  50269. this._offsetsCache = {};
  50270. this._highLimitsCache = {};
  50271. this._currentFrame = 0;
  50272. this._blendingFactor = 0;
  50273. this._originalValue = null;
  50274. };
  50275. RuntimeAnimation.prototype.isStopped = function () {
  50276. return this._stopped;
  50277. };
  50278. RuntimeAnimation.prototype.dispose = function () {
  50279. var index = this._animation.runtimeAnimations.indexOf(this);
  50280. if (index > -1) {
  50281. this._animation.runtimeAnimations.splice(index, 1);
  50282. }
  50283. };
  50284. RuntimeAnimation.prototype._getKeyValue = function (value) {
  50285. if (typeof value === "function") {
  50286. return value();
  50287. }
  50288. return value;
  50289. };
  50290. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50291. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50292. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50293. }
  50294. this._currentFrame = currentFrame;
  50295. var keys = this._animation.getKeys();
  50296. // Try to get a hash to find the right key
  50297. 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));
  50298. if (keys[startKeyIndex].frame >= currentFrame) {
  50299. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50300. startKeyIndex--;
  50301. }
  50302. }
  50303. for (var key = startKeyIndex; key < keys.length; key++) {
  50304. var endKey = keys[key + 1];
  50305. if (endKey.frame >= currentFrame) {
  50306. var startKey = keys[key];
  50307. var startValue = this._getKeyValue(startKey.value);
  50308. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  50309. return startValue;
  50310. }
  50311. var endValue = this._getKeyValue(endKey.value);
  50312. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50313. var frameDelta = endKey.frame - startKey.frame;
  50314. // gradient : percent of currentFrame between the frame inf and the frame sup
  50315. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50316. // check for easingFunction and correction of gradient
  50317. var easingFunction = this._animation.getEasingFunction();
  50318. if (easingFunction != null) {
  50319. gradient = easingFunction.ease(gradient);
  50320. }
  50321. switch (this._animation.dataType) {
  50322. // Float
  50323. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50324. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  50325. switch (loopMode) {
  50326. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50327. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50328. return floatValue;
  50329. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50330. return offsetValue * repeatCount + floatValue;
  50331. }
  50332. break;
  50333. // Quaternion
  50334. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50335. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  50336. switch (loopMode) {
  50337. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50338. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50339. return quatValue;
  50340. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50341. return quatValue.add(offsetValue.scale(repeatCount));
  50342. }
  50343. return quatValue;
  50344. // Vector3
  50345. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50346. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  50347. switch (loopMode) {
  50348. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50349. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50350. return vec3Value;
  50351. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50352. return vec3Value.add(offsetValue.scale(repeatCount));
  50353. }
  50354. // Vector2
  50355. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50356. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  50357. switch (loopMode) {
  50358. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50359. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50360. return vec2Value;
  50361. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50362. return vec2Value.add(offsetValue.scale(repeatCount));
  50363. }
  50364. // Size
  50365. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50366. switch (loopMode) {
  50367. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50368. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50369. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  50370. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50371. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50372. }
  50373. // Color3
  50374. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50375. switch (loopMode) {
  50376. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50377. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50378. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  50379. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50380. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50381. }
  50382. // Matrix
  50383. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  50384. switch (loopMode) {
  50385. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  50386. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  50387. if (BABYLON.Animation.AllowMatricesInterpolation) {
  50388. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  50389. }
  50390. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  50391. return startValue;
  50392. }
  50393. default:
  50394. break;
  50395. }
  50396. break;
  50397. }
  50398. }
  50399. return this._getKeyValue(keys[keys.length - 1].value);
  50400. };
  50401. /**
  50402. * Affect the interpolated value to the target
  50403. * @param currentValue defines the value computed by the animation
  50404. * @param weight defines the weight to apply to this value
  50405. */
  50406. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50407. if (weight === void 0) { weight = 1.0; }
  50408. // Set value
  50409. var path;
  50410. var destination;
  50411. var targetPropertyPath = this._animation.targetPropertyPath;
  50412. if (targetPropertyPath.length > 1) {
  50413. var property = this._target[targetPropertyPath[0]];
  50414. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50415. property = property[targetPropertyPath[index]];
  50416. }
  50417. path = targetPropertyPath[targetPropertyPath.length - 1];
  50418. destination = property;
  50419. }
  50420. else {
  50421. path = targetPropertyPath[0];
  50422. destination = this._target;
  50423. }
  50424. this._targetPath = path;
  50425. this._activeTarget = destination;
  50426. this._weight = weight;
  50427. // Blending
  50428. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50429. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50430. if (enableBlending && this._blendingFactor <= 1.0) {
  50431. if (!this._originalBlendValue) {
  50432. var originalValue = destination[path];
  50433. if (originalValue.clone) {
  50434. this._originalBlendValue = originalValue.clone();
  50435. }
  50436. else {
  50437. this._originalBlendValue = originalValue;
  50438. }
  50439. }
  50440. }
  50441. if (weight !== -1.0) {
  50442. if (!this._originalValue) {
  50443. var originalValue = void 0;
  50444. if (destination.getRestPose) {
  50445. originalValue = destination.getRestPose();
  50446. }
  50447. else {
  50448. originalValue = destination[path];
  50449. }
  50450. if (originalValue.clone) {
  50451. this._originalValue = originalValue.clone();
  50452. }
  50453. else {
  50454. this._originalValue = originalValue;
  50455. }
  50456. }
  50457. }
  50458. if (enableBlending && this._blendingFactor <= 1.0) {
  50459. if (this._originalBlendValue.prototype) {
  50460. if (this._originalBlendValue.prototype.Lerp) {
  50461. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  50462. }
  50463. else {
  50464. this._currentValue = currentValue;
  50465. }
  50466. }
  50467. else if (this._originalBlendValue.m) {
  50468. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50469. if (this._currentValue) {
  50470. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50471. }
  50472. else {
  50473. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50474. }
  50475. }
  50476. else {
  50477. if (this._currentValue) {
  50478. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50479. }
  50480. else {
  50481. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50482. }
  50483. }
  50484. }
  50485. else {
  50486. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  50487. }
  50488. this._blendingFactor += blendingSpeed;
  50489. }
  50490. else {
  50491. this._currentValue = currentValue;
  50492. }
  50493. if (weight !== -1.0) {
  50494. this._scene._registerTargetForLateAnimationBinding(this);
  50495. }
  50496. else {
  50497. destination[path] = this._currentValue;
  50498. }
  50499. if (this._target.markAsDirty) {
  50500. this._target.markAsDirty(this._animation.targetProperty);
  50501. }
  50502. };
  50503. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50504. if (this._target && this._target.animationPropertiesOverride) {
  50505. return this._target.animationPropertiesOverride.loopMode;
  50506. }
  50507. return this._animation.loopMode;
  50508. };
  50509. /**
  50510. * Move the current animation to a given frame
  50511. * @param frame defines the frame to move to
  50512. */
  50513. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50514. var keys = this._animation.getKeys();
  50515. if (frame < keys[0].frame) {
  50516. frame = keys[0].frame;
  50517. }
  50518. else if (frame > keys[keys.length - 1].frame) {
  50519. frame = keys[keys.length - 1].frame;
  50520. }
  50521. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50522. this.setValue(currentValue, -1);
  50523. };
  50524. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50525. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50526. this._ratioOffset = this._previousRatio - newRatio;
  50527. };
  50528. /**
  50529. * Execute the current animation
  50530. * @param delay defines the delay to add to the current frame
  50531. * @param from defines the lower bound of the animation range
  50532. * @param to defines the upper bound of the animation range
  50533. * @param loop defines if the current animation must loop
  50534. * @param speedRatio defines the current speed ratio
  50535. * @param weight defines the weight of the animation (default is -1 so no weight)
  50536. * @returns a boolean indicating if the animation has ended
  50537. */
  50538. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50539. if (weight === void 0) { weight = -1.0; }
  50540. var targetPropertyPath = this._animation.targetPropertyPath;
  50541. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50542. this._stopped = true;
  50543. return false;
  50544. }
  50545. var returnValue = true;
  50546. var keys = this._animation.getKeys();
  50547. // Adding a start key at frame 0 if missing
  50548. if (keys[0].frame !== 0) {
  50549. var newKey = { frame: 0, value: keys[0].value };
  50550. keys.splice(0, 0, newKey);
  50551. }
  50552. // Check limits
  50553. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50554. from = keys[0].frame;
  50555. }
  50556. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50557. to = keys[keys.length - 1].frame;
  50558. }
  50559. //to and from cannot be the same key
  50560. if (from === to) {
  50561. if (from > keys[0].frame) {
  50562. from--;
  50563. }
  50564. else if (to < keys[keys.length - 1].frame) {
  50565. to++;
  50566. }
  50567. }
  50568. // Compute ratio
  50569. var range = to - from;
  50570. var offsetValue;
  50571. // ratio represents the frame delta between from and to
  50572. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50573. var highLimitValue = 0;
  50574. this._previousDelay = delay;
  50575. this._previousRatio = ratio;
  50576. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  50577. returnValue = false;
  50578. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  50579. }
  50580. else {
  50581. // Get max value if required
  50582. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50583. var keyOffset = to.toString() + from.toString();
  50584. if (!this._offsetsCache[keyOffset]) {
  50585. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50586. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50587. switch (this._animation.dataType) {
  50588. // Float
  50589. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50590. this._offsetsCache[keyOffset] = toValue - fromValue;
  50591. break;
  50592. // Quaternion
  50593. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50594. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50595. break;
  50596. // Vector3
  50597. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50598. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50599. // Vector2
  50600. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50601. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50602. // Size
  50603. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50604. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50605. // Color3
  50606. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50607. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50608. default:
  50609. break;
  50610. }
  50611. this._highLimitsCache[keyOffset] = toValue;
  50612. }
  50613. highLimitValue = this._highLimitsCache[keyOffset];
  50614. offsetValue = this._offsetsCache[keyOffset];
  50615. }
  50616. }
  50617. if (offsetValue === undefined) {
  50618. switch (this._animation.dataType) {
  50619. // Float
  50620. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50621. offsetValue = 0;
  50622. break;
  50623. // Quaternion
  50624. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50625. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  50626. break;
  50627. // Vector3
  50628. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50629. offsetValue = BABYLON.Vector3.Zero();
  50630. break;
  50631. // Vector2
  50632. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50633. offsetValue = BABYLON.Vector2.Zero();
  50634. break;
  50635. // Size
  50636. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50637. offsetValue = BABYLON.Size.Zero();
  50638. break;
  50639. // Color3
  50640. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50641. offsetValue = BABYLON.Color3.Black();
  50642. }
  50643. }
  50644. // Compute value
  50645. var repeatCount = (ratio / range) >> 0;
  50646. var currentFrame = returnValue ? from + ratio % range : to;
  50647. // Need to normalize?
  50648. if (this._host && this._host.syncRoot) {
  50649. var syncRoot = this._host.syncRoot;
  50650. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  50651. currentFrame = from + (to - from) * hostNormalizedFrame;
  50652. }
  50653. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  50654. // Set value
  50655. this.setValue(currentValue, weight);
  50656. // Check events
  50657. var events = this._animation.getEvents();
  50658. for (var index = 0; index < events.length; index++) {
  50659. // Make sure current frame has passed event frame and that event frame is within the current range
  50660. // Also, handle both forward and reverse animations
  50661. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  50662. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  50663. var event = events[index];
  50664. if (!event.isDone) {
  50665. // If event should be done only once, remove it.
  50666. if (event.onlyOnce) {
  50667. events.splice(index, 1);
  50668. index--;
  50669. }
  50670. event.isDone = true;
  50671. event.action();
  50672. } // Don't do anything if the event has already be done.
  50673. }
  50674. else if (events[index].isDone && !events[index].onlyOnce) {
  50675. // reset event, the animation is looping
  50676. events[index].isDone = false;
  50677. }
  50678. }
  50679. if (!returnValue) {
  50680. this._stopped = true;
  50681. }
  50682. return returnValue;
  50683. };
  50684. return RuntimeAnimation;
  50685. }());
  50686. BABYLON.RuntimeAnimation = RuntimeAnimation;
  50687. })(BABYLON || (BABYLON = {}));
  50688. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  50689. "use strict";
  50690. var BABYLON;
  50691. (function (BABYLON) {
  50692. var Animatable = /** @class */ (function () {
  50693. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  50694. if (fromFrame === void 0) { fromFrame = 0; }
  50695. if (toFrame === void 0) { toFrame = 100; }
  50696. if (loopAnimation === void 0) { loopAnimation = false; }
  50697. if (speedRatio === void 0) { speedRatio = 1.0; }
  50698. this.target = target;
  50699. this.fromFrame = fromFrame;
  50700. this.toFrame = toFrame;
  50701. this.loopAnimation = loopAnimation;
  50702. this.onAnimationEnd = onAnimationEnd;
  50703. this._localDelayOffset = null;
  50704. this._pausedDelay = null;
  50705. this._runtimeAnimations = new Array();
  50706. this._paused = false;
  50707. this._speedRatio = 1;
  50708. this._weight = -1.0;
  50709. this.animationStarted = false;
  50710. if (animations) {
  50711. this.appendAnimations(target, animations);
  50712. }
  50713. this._speedRatio = speedRatio;
  50714. this._scene = scene;
  50715. scene._activeAnimatables.push(this);
  50716. }
  50717. Object.defineProperty(Animatable.prototype, "syncRoot", {
  50718. /**
  50719. * Gets the root Animatable used to synchronize and normalize animations
  50720. */
  50721. get: function () {
  50722. return this._syncRoot;
  50723. },
  50724. enumerable: true,
  50725. configurable: true
  50726. });
  50727. Object.defineProperty(Animatable.prototype, "masterFrame", {
  50728. /**
  50729. * Gets the current frame of the first RuntimeAnimation
  50730. * Used to synchronize Animatables
  50731. */
  50732. get: function () {
  50733. if (this._runtimeAnimations.length === 0) {
  50734. return 0;
  50735. }
  50736. return this._runtimeAnimations[0].currentFrame;
  50737. },
  50738. enumerable: true,
  50739. configurable: true
  50740. });
  50741. Object.defineProperty(Animatable.prototype, "weight", {
  50742. /**
  50743. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  50744. */
  50745. get: function () {
  50746. return this._weight;
  50747. },
  50748. set: function (value) {
  50749. if (value === -1) {
  50750. this._weight = -1;
  50751. return;
  50752. }
  50753. // Else weight must be in [0, 1] range
  50754. this._weight = Math.min(Math.max(value, 0), 1.0);
  50755. },
  50756. enumerable: true,
  50757. configurable: true
  50758. });
  50759. Object.defineProperty(Animatable.prototype, "speedRatio", {
  50760. /**
  50761. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  50762. */
  50763. get: function () {
  50764. return this._speedRatio;
  50765. },
  50766. set: function (value) {
  50767. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  50768. var animation = this._runtimeAnimations[index];
  50769. animation._prepareForSpeedRatioChange(value);
  50770. }
  50771. this._speedRatio = value;
  50772. },
  50773. enumerable: true,
  50774. configurable: true
  50775. });
  50776. // Methods
  50777. /**
  50778. * Synchronize and normalize current Animatable with a source Animatable.
  50779. * This is useful when using animation weights and when animations are not of the same length
  50780. * @param root defines the root Animatable to synchronize with
  50781. * @returns the current Animatable
  50782. */
  50783. Animatable.prototype.syncWith = function (root) {
  50784. this._syncRoot = root;
  50785. if (root) {
  50786. // Make sure this animatable will animate after the root
  50787. var index = this._scene._activeAnimatables.indexOf(this);
  50788. if (index > -1) {
  50789. this._scene._activeAnimatables.splice(index, 1);
  50790. this._scene._activeAnimatables.push(this);
  50791. }
  50792. }
  50793. return this;
  50794. };
  50795. Animatable.prototype.getAnimations = function () {
  50796. return this._runtimeAnimations;
  50797. };
  50798. Animatable.prototype.appendAnimations = function (target, animations) {
  50799. for (var index = 0; index < animations.length; index++) {
  50800. var animation = animations[index];
  50801. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  50802. }
  50803. };
  50804. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  50805. var runtimeAnimations = this._runtimeAnimations;
  50806. for (var index = 0; index < runtimeAnimations.length; index++) {
  50807. if (runtimeAnimations[index].animation.targetProperty === property) {
  50808. return runtimeAnimations[index].animation;
  50809. }
  50810. }
  50811. return null;
  50812. };
  50813. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  50814. var runtimeAnimations = this._runtimeAnimations;
  50815. for (var index = 0; index < runtimeAnimations.length; index++) {
  50816. if (runtimeAnimations[index].animation.targetProperty === property) {
  50817. return runtimeAnimations[index];
  50818. }
  50819. }
  50820. return null;
  50821. };
  50822. Animatable.prototype.reset = function () {
  50823. var runtimeAnimations = this._runtimeAnimations;
  50824. for (var index = 0; index < runtimeAnimations.length; index++) {
  50825. runtimeAnimations[index].reset();
  50826. }
  50827. // Reset to original value
  50828. for (index = 0; index < runtimeAnimations.length; index++) {
  50829. var animation = runtimeAnimations[index];
  50830. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  50831. }
  50832. this._localDelayOffset = null;
  50833. this._pausedDelay = null;
  50834. };
  50835. Animatable.prototype.enableBlending = function (blendingSpeed) {
  50836. var runtimeAnimations = this._runtimeAnimations;
  50837. for (var index = 0; index < runtimeAnimations.length; index++) {
  50838. runtimeAnimations[index].animation.enableBlending = true;
  50839. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  50840. }
  50841. };
  50842. Animatable.prototype.disableBlending = function () {
  50843. var runtimeAnimations = this._runtimeAnimations;
  50844. for (var index = 0; index < runtimeAnimations.length; index++) {
  50845. runtimeAnimations[index].animation.enableBlending = false;
  50846. }
  50847. };
  50848. Animatable.prototype.goToFrame = function (frame) {
  50849. var runtimeAnimations = this._runtimeAnimations;
  50850. if (runtimeAnimations[0]) {
  50851. var fps = runtimeAnimations[0].animation.framePerSecond;
  50852. var currentFrame = runtimeAnimations[0].currentFrame;
  50853. var adjustTime = frame - currentFrame;
  50854. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  50855. if (this._localDelayOffset === null) {
  50856. this._localDelayOffset = 0;
  50857. }
  50858. this._localDelayOffset -= delay;
  50859. }
  50860. for (var index = 0; index < runtimeAnimations.length; index++) {
  50861. runtimeAnimations[index].goToFrame(frame);
  50862. }
  50863. };
  50864. Animatable.prototype.pause = function () {
  50865. if (this._paused) {
  50866. return;
  50867. }
  50868. this._paused = true;
  50869. };
  50870. Animatable.prototype.restart = function () {
  50871. this._paused = false;
  50872. };
  50873. Animatable.prototype.stop = function (animationName) {
  50874. if (animationName) {
  50875. var idx = this._scene._activeAnimatables.indexOf(this);
  50876. if (idx > -1) {
  50877. var runtimeAnimations = this._runtimeAnimations;
  50878. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  50879. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  50880. continue;
  50881. }
  50882. runtimeAnimations[index].dispose();
  50883. runtimeAnimations.splice(index, 1);
  50884. }
  50885. if (runtimeAnimations.length == 0) {
  50886. this._scene._activeAnimatables.splice(idx, 1);
  50887. if (this.onAnimationEnd) {
  50888. this.onAnimationEnd();
  50889. }
  50890. }
  50891. }
  50892. }
  50893. else {
  50894. var index = this._scene._activeAnimatables.indexOf(this);
  50895. if (index > -1) {
  50896. this._scene._activeAnimatables.splice(index, 1);
  50897. var runtimeAnimations = this._runtimeAnimations;
  50898. for (var index = 0; index < runtimeAnimations.length; index++) {
  50899. runtimeAnimations[index].dispose();
  50900. }
  50901. if (this.onAnimationEnd) {
  50902. this.onAnimationEnd();
  50903. }
  50904. }
  50905. }
  50906. };
  50907. Animatable.prototype._animate = function (delay) {
  50908. if (this._paused) {
  50909. this.animationStarted = false;
  50910. if (this._pausedDelay === null) {
  50911. this._pausedDelay = delay;
  50912. }
  50913. return true;
  50914. }
  50915. if (this._localDelayOffset === null) {
  50916. this._localDelayOffset = delay;
  50917. this._pausedDelay = null;
  50918. }
  50919. else if (this._pausedDelay !== null) {
  50920. this._localDelayOffset += delay - this._pausedDelay;
  50921. this._pausedDelay = null;
  50922. }
  50923. if (this._weight === 0) {
  50924. return true;
  50925. }
  50926. // Animating
  50927. var running = false;
  50928. var runtimeAnimations = this._runtimeAnimations;
  50929. var index;
  50930. for (index = 0; index < runtimeAnimations.length; index++) {
  50931. var animation = runtimeAnimations[index];
  50932. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  50933. running = running || isRunning;
  50934. }
  50935. this.animationStarted = running;
  50936. if (!running) {
  50937. // Remove from active animatables
  50938. index = this._scene._activeAnimatables.indexOf(this);
  50939. this._scene._activeAnimatables.splice(index, 1);
  50940. // Dispose all runtime animations
  50941. for (index = 0; index < runtimeAnimations.length; index++) {
  50942. runtimeAnimations[index].dispose();
  50943. }
  50944. }
  50945. if (!running && this.onAnimationEnd) {
  50946. this.onAnimationEnd();
  50947. this.onAnimationEnd = null;
  50948. }
  50949. return running;
  50950. };
  50951. return Animatable;
  50952. }());
  50953. BABYLON.Animatable = Animatable;
  50954. })(BABYLON || (BABYLON = {}));
  50955. //# sourceMappingURL=babylon.animatable.js.map
  50956. "use strict";
  50957. var BABYLON;
  50958. (function (BABYLON) {
  50959. var EasingFunction = /** @class */ (function () {
  50960. function EasingFunction() {
  50961. // Properties
  50962. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  50963. }
  50964. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  50965. get: function () {
  50966. return EasingFunction._EASINGMODE_EASEIN;
  50967. },
  50968. enumerable: true,
  50969. configurable: true
  50970. });
  50971. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  50972. get: function () {
  50973. return EasingFunction._EASINGMODE_EASEOUT;
  50974. },
  50975. enumerable: true,
  50976. configurable: true
  50977. });
  50978. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  50979. get: function () {
  50980. return EasingFunction._EASINGMODE_EASEINOUT;
  50981. },
  50982. enumerable: true,
  50983. configurable: true
  50984. });
  50985. EasingFunction.prototype.setEasingMode = function (easingMode) {
  50986. var n = Math.min(Math.max(easingMode, 0), 2);
  50987. this._easingMode = n;
  50988. };
  50989. EasingFunction.prototype.getEasingMode = function () {
  50990. return this._easingMode;
  50991. };
  50992. EasingFunction.prototype.easeInCore = function (gradient) {
  50993. throw new Error('You must implement this method');
  50994. };
  50995. EasingFunction.prototype.ease = function (gradient) {
  50996. switch (this._easingMode) {
  50997. case EasingFunction.EASINGMODE_EASEIN:
  50998. return this.easeInCore(gradient);
  50999. case EasingFunction.EASINGMODE_EASEOUT:
  51000. return (1 - this.easeInCore(1 - gradient));
  51001. }
  51002. if (gradient >= 0.5) {
  51003. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51004. }
  51005. return (this.easeInCore(gradient * 2) * 0.5);
  51006. };
  51007. //Statics
  51008. EasingFunction._EASINGMODE_EASEIN = 0;
  51009. EasingFunction._EASINGMODE_EASEOUT = 1;
  51010. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51011. return EasingFunction;
  51012. }());
  51013. BABYLON.EasingFunction = EasingFunction;
  51014. var CircleEase = /** @class */ (function (_super) {
  51015. __extends(CircleEase, _super);
  51016. function CircleEase() {
  51017. return _super !== null && _super.apply(this, arguments) || this;
  51018. }
  51019. CircleEase.prototype.easeInCore = function (gradient) {
  51020. gradient = Math.max(0, Math.min(1, gradient));
  51021. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51022. };
  51023. return CircleEase;
  51024. }(EasingFunction));
  51025. BABYLON.CircleEase = CircleEase;
  51026. var BackEase = /** @class */ (function (_super) {
  51027. __extends(BackEase, _super);
  51028. function BackEase(amplitude) {
  51029. if (amplitude === void 0) { amplitude = 1; }
  51030. var _this = _super.call(this) || this;
  51031. _this.amplitude = amplitude;
  51032. return _this;
  51033. }
  51034. BackEase.prototype.easeInCore = function (gradient) {
  51035. var num = Math.max(0, this.amplitude);
  51036. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51037. };
  51038. return BackEase;
  51039. }(EasingFunction));
  51040. BABYLON.BackEase = BackEase;
  51041. var BounceEase = /** @class */ (function (_super) {
  51042. __extends(BounceEase, _super);
  51043. function BounceEase(bounces, bounciness) {
  51044. if (bounces === void 0) { bounces = 3; }
  51045. if (bounciness === void 0) { bounciness = 2; }
  51046. var _this = _super.call(this) || this;
  51047. _this.bounces = bounces;
  51048. _this.bounciness = bounciness;
  51049. return _this;
  51050. }
  51051. BounceEase.prototype.easeInCore = function (gradient) {
  51052. var y = Math.max(0.0, this.bounces);
  51053. var bounciness = this.bounciness;
  51054. if (bounciness <= 1.0) {
  51055. bounciness = 1.001;
  51056. }
  51057. var num9 = Math.pow(bounciness, y);
  51058. var num5 = 1.0 - bounciness;
  51059. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51060. var num15 = gradient * num4;
  51061. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51062. var num3 = Math.floor(num65);
  51063. var num13 = num3 + 1.0;
  51064. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51065. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51066. var num7 = (num8 + num12) * 0.5;
  51067. var num6 = gradient - num7;
  51068. var num2 = num7 - num8;
  51069. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51070. };
  51071. return BounceEase;
  51072. }(EasingFunction));
  51073. BABYLON.BounceEase = BounceEase;
  51074. var CubicEase = /** @class */ (function (_super) {
  51075. __extends(CubicEase, _super);
  51076. function CubicEase() {
  51077. return _super !== null && _super.apply(this, arguments) || this;
  51078. }
  51079. CubicEase.prototype.easeInCore = function (gradient) {
  51080. return (gradient * gradient * gradient);
  51081. };
  51082. return CubicEase;
  51083. }(EasingFunction));
  51084. BABYLON.CubicEase = CubicEase;
  51085. var ElasticEase = /** @class */ (function (_super) {
  51086. __extends(ElasticEase, _super);
  51087. function ElasticEase(oscillations, springiness) {
  51088. if (oscillations === void 0) { oscillations = 3; }
  51089. if (springiness === void 0) { springiness = 3; }
  51090. var _this = _super.call(this) || this;
  51091. _this.oscillations = oscillations;
  51092. _this.springiness = springiness;
  51093. return _this;
  51094. }
  51095. ElasticEase.prototype.easeInCore = function (gradient) {
  51096. var num2;
  51097. var num3 = Math.max(0.0, this.oscillations);
  51098. var num = Math.max(0.0, this.springiness);
  51099. if (num == 0) {
  51100. num2 = gradient;
  51101. }
  51102. else {
  51103. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51104. }
  51105. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51106. };
  51107. return ElasticEase;
  51108. }(EasingFunction));
  51109. BABYLON.ElasticEase = ElasticEase;
  51110. var ExponentialEase = /** @class */ (function (_super) {
  51111. __extends(ExponentialEase, _super);
  51112. function ExponentialEase(exponent) {
  51113. if (exponent === void 0) { exponent = 2; }
  51114. var _this = _super.call(this) || this;
  51115. _this.exponent = exponent;
  51116. return _this;
  51117. }
  51118. ExponentialEase.prototype.easeInCore = function (gradient) {
  51119. if (this.exponent <= 0) {
  51120. return gradient;
  51121. }
  51122. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51123. };
  51124. return ExponentialEase;
  51125. }(EasingFunction));
  51126. BABYLON.ExponentialEase = ExponentialEase;
  51127. var PowerEase = /** @class */ (function (_super) {
  51128. __extends(PowerEase, _super);
  51129. function PowerEase(power) {
  51130. if (power === void 0) { power = 2; }
  51131. var _this = _super.call(this) || this;
  51132. _this.power = power;
  51133. return _this;
  51134. }
  51135. PowerEase.prototype.easeInCore = function (gradient) {
  51136. var y = Math.max(0.0, this.power);
  51137. return Math.pow(gradient, y);
  51138. };
  51139. return PowerEase;
  51140. }(EasingFunction));
  51141. BABYLON.PowerEase = PowerEase;
  51142. var QuadraticEase = /** @class */ (function (_super) {
  51143. __extends(QuadraticEase, _super);
  51144. function QuadraticEase() {
  51145. return _super !== null && _super.apply(this, arguments) || this;
  51146. }
  51147. QuadraticEase.prototype.easeInCore = function (gradient) {
  51148. return (gradient * gradient);
  51149. };
  51150. return QuadraticEase;
  51151. }(EasingFunction));
  51152. BABYLON.QuadraticEase = QuadraticEase;
  51153. var QuarticEase = /** @class */ (function (_super) {
  51154. __extends(QuarticEase, _super);
  51155. function QuarticEase() {
  51156. return _super !== null && _super.apply(this, arguments) || this;
  51157. }
  51158. QuarticEase.prototype.easeInCore = function (gradient) {
  51159. return (gradient * gradient * gradient * gradient);
  51160. };
  51161. return QuarticEase;
  51162. }(EasingFunction));
  51163. BABYLON.QuarticEase = QuarticEase;
  51164. var QuinticEase = /** @class */ (function (_super) {
  51165. __extends(QuinticEase, _super);
  51166. function QuinticEase() {
  51167. return _super !== null && _super.apply(this, arguments) || this;
  51168. }
  51169. QuinticEase.prototype.easeInCore = function (gradient) {
  51170. return (gradient * gradient * gradient * gradient * gradient);
  51171. };
  51172. return QuinticEase;
  51173. }(EasingFunction));
  51174. BABYLON.QuinticEase = QuinticEase;
  51175. var SineEase = /** @class */ (function (_super) {
  51176. __extends(SineEase, _super);
  51177. function SineEase() {
  51178. return _super !== null && _super.apply(this, arguments) || this;
  51179. }
  51180. SineEase.prototype.easeInCore = function (gradient) {
  51181. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51182. };
  51183. return SineEase;
  51184. }(EasingFunction));
  51185. BABYLON.SineEase = SineEase;
  51186. var BezierCurveEase = /** @class */ (function (_super) {
  51187. __extends(BezierCurveEase, _super);
  51188. function BezierCurveEase(x1, y1, x2, y2) {
  51189. if (x1 === void 0) { x1 = 0; }
  51190. if (y1 === void 0) { y1 = 0; }
  51191. if (x2 === void 0) { x2 = 1; }
  51192. if (y2 === void 0) { y2 = 1; }
  51193. var _this = _super.call(this) || this;
  51194. _this.x1 = x1;
  51195. _this.y1 = y1;
  51196. _this.x2 = x2;
  51197. _this.y2 = y2;
  51198. return _this;
  51199. }
  51200. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51201. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51202. };
  51203. return BezierCurveEase;
  51204. }(EasingFunction));
  51205. BABYLON.BezierCurveEase = BezierCurveEase;
  51206. })(BABYLON || (BABYLON = {}));
  51207. //# sourceMappingURL=babylon.easing.js.map
  51208. "use strict";
  51209. var BABYLON;
  51210. (function (BABYLON) {
  51211. /**
  51212. * A Condition applied to an Action
  51213. */
  51214. var Condition = /** @class */ (function () {
  51215. /**
  51216. * Creates a new Condition
  51217. * @param actionManager the manager of the action the condition is applied to
  51218. */
  51219. function Condition(actionManager) {
  51220. this._actionManager = actionManager;
  51221. }
  51222. /**
  51223. * Check if the current condition is valid
  51224. * @returns a boolean
  51225. */
  51226. Condition.prototype.isValid = function () {
  51227. return true;
  51228. };
  51229. /**
  51230. * Internal only
  51231. * @ignore
  51232. */
  51233. Condition.prototype._getProperty = function (propertyPath) {
  51234. return this._actionManager._getProperty(propertyPath);
  51235. };
  51236. /**
  51237. * Internal only
  51238. * @ignore
  51239. */
  51240. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51241. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51242. };
  51243. /**
  51244. * Serialize placeholder for child classes
  51245. * @returns the serialized object
  51246. */
  51247. Condition.prototype.serialize = function () {
  51248. };
  51249. /**
  51250. * Internal only
  51251. * @ignore
  51252. */
  51253. Condition.prototype._serialize = function (serializedCondition) {
  51254. return {
  51255. type: 2,
  51256. children: [],
  51257. name: serializedCondition.name,
  51258. properties: serializedCondition.properties
  51259. };
  51260. };
  51261. return Condition;
  51262. }());
  51263. BABYLON.Condition = Condition;
  51264. /**
  51265. * Defines specific conditional operators as extensions of Condition
  51266. */
  51267. var ValueCondition = /** @class */ (function (_super) {
  51268. __extends(ValueCondition, _super);
  51269. /**
  51270. * Creates a new ValueCondition
  51271. * @param actionManager manager for the action the condition applies to
  51272. * @param target for the action
  51273. * @param propertyPath path to specify the property of the target the conditional operator uses
  51274. * @param value the vale compared by the conditional operator against the current value of the property
  51275. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  51276. */
  51277. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  51278. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51279. var _this = _super.call(this, actionManager) || this;
  51280. _this.propertyPath = propertyPath;
  51281. _this.value = value;
  51282. _this.operator = operator;
  51283. _this._target = target;
  51284. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51285. _this._property = _this._getProperty(_this.propertyPath);
  51286. return _this;
  51287. }
  51288. Object.defineProperty(ValueCondition, "IsEqual", {
  51289. /**
  51290. * returns the number for IsEqual
  51291. */
  51292. get: function () {
  51293. return ValueCondition._IsEqual;
  51294. },
  51295. enumerable: true,
  51296. configurable: true
  51297. });
  51298. Object.defineProperty(ValueCondition, "IsDifferent", {
  51299. /**
  51300. * Returns the number for IsDifferent
  51301. */
  51302. get: function () {
  51303. return ValueCondition._IsDifferent;
  51304. },
  51305. enumerable: true,
  51306. configurable: true
  51307. });
  51308. Object.defineProperty(ValueCondition, "IsGreater", {
  51309. /**
  51310. * Returns the number for IsGreater
  51311. */
  51312. get: function () {
  51313. return ValueCondition._IsGreater;
  51314. },
  51315. enumerable: true,
  51316. configurable: true
  51317. });
  51318. Object.defineProperty(ValueCondition, "IsLesser", {
  51319. /**
  51320. * Returns the number for IsLesser
  51321. */
  51322. get: function () {
  51323. return ValueCondition._IsLesser;
  51324. },
  51325. enumerable: true,
  51326. configurable: true
  51327. });
  51328. /**
  51329. * Compares the given value with the property value for the specified conditional operator
  51330. * @returns the result of the comparison
  51331. */
  51332. ValueCondition.prototype.isValid = function () {
  51333. switch (this.operator) {
  51334. case ValueCondition.IsGreater:
  51335. return this._effectiveTarget[this._property] > this.value;
  51336. case ValueCondition.IsLesser:
  51337. return this._effectiveTarget[this._property] < this.value;
  51338. case ValueCondition.IsEqual:
  51339. case ValueCondition.IsDifferent:
  51340. var check;
  51341. if (this.value.equals) {
  51342. check = this.value.equals(this._effectiveTarget[this._property]);
  51343. }
  51344. else {
  51345. check = this.value === this._effectiveTarget[this._property];
  51346. }
  51347. return this.operator === ValueCondition.IsEqual ? check : !check;
  51348. }
  51349. return false;
  51350. };
  51351. /**
  51352. * Serialize the ValueCondition into a JSON compatible object
  51353. * @returns serialization object
  51354. */
  51355. ValueCondition.prototype.serialize = function () {
  51356. return this._serialize({
  51357. name: "ValueCondition",
  51358. properties: [
  51359. BABYLON.Action._GetTargetProperty(this._target),
  51360. { name: "propertyPath", value: this.propertyPath },
  51361. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51362. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51363. ]
  51364. });
  51365. };
  51366. /**
  51367. * Gets the name of the conditional operator for the ValueCondition
  51368. * @param operator the conditional operator
  51369. * @returns the name
  51370. */
  51371. ValueCondition.GetOperatorName = function (operator) {
  51372. switch (operator) {
  51373. case ValueCondition._IsEqual: return "IsEqual";
  51374. case ValueCondition._IsDifferent: return "IsDifferent";
  51375. case ValueCondition._IsGreater: return "IsGreater";
  51376. case ValueCondition._IsLesser: return "IsLesser";
  51377. default: return "";
  51378. }
  51379. };
  51380. /**
  51381. * Internal only
  51382. * @ignore
  51383. */
  51384. ValueCondition._IsEqual = 0;
  51385. /**
  51386. * Internal only
  51387. * @ignore
  51388. */
  51389. ValueCondition._IsDifferent = 1;
  51390. /**
  51391. * Internal only
  51392. * @ignore
  51393. */
  51394. ValueCondition._IsGreater = 2;
  51395. /**
  51396. * Internal only
  51397. * @ignore
  51398. */
  51399. ValueCondition._IsLesser = 3;
  51400. return ValueCondition;
  51401. }(Condition));
  51402. BABYLON.ValueCondition = ValueCondition;
  51403. /**
  51404. * Defines a predicate condition as an extension of Condition
  51405. */
  51406. var PredicateCondition = /** @class */ (function (_super) {
  51407. __extends(PredicateCondition, _super);
  51408. /**
  51409. * Creates a new {BABYLON.PredicateCondition}
  51410. * @param actionManager manager for the action the condition applies to
  51411. * @param predicate
  51412. */
  51413. function PredicateCondition(actionManager, predicate) {
  51414. var _this = _super.call(this, actionManager) || this;
  51415. _this.predicate = predicate;
  51416. return _this;
  51417. }
  51418. /**
  51419. * @returns the validity of the predicate condition
  51420. */
  51421. PredicateCondition.prototype.isValid = function () {
  51422. return this.predicate();
  51423. };
  51424. return PredicateCondition;
  51425. }(Condition));
  51426. BABYLON.PredicateCondition = PredicateCondition;
  51427. /**
  51428. * Defines a state condition as an extension of {BABYLON.Condition}
  51429. */
  51430. var StateCondition = /** @class */ (function (_super) {
  51431. __extends(StateCondition, _super);
  51432. /**
  51433. * Creates a new {BABYLON.StateCondition}
  51434. * @param actionManager manager for the action the condition applies to
  51435. * @param target of the condition
  51436. * @param value to compare with target state
  51437. */
  51438. function StateCondition(actionManager, target, value) {
  51439. var _this = _super.call(this, actionManager) || this;
  51440. _this.value = value;
  51441. _this._target = target;
  51442. return _this;
  51443. }
  51444. /**
  51445. * @returns the validity of the state
  51446. */
  51447. StateCondition.prototype.isValid = function () {
  51448. return this._target.state === this.value;
  51449. };
  51450. /**
  51451. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  51452. * @returns serialization object
  51453. */
  51454. StateCondition.prototype.serialize = function () {
  51455. return this._serialize({
  51456. name: "StateCondition",
  51457. properties: [
  51458. BABYLON.Action._GetTargetProperty(this._target),
  51459. { name: "value", value: this.value }
  51460. ]
  51461. });
  51462. };
  51463. return StateCondition;
  51464. }(Condition));
  51465. BABYLON.StateCondition = StateCondition;
  51466. })(BABYLON || (BABYLON = {}));
  51467. //# sourceMappingURL=babylon.condition.js.map
  51468. "use strict";
  51469. var BABYLON;
  51470. (function (BABYLON) {
  51471. /**
  51472. * The action to be carried out following a trigger
  51473. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51474. */
  51475. var Action = /** @class */ (function () {
  51476. /**
  51477. * Creates a new Action
  51478. * @param triggerOptions the trigger, with or without parameters, for the action
  51479. * @param condition an optional determinant of action
  51480. */
  51481. function Action(triggerOptions, condition) {
  51482. this.triggerOptions = triggerOptions;
  51483. /**
  51484. * An event triggered prior to action being executed.
  51485. */
  51486. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51487. if (triggerOptions.parameter) {
  51488. this.trigger = triggerOptions.trigger;
  51489. this._triggerParameter = triggerOptions.parameter;
  51490. }
  51491. else {
  51492. this.trigger = triggerOptions;
  51493. }
  51494. this._nextActiveAction = this;
  51495. this._condition = condition;
  51496. }
  51497. /**
  51498. * Internal only
  51499. * @ignore
  51500. */
  51501. Action.prototype._prepare = function () {
  51502. };
  51503. /**
  51504. * Gets the trigger parameters
  51505. * @returns the trigger parameters
  51506. */
  51507. Action.prototype.getTriggerParameter = function () {
  51508. return this._triggerParameter;
  51509. };
  51510. /**
  51511. * Internal only - executes current action event
  51512. * @ignore
  51513. */
  51514. Action.prototype._executeCurrent = function (evt) {
  51515. if (this._nextActiveAction._condition) {
  51516. var condition = this._nextActiveAction._condition;
  51517. var currentRenderId = this._actionManager.getScene().getRenderId();
  51518. // We cache the current evaluation for the current frame
  51519. if (condition._evaluationId === currentRenderId) {
  51520. if (!condition._currentResult) {
  51521. return;
  51522. }
  51523. }
  51524. else {
  51525. condition._evaluationId = currentRenderId;
  51526. if (!condition.isValid()) {
  51527. condition._currentResult = false;
  51528. return;
  51529. }
  51530. condition._currentResult = true;
  51531. }
  51532. }
  51533. this.onBeforeExecuteObservable.notifyObservers(this);
  51534. this._nextActiveAction.execute(evt);
  51535. this.skipToNextActiveAction();
  51536. };
  51537. /**
  51538. * Execute placeholder for child classes
  51539. * @param evt optional action event
  51540. */
  51541. Action.prototype.execute = function (evt) {
  51542. };
  51543. /**
  51544. * Skips to next active action
  51545. */
  51546. Action.prototype.skipToNextActiveAction = function () {
  51547. if (this._nextActiveAction._child) {
  51548. if (!this._nextActiveAction._child._actionManager) {
  51549. this._nextActiveAction._child._actionManager = this._actionManager;
  51550. }
  51551. this._nextActiveAction = this._nextActiveAction._child;
  51552. }
  51553. else {
  51554. this._nextActiveAction = this;
  51555. }
  51556. };
  51557. /**
  51558. * Adds action to chain of actions, may be a DoNothingAction
  51559. * @param index The index of the attribute.
  51560. * @returns The action passed in
  51561. * @see https://www.babylonjs-playground.com/#1T30HR#0
  51562. */
  51563. Action.prototype.then = function (action) {
  51564. this._child = action;
  51565. action._actionManager = this._actionManager;
  51566. action._prepare();
  51567. return action;
  51568. };
  51569. /**
  51570. * Internal only
  51571. * @ignore
  51572. */
  51573. Action.prototype._getProperty = function (propertyPath) {
  51574. return this._actionManager._getProperty(propertyPath);
  51575. };
  51576. /**
  51577. * Internal only
  51578. * @ignore
  51579. */
  51580. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  51581. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51582. };
  51583. /**
  51584. * Serialize placeholder for child classes
  51585. * @param parent of child
  51586. * @returns the serialized object
  51587. */
  51588. Action.prototype.serialize = function (parent) {
  51589. };
  51590. /**
  51591. * Internal only called by serialize
  51592. * @ignore
  51593. */
  51594. Action.prototype._serialize = function (serializedAction, parent) {
  51595. var serializationObject = {
  51596. type: 1,
  51597. children: [],
  51598. name: serializedAction.name,
  51599. properties: serializedAction.properties || []
  51600. };
  51601. // Serialize child
  51602. if (this._child) {
  51603. this._child.serialize(serializationObject);
  51604. }
  51605. // Check if "this" has a condition
  51606. if (this._condition) {
  51607. var serializedCondition = this._condition.serialize();
  51608. serializedCondition.children.push(serializationObject);
  51609. if (parent) {
  51610. parent.children.push(serializedCondition);
  51611. }
  51612. return serializedCondition;
  51613. }
  51614. if (parent) {
  51615. parent.children.push(serializationObject);
  51616. }
  51617. return serializationObject;
  51618. };
  51619. /**
  51620. * Internal only
  51621. * @ignore
  51622. */
  51623. Action._SerializeValueAsString = function (value) {
  51624. if (typeof value === "number") {
  51625. return value.toString();
  51626. }
  51627. if (typeof value === "boolean") {
  51628. return value ? "true" : "false";
  51629. }
  51630. if (value instanceof BABYLON.Vector2) {
  51631. return value.x + ", " + value.y;
  51632. }
  51633. if (value instanceof BABYLON.Vector3) {
  51634. return value.x + ", " + value.y + ", " + value.z;
  51635. }
  51636. if (value instanceof BABYLON.Color3) {
  51637. return value.r + ", " + value.g + ", " + value.b;
  51638. }
  51639. if (value instanceof BABYLON.Color4) {
  51640. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  51641. }
  51642. return value; // string
  51643. };
  51644. /**
  51645. * Internal only
  51646. * @ignore
  51647. */
  51648. Action._GetTargetProperty = function (target) {
  51649. return {
  51650. name: "target",
  51651. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  51652. : target instanceof BABYLON.Light ? "LightProperties"
  51653. : target instanceof BABYLON.Camera ? "CameraProperties"
  51654. : "SceneProperties",
  51655. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  51656. };
  51657. };
  51658. return Action;
  51659. }());
  51660. BABYLON.Action = Action;
  51661. })(BABYLON || (BABYLON = {}));
  51662. //# sourceMappingURL=babylon.action.js.map
  51663. "use strict";
  51664. var BABYLON;
  51665. (function (BABYLON) {
  51666. /**
  51667. * ActionEvent is the event being sent when an action is triggered.
  51668. */
  51669. var ActionEvent = /** @class */ (function () {
  51670. /**
  51671. * @param source The mesh or sprite that triggered the action.
  51672. * @param pointerX The X mouse cursor position at the time of the event
  51673. * @param pointerY The Y mouse cursor position at the time of the event
  51674. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  51675. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  51676. */
  51677. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  51678. this.source = source;
  51679. this.pointerX = pointerX;
  51680. this.pointerY = pointerY;
  51681. this.meshUnderPointer = meshUnderPointer;
  51682. this.sourceEvent = sourceEvent;
  51683. this.additionalData = additionalData;
  51684. }
  51685. /**
  51686. * Helper function to auto-create an ActionEvent from a source mesh.
  51687. * @param source The source mesh that triggered the event
  51688. * @param evt {Event} The original (browser) event
  51689. */
  51690. ActionEvent.CreateNew = function (source, evt, additionalData) {
  51691. var scene = source.getScene();
  51692. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51693. };
  51694. /**
  51695. * Helper function to auto-create an ActionEvent from a source mesh.
  51696. * @param source The source sprite that triggered the event
  51697. * @param scene Scene associated with the sprite
  51698. * @param evt {Event} The original (browser) event
  51699. */
  51700. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  51701. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  51702. };
  51703. /**
  51704. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  51705. * @param scene the scene where the event occurred
  51706. * @param evt {Event} The original (browser) event
  51707. */
  51708. ActionEvent.CreateNewFromScene = function (scene, evt) {
  51709. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  51710. };
  51711. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  51712. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  51713. };
  51714. return ActionEvent;
  51715. }());
  51716. BABYLON.ActionEvent = ActionEvent;
  51717. /**
  51718. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  51719. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  51720. */
  51721. var ActionManager = /** @class */ (function () {
  51722. function ActionManager(scene) {
  51723. // Members
  51724. this.actions = new Array();
  51725. this.hoverCursor = '';
  51726. this._scene = scene;
  51727. scene._actionManagers.push(this);
  51728. }
  51729. Object.defineProperty(ActionManager, "NothingTrigger", {
  51730. get: function () {
  51731. return ActionManager._NothingTrigger;
  51732. },
  51733. enumerable: true,
  51734. configurable: true
  51735. });
  51736. Object.defineProperty(ActionManager, "OnPickTrigger", {
  51737. get: function () {
  51738. return ActionManager._OnPickTrigger;
  51739. },
  51740. enumerable: true,
  51741. configurable: true
  51742. });
  51743. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  51744. get: function () {
  51745. return ActionManager._OnLeftPickTrigger;
  51746. },
  51747. enumerable: true,
  51748. configurable: true
  51749. });
  51750. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  51751. get: function () {
  51752. return ActionManager._OnRightPickTrigger;
  51753. },
  51754. enumerable: true,
  51755. configurable: true
  51756. });
  51757. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  51758. get: function () {
  51759. return ActionManager._OnCenterPickTrigger;
  51760. },
  51761. enumerable: true,
  51762. configurable: true
  51763. });
  51764. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  51765. get: function () {
  51766. return ActionManager._OnPickDownTrigger;
  51767. },
  51768. enumerable: true,
  51769. configurable: true
  51770. });
  51771. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  51772. get: function () {
  51773. return ActionManager._OnDoublePickTrigger;
  51774. },
  51775. enumerable: true,
  51776. configurable: true
  51777. });
  51778. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  51779. get: function () {
  51780. return ActionManager._OnPickUpTrigger;
  51781. },
  51782. enumerable: true,
  51783. configurable: true
  51784. });
  51785. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  51786. /// This trigger will only be raised if you also declared a OnPickDown
  51787. get: function () {
  51788. return ActionManager._OnPickOutTrigger;
  51789. },
  51790. enumerable: true,
  51791. configurable: true
  51792. });
  51793. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  51794. get: function () {
  51795. return ActionManager._OnLongPressTrigger;
  51796. },
  51797. enumerable: true,
  51798. configurable: true
  51799. });
  51800. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  51801. get: function () {
  51802. return ActionManager._OnPointerOverTrigger;
  51803. },
  51804. enumerable: true,
  51805. configurable: true
  51806. });
  51807. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  51808. get: function () {
  51809. return ActionManager._OnPointerOutTrigger;
  51810. },
  51811. enumerable: true,
  51812. configurable: true
  51813. });
  51814. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  51815. get: function () {
  51816. return ActionManager._OnEveryFrameTrigger;
  51817. },
  51818. enumerable: true,
  51819. configurable: true
  51820. });
  51821. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  51822. get: function () {
  51823. return ActionManager._OnIntersectionEnterTrigger;
  51824. },
  51825. enumerable: true,
  51826. configurable: true
  51827. });
  51828. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  51829. get: function () {
  51830. return ActionManager._OnIntersectionExitTrigger;
  51831. },
  51832. enumerable: true,
  51833. configurable: true
  51834. });
  51835. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  51836. get: function () {
  51837. return ActionManager._OnKeyDownTrigger;
  51838. },
  51839. enumerable: true,
  51840. configurable: true
  51841. });
  51842. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  51843. get: function () {
  51844. return ActionManager._OnKeyUpTrigger;
  51845. },
  51846. enumerable: true,
  51847. configurable: true
  51848. });
  51849. // Methods
  51850. ActionManager.prototype.dispose = function () {
  51851. var index = this._scene._actionManagers.indexOf(this);
  51852. for (var i = 0; i < this.actions.length; i++) {
  51853. var action = this.actions[i];
  51854. ActionManager.Triggers[action.trigger]--;
  51855. if (ActionManager.Triggers[action.trigger] === 0) {
  51856. delete ActionManager.Triggers[action.trigger];
  51857. }
  51858. }
  51859. if (index > -1) {
  51860. this._scene._actionManagers.splice(index, 1);
  51861. }
  51862. };
  51863. ActionManager.prototype.getScene = function () {
  51864. return this._scene;
  51865. };
  51866. /**
  51867. * Does this action manager handles actions of any of the given triggers
  51868. * @param {number[]} triggers - the triggers to be tested
  51869. * @return {boolean} whether one (or more) of the triggers is handeled
  51870. */
  51871. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  51872. for (var index = 0; index < this.actions.length; index++) {
  51873. var action = this.actions[index];
  51874. if (triggers.indexOf(action.trigger) > -1) {
  51875. return true;
  51876. }
  51877. }
  51878. return false;
  51879. };
  51880. /**
  51881. * Does this action manager handles actions of a given trigger
  51882. * @param trigger defines the trigger to be tested
  51883. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  51884. * @return whether the trigger is handled
  51885. */
  51886. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  51887. for (var index = 0; index < this.actions.length; index++) {
  51888. var action = this.actions[index];
  51889. if (action.trigger === trigger) {
  51890. if (parameterPredicate) {
  51891. if (parameterPredicate(action.getTriggerParameter())) {
  51892. return true;
  51893. }
  51894. }
  51895. else {
  51896. return true;
  51897. }
  51898. }
  51899. }
  51900. return false;
  51901. };
  51902. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  51903. /**
  51904. * Does this action manager has pointer triggers
  51905. * @return {boolean} whether or not it has pointer triggers
  51906. */
  51907. get: function () {
  51908. for (var index = 0; index < this.actions.length; index++) {
  51909. var action = this.actions[index];
  51910. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  51911. return true;
  51912. }
  51913. }
  51914. return false;
  51915. },
  51916. enumerable: true,
  51917. configurable: true
  51918. });
  51919. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  51920. /**
  51921. * Does this action manager has pick triggers
  51922. * @return {boolean} whether or not it has pick triggers
  51923. */
  51924. get: function () {
  51925. for (var index = 0; index < this.actions.length; index++) {
  51926. var action = this.actions[index];
  51927. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  51928. return true;
  51929. }
  51930. }
  51931. return false;
  51932. },
  51933. enumerable: true,
  51934. configurable: true
  51935. });
  51936. Object.defineProperty(ActionManager, "HasTriggers", {
  51937. /**
  51938. * Does exist one action manager with at least one trigger
  51939. * @return {boolean} whether or not it exists one action manager with one trigger
  51940. **/
  51941. get: function () {
  51942. for (var t in ActionManager.Triggers) {
  51943. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51944. return true;
  51945. }
  51946. }
  51947. return false;
  51948. },
  51949. enumerable: true,
  51950. configurable: true
  51951. });
  51952. Object.defineProperty(ActionManager, "HasPickTriggers", {
  51953. /**
  51954. * Does exist one action manager with at least one pick trigger
  51955. * @return {boolean} whether or not it exists one action manager with one pick trigger
  51956. **/
  51957. get: function () {
  51958. for (var t in ActionManager.Triggers) {
  51959. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51960. var t_int = parseInt(t);
  51961. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  51962. return true;
  51963. }
  51964. }
  51965. }
  51966. return false;
  51967. },
  51968. enumerable: true,
  51969. configurable: true
  51970. });
  51971. /**
  51972. * Does exist one action manager that handles actions of a given trigger
  51973. * @param {number} trigger - the trigger to be tested
  51974. * @return {boolean} whether the trigger is handeled by at least one action manager
  51975. **/
  51976. ActionManager.HasSpecificTrigger = function (trigger) {
  51977. for (var t in ActionManager.Triggers) {
  51978. if (ActionManager.Triggers.hasOwnProperty(t)) {
  51979. var t_int = parseInt(t);
  51980. if (t_int === trigger) {
  51981. return true;
  51982. }
  51983. }
  51984. }
  51985. return false;
  51986. };
  51987. /**
  51988. * Registers an action to this action manager
  51989. * @param {BABYLON.Action} action - the action to be registered
  51990. * @return {BABYLON.Action} the action amended (prepared) after registration
  51991. */
  51992. ActionManager.prototype.registerAction = function (action) {
  51993. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  51994. if (this.getScene().actionManager !== this) {
  51995. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  51996. return null;
  51997. }
  51998. }
  51999. this.actions.push(action);
  52000. if (ActionManager.Triggers[action.trigger]) {
  52001. ActionManager.Triggers[action.trigger]++;
  52002. }
  52003. else {
  52004. ActionManager.Triggers[action.trigger] = 1;
  52005. }
  52006. action._actionManager = this;
  52007. action._prepare();
  52008. return action;
  52009. };
  52010. /**
  52011. * Unregisters an action to this action manager
  52012. * @param action The action to be unregistered
  52013. * @return whether the action has been unregistered
  52014. */
  52015. ActionManager.prototype.unregisterAction = function (action) {
  52016. var index = this.actions.indexOf(action);
  52017. if (index !== -1) {
  52018. this.actions.splice(index, 1);
  52019. ActionManager.Triggers[action.trigger] -= 1;
  52020. if (ActionManager.Triggers[action.trigger] === 0) {
  52021. delete ActionManager.Triggers[action.trigger];
  52022. }
  52023. delete action._actionManager;
  52024. return true;
  52025. }
  52026. return false;
  52027. };
  52028. /**
  52029. * Process a specific trigger
  52030. * @param {number} trigger - the trigger to process
  52031. * @param evt {BABYLON.ActionEvent} the event details to be processed
  52032. */
  52033. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52034. for (var index = 0; index < this.actions.length; index++) {
  52035. var action = this.actions[index];
  52036. if (action.trigger === trigger) {
  52037. if (evt) {
  52038. if (trigger === ActionManager.OnKeyUpTrigger
  52039. || trigger === ActionManager.OnKeyDownTrigger) {
  52040. var parameter = action.getTriggerParameter();
  52041. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52042. if (!parameter.toLowerCase) {
  52043. continue;
  52044. }
  52045. var lowerCase = parameter.toLowerCase();
  52046. if (lowerCase !== evt.sourceEvent.key) {
  52047. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52048. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52049. if (actualkey !== lowerCase) {
  52050. continue;
  52051. }
  52052. }
  52053. }
  52054. }
  52055. }
  52056. action._executeCurrent(evt);
  52057. }
  52058. }
  52059. };
  52060. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52061. var properties = propertyPath.split(".");
  52062. for (var index = 0; index < properties.length - 1; index++) {
  52063. target = target[properties[index]];
  52064. }
  52065. return target;
  52066. };
  52067. ActionManager.prototype._getProperty = function (propertyPath) {
  52068. var properties = propertyPath.split(".");
  52069. return properties[properties.length - 1];
  52070. };
  52071. ActionManager.prototype.serialize = function (name) {
  52072. var root = {
  52073. children: new Array(),
  52074. name: name,
  52075. type: 3,
  52076. properties: new Array() // Empty for root but required
  52077. };
  52078. for (var i = 0; i < this.actions.length; i++) {
  52079. var triggerObject = {
  52080. type: 0,
  52081. children: new Array(),
  52082. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52083. properties: new Array()
  52084. };
  52085. var triggerOptions = this.actions[i].triggerOptions;
  52086. if (triggerOptions && typeof triggerOptions !== "number") {
  52087. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52088. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52089. }
  52090. else {
  52091. var parameter = {};
  52092. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52093. if (triggerOptions.parameter.mesh) {
  52094. parameter._meshId = triggerOptions.parameter.mesh.id;
  52095. }
  52096. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52097. }
  52098. }
  52099. // Serialize child action, recursively
  52100. this.actions[i].serialize(triggerObject);
  52101. // Add serialized trigger
  52102. root.children.push(triggerObject);
  52103. }
  52104. return root;
  52105. };
  52106. ActionManager.Parse = function (parsedActions, object, scene) {
  52107. var actionManager = new ActionManager(scene);
  52108. if (object === null)
  52109. scene.actionManager = actionManager;
  52110. else
  52111. object.actionManager = actionManager;
  52112. // instanciate a new object
  52113. var instanciate = function (name, params) {
  52114. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52115. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52116. newInstance.constructor.apply(newInstance, params);
  52117. return newInstance;
  52118. };
  52119. var parseParameter = function (name, value, target, propertyPath) {
  52120. if (propertyPath === null) {
  52121. // String, boolean or float
  52122. var floatValue = parseFloat(value);
  52123. if (value === "true" || value === "false")
  52124. return value === "true";
  52125. else
  52126. return isNaN(floatValue) ? value : floatValue;
  52127. }
  52128. var effectiveTarget = propertyPath.split(".");
  52129. var values = value.split(",");
  52130. // Get effective Target
  52131. for (var i = 0; i < effectiveTarget.length; i++) {
  52132. target = target[effectiveTarget[i]];
  52133. }
  52134. // Return appropriate value with its type
  52135. if (typeof (target) === "boolean")
  52136. return values[0] === "true";
  52137. if (typeof (target) === "string")
  52138. return values[0];
  52139. // Parameters with multiple values such as Vector3 etc.
  52140. var split = new Array();
  52141. for (var i = 0; i < values.length; i++)
  52142. split.push(parseFloat(values[i]));
  52143. if (target instanceof BABYLON.Vector3)
  52144. return BABYLON.Vector3.FromArray(split);
  52145. if (target instanceof BABYLON.Vector4)
  52146. return BABYLON.Vector4.FromArray(split);
  52147. if (target instanceof BABYLON.Color3)
  52148. return BABYLON.Color3.FromArray(split);
  52149. if (target instanceof BABYLON.Color4)
  52150. return BABYLON.Color4.FromArray(split);
  52151. return parseFloat(values[0]);
  52152. };
  52153. // traverse graph per trigger
  52154. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52155. if (combineArray === void 0) { combineArray = null; }
  52156. if (parsedAction.detached)
  52157. return;
  52158. var parameters = new Array();
  52159. var target = null;
  52160. var propertyPath = null;
  52161. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52162. // Parameters
  52163. if (parsedAction.type === 2)
  52164. parameters.push(actionManager);
  52165. else
  52166. parameters.push(trigger);
  52167. if (combine) {
  52168. var actions = new Array();
  52169. for (var j = 0; j < parsedAction.combine.length; j++) {
  52170. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52171. }
  52172. parameters.push(actions);
  52173. }
  52174. else {
  52175. for (var i = 0; i < parsedAction.properties.length; i++) {
  52176. var value = parsedAction.properties[i].value;
  52177. var name = parsedAction.properties[i].name;
  52178. var targetType = parsedAction.properties[i].targetType;
  52179. if (name === "target")
  52180. if (targetType !== null && targetType === "SceneProperties")
  52181. value = target = scene;
  52182. else
  52183. value = target = scene.getNodeByName(value);
  52184. else if (name === "parent")
  52185. value = scene.getNodeByName(value);
  52186. else if (name === "sound")
  52187. value = scene.getSoundByName(value);
  52188. else if (name !== "propertyPath") {
  52189. if (parsedAction.type === 2 && name === "operator")
  52190. value = BABYLON.ValueCondition[value];
  52191. else
  52192. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52193. }
  52194. else {
  52195. propertyPath = value;
  52196. }
  52197. parameters.push(value);
  52198. }
  52199. }
  52200. if (combineArray === null) {
  52201. parameters.push(condition);
  52202. }
  52203. else {
  52204. parameters.push(null);
  52205. }
  52206. // If interpolate value action
  52207. if (parsedAction.name === "InterpolateValueAction") {
  52208. var param = parameters[parameters.length - 2];
  52209. parameters[parameters.length - 1] = param;
  52210. parameters[parameters.length - 2] = condition;
  52211. }
  52212. // Action or condition(s) and not CombineAction
  52213. var newAction = instanciate(parsedAction.name, parameters);
  52214. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52215. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52216. if (action)
  52217. action.then(nothing);
  52218. else
  52219. actionManager.registerAction(nothing);
  52220. action = nothing;
  52221. }
  52222. if (combineArray === null) {
  52223. if (newAction instanceof BABYLON.Condition) {
  52224. condition = newAction;
  52225. newAction = action;
  52226. }
  52227. else {
  52228. condition = null;
  52229. if (action)
  52230. action.then(newAction);
  52231. else
  52232. actionManager.registerAction(newAction);
  52233. }
  52234. }
  52235. else {
  52236. combineArray.push(newAction);
  52237. }
  52238. for (var i = 0; i < parsedAction.children.length; i++)
  52239. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52240. };
  52241. // triggers
  52242. for (var i = 0; i < parsedActions.children.length; i++) {
  52243. var triggerParams;
  52244. var trigger = parsedActions.children[i];
  52245. if (trigger.properties.length > 0) {
  52246. var param = trigger.properties[0].value;
  52247. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52248. if (value._meshId) {
  52249. value.mesh = scene.getMeshByID(value._meshId);
  52250. }
  52251. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52252. }
  52253. else
  52254. triggerParams = ActionManager[trigger.name];
  52255. for (var j = 0; j < trigger.children.length; j++) {
  52256. if (!trigger.detached)
  52257. traverse(trigger.children[j], triggerParams, null, null);
  52258. }
  52259. }
  52260. };
  52261. ActionManager.GetTriggerName = function (trigger) {
  52262. switch (trigger) {
  52263. case 0: return "NothingTrigger";
  52264. case 1: return "OnPickTrigger";
  52265. case 2: return "OnLeftPickTrigger";
  52266. case 3: return "OnRightPickTrigger";
  52267. case 4: return "OnCenterPickTrigger";
  52268. case 5: return "OnPickDownTrigger";
  52269. case 6: return "OnPickUpTrigger";
  52270. case 7: return "OnLongPressTrigger";
  52271. case 8: return "OnPointerOverTrigger";
  52272. case 9: return "OnPointerOutTrigger";
  52273. case 10: return "OnEveryFrameTrigger";
  52274. case 11: return "OnIntersectionEnterTrigger";
  52275. case 12: return "OnIntersectionExitTrigger";
  52276. case 13: return "OnKeyDownTrigger";
  52277. case 14: return "OnKeyUpTrigger";
  52278. case 15: return "OnPickOutTrigger";
  52279. default: return "";
  52280. }
  52281. };
  52282. // Statics
  52283. ActionManager._NothingTrigger = 0;
  52284. ActionManager._OnPickTrigger = 1;
  52285. ActionManager._OnLeftPickTrigger = 2;
  52286. ActionManager._OnRightPickTrigger = 3;
  52287. ActionManager._OnCenterPickTrigger = 4;
  52288. ActionManager._OnPickDownTrigger = 5;
  52289. ActionManager._OnDoublePickTrigger = 6;
  52290. ActionManager._OnPickUpTrigger = 7;
  52291. ActionManager._OnLongPressTrigger = 8;
  52292. ActionManager._OnPointerOverTrigger = 9;
  52293. ActionManager._OnPointerOutTrigger = 10;
  52294. ActionManager._OnEveryFrameTrigger = 11;
  52295. ActionManager._OnIntersectionEnterTrigger = 12;
  52296. ActionManager._OnIntersectionExitTrigger = 13;
  52297. ActionManager._OnKeyDownTrigger = 14;
  52298. ActionManager._OnKeyUpTrigger = 15;
  52299. ActionManager._OnPickOutTrigger = 16;
  52300. ActionManager.Triggers = {};
  52301. return ActionManager;
  52302. }());
  52303. BABYLON.ActionManager = ActionManager;
  52304. })(BABYLON || (BABYLON = {}));
  52305. //# sourceMappingURL=babylon.actionManager.js.map
  52306. "use strict";
  52307. var BABYLON;
  52308. (function (BABYLON) {
  52309. var InterpolateValueAction = /** @class */ (function (_super) {
  52310. __extends(InterpolateValueAction, _super);
  52311. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52312. if (duration === void 0) { duration = 1000; }
  52313. var _this = _super.call(this, triggerOptions, condition) || this;
  52314. _this.propertyPath = propertyPath;
  52315. _this.value = value;
  52316. _this.duration = duration;
  52317. _this.stopOtherAnimations = stopOtherAnimations;
  52318. _this.onInterpolationDone = onInterpolationDone;
  52319. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52320. _this._target = _this._effectiveTarget = target;
  52321. return _this;
  52322. }
  52323. InterpolateValueAction.prototype._prepare = function () {
  52324. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52325. this._property = this._getProperty(this.propertyPath);
  52326. };
  52327. InterpolateValueAction.prototype.execute = function () {
  52328. var _this = this;
  52329. var scene = this._actionManager.getScene();
  52330. var keys = [
  52331. {
  52332. frame: 0,
  52333. value: this._effectiveTarget[this._property]
  52334. }, {
  52335. frame: 100,
  52336. value: this.value
  52337. }
  52338. ];
  52339. var dataType;
  52340. if (typeof this.value === "number") {
  52341. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52342. }
  52343. else if (this.value instanceof BABYLON.Color3) {
  52344. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52345. }
  52346. else if (this.value instanceof BABYLON.Vector3) {
  52347. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52348. }
  52349. else if (this.value instanceof BABYLON.Matrix) {
  52350. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52351. }
  52352. else if (this.value instanceof BABYLON.Quaternion) {
  52353. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52354. }
  52355. else {
  52356. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52357. return;
  52358. }
  52359. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52360. animation.setKeys(keys);
  52361. if (this.stopOtherAnimations) {
  52362. scene.stopAnimation(this._effectiveTarget);
  52363. }
  52364. var wrapper = function () {
  52365. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52366. if (_this.onInterpolationDone) {
  52367. _this.onInterpolationDone();
  52368. }
  52369. };
  52370. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52371. };
  52372. InterpolateValueAction.prototype.serialize = function (parent) {
  52373. return _super.prototype._serialize.call(this, {
  52374. name: "InterpolateValueAction",
  52375. properties: [
  52376. BABYLON.Action._GetTargetProperty(this._target),
  52377. { name: "propertyPath", value: this.propertyPath },
  52378. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52379. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  52380. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  52381. ]
  52382. }, parent);
  52383. };
  52384. return InterpolateValueAction;
  52385. }(BABYLON.Action));
  52386. BABYLON.InterpolateValueAction = InterpolateValueAction;
  52387. })(BABYLON || (BABYLON = {}));
  52388. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  52389. "use strict";
  52390. var BABYLON;
  52391. (function (BABYLON) {
  52392. var SwitchBooleanAction = /** @class */ (function (_super) {
  52393. __extends(SwitchBooleanAction, _super);
  52394. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  52395. var _this = _super.call(this, triggerOptions, condition) || this;
  52396. _this.propertyPath = propertyPath;
  52397. _this._target = _this._effectiveTarget = target;
  52398. return _this;
  52399. }
  52400. SwitchBooleanAction.prototype._prepare = function () {
  52401. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52402. this._property = this._getProperty(this.propertyPath);
  52403. };
  52404. SwitchBooleanAction.prototype.execute = function () {
  52405. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  52406. };
  52407. SwitchBooleanAction.prototype.serialize = function (parent) {
  52408. return _super.prototype._serialize.call(this, {
  52409. name: "SwitchBooleanAction",
  52410. properties: [
  52411. BABYLON.Action._GetTargetProperty(this._target),
  52412. { name: "propertyPath", value: this.propertyPath }
  52413. ]
  52414. }, parent);
  52415. };
  52416. return SwitchBooleanAction;
  52417. }(BABYLON.Action));
  52418. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  52419. var SetStateAction = /** @class */ (function (_super) {
  52420. __extends(SetStateAction, _super);
  52421. function SetStateAction(triggerOptions, target, value, condition) {
  52422. var _this = _super.call(this, triggerOptions, condition) || this;
  52423. _this.value = value;
  52424. _this._target = target;
  52425. return _this;
  52426. }
  52427. SetStateAction.prototype.execute = function () {
  52428. this._target.state = this.value;
  52429. };
  52430. SetStateAction.prototype.serialize = function (parent) {
  52431. return _super.prototype._serialize.call(this, {
  52432. name: "SetStateAction",
  52433. properties: [
  52434. BABYLON.Action._GetTargetProperty(this._target),
  52435. { name: "value", value: this.value }
  52436. ]
  52437. }, parent);
  52438. };
  52439. return SetStateAction;
  52440. }(BABYLON.Action));
  52441. BABYLON.SetStateAction = SetStateAction;
  52442. var SetValueAction = /** @class */ (function (_super) {
  52443. __extends(SetValueAction, _super);
  52444. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  52445. var _this = _super.call(this, triggerOptions, condition) || this;
  52446. _this.propertyPath = propertyPath;
  52447. _this.value = value;
  52448. _this._target = _this._effectiveTarget = target;
  52449. return _this;
  52450. }
  52451. SetValueAction.prototype._prepare = function () {
  52452. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52453. this._property = this._getProperty(this.propertyPath);
  52454. };
  52455. SetValueAction.prototype.execute = function () {
  52456. this._effectiveTarget[this._property] = this.value;
  52457. if (this._target.markAsDirty) {
  52458. this._target.markAsDirty(this._property);
  52459. }
  52460. };
  52461. SetValueAction.prototype.serialize = function (parent) {
  52462. return _super.prototype._serialize.call(this, {
  52463. name: "SetValueAction",
  52464. properties: [
  52465. BABYLON.Action._GetTargetProperty(this._target),
  52466. { name: "propertyPath", value: this.propertyPath },
  52467. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52468. ]
  52469. }, parent);
  52470. };
  52471. return SetValueAction;
  52472. }(BABYLON.Action));
  52473. BABYLON.SetValueAction = SetValueAction;
  52474. var IncrementValueAction = /** @class */ (function (_super) {
  52475. __extends(IncrementValueAction, _super);
  52476. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  52477. var _this = _super.call(this, triggerOptions, condition) || this;
  52478. _this.propertyPath = propertyPath;
  52479. _this.value = value;
  52480. _this._target = _this._effectiveTarget = target;
  52481. return _this;
  52482. }
  52483. IncrementValueAction.prototype._prepare = function () {
  52484. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52485. this._property = this._getProperty(this.propertyPath);
  52486. if (typeof this._effectiveTarget[this._property] !== "number") {
  52487. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  52488. }
  52489. };
  52490. IncrementValueAction.prototype.execute = function () {
  52491. this._effectiveTarget[this._property] += this.value;
  52492. if (this._target.markAsDirty) {
  52493. this._target.markAsDirty(this._property);
  52494. }
  52495. };
  52496. IncrementValueAction.prototype.serialize = function (parent) {
  52497. return _super.prototype._serialize.call(this, {
  52498. name: "IncrementValueAction",
  52499. properties: [
  52500. BABYLON.Action._GetTargetProperty(this._target),
  52501. { name: "propertyPath", value: this.propertyPath },
  52502. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  52503. ]
  52504. }, parent);
  52505. };
  52506. return IncrementValueAction;
  52507. }(BABYLON.Action));
  52508. BABYLON.IncrementValueAction = IncrementValueAction;
  52509. var PlayAnimationAction = /** @class */ (function (_super) {
  52510. __extends(PlayAnimationAction, _super);
  52511. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  52512. var _this = _super.call(this, triggerOptions, condition) || this;
  52513. _this.from = from;
  52514. _this.to = to;
  52515. _this.loop = loop;
  52516. _this._target = target;
  52517. return _this;
  52518. }
  52519. PlayAnimationAction.prototype._prepare = function () {
  52520. };
  52521. PlayAnimationAction.prototype.execute = function () {
  52522. var scene = this._actionManager.getScene();
  52523. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  52524. };
  52525. PlayAnimationAction.prototype.serialize = function (parent) {
  52526. return _super.prototype._serialize.call(this, {
  52527. name: "PlayAnimationAction",
  52528. properties: [
  52529. BABYLON.Action._GetTargetProperty(this._target),
  52530. { name: "from", value: String(this.from) },
  52531. { name: "to", value: String(this.to) },
  52532. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  52533. ]
  52534. }, parent);
  52535. };
  52536. return PlayAnimationAction;
  52537. }(BABYLON.Action));
  52538. BABYLON.PlayAnimationAction = PlayAnimationAction;
  52539. var StopAnimationAction = /** @class */ (function (_super) {
  52540. __extends(StopAnimationAction, _super);
  52541. function StopAnimationAction(triggerOptions, target, condition) {
  52542. var _this = _super.call(this, triggerOptions, condition) || this;
  52543. _this._target = target;
  52544. return _this;
  52545. }
  52546. StopAnimationAction.prototype._prepare = function () {
  52547. };
  52548. StopAnimationAction.prototype.execute = function () {
  52549. var scene = this._actionManager.getScene();
  52550. scene.stopAnimation(this._target);
  52551. };
  52552. StopAnimationAction.prototype.serialize = function (parent) {
  52553. return _super.prototype._serialize.call(this, {
  52554. name: "StopAnimationAction",
  52555. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  52556. }, parent);
  52557. };
  52558. return StopAnimationAction;
  52559. }(BABYLON.Action));
  52560. BABYLON.StopAnimationAction = StopAnimationAction;
  52561. var DoNothingAction = /** @class */ (function (_super) {
  52562. __extends(DoNothingAction, _super);
  52563. function DoNothingAction(triggerOptions, condition) {
  52564. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  52565. return _super.call(this, triggerOptions, condition) || this;
  52566. }
  52567. DoNothingAction.prototype.execute = function () {
  52568. };
  52569. DoNothingAction.prototype.serialize = function (parent) {
  52570. return _super.prototype._serialize.call(this, {
  52571. name: "DoNothingAction",
  52572. properties: []
  52573. }, parent);
  52574. };
  52575. return DoNothingAction;
  52576. }(BABYLON.Action));
  52577. BABYLON.DoNothingAction = DoNothingAction;
  52578. var CombineAction = /** @class */ (function (_super) {
  52579. __extends(CombineAction, _super);
  52580. function CombineAction(triggerOptions, children, condition) {
  52581. var _this = _super.call(this, triggerOptions, condition) || this;
  52582. _this.children = children;
  52583. return _this;
  52584. }
  52585. CombineAction.prototype._prepare = function () {
  52586. for (var index = 0; index < this.children.length; index++) {
  52587. this.children[index]._actionManager = this._actionManager;
  52588. this.children[index]._prepare();
  52589. }
  52590. };
  52591. CombineAction.prototype.execute = function (evt) {
  52592. for (var index = 0; index < this.children.length; index++) {
  52593. this.children[index].execute(evt);
  52594. }
  52595. };
  52596. CombineAction.prototype.serialize = function (parent) {
  52597. var serializationObject = _super.prototype._serialize.call(this, {
  52598. name: "CombineAction",
  52599. properties: [],
  52600. combine: []
  52601. }, parent);
  52602. for (var i = 0; i < this.children.length; i++) {
  52603. serializationObject.combine.push(this.children[i].serialize(null));
  52604. }
  52605. return serializationObject;
  52606. };
  52607. return CombineAction;
  52608. }(BABYLON.Action));
  52609. BABYLON.CombineAction = CombineAction;
  52610. var ExecuteCodeAction = /** @class */ (function (_super) {
  52611. __extends(ExecuteCodeAction, _super);
  52612. function ExecuteCodeAction(triggerOptions, func, condition) {
  52613. var _this = _super.call(this, triggerOptions, condition) || this;
  52614. _this.func = func;
  52615. return _this;
  52616. }
  52617. ExecuteCodeAction.prototype.execute = function (evt) {
  52618. this.func(evt);
  52619. };
  52620. return ExecuteCodeAction;
  52621. }(BABYLON.Action));
  52622. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  52623. var SetParentAction = /** @class */ (function (_super) {
  52624. __extends(SetParentAction, _super);
  52625. function SetParentAction(triggerOptions, target, parent, condition) {
  52626. var _this = _super.call(this, triggerOptions, condition) || this;
  52627. _this._target = target;
  52628. _this._parent = parent;
  52629. return _this;
  52630. }
  52631. SetParentAction.prototype._prepare = function () {
  52632. };
  52633. SetParentAction.prototype.execute = function () {
  52634. if (this._target.parent === this._parent) {
  52635. return;
  52636. }
  52637. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  52638. invertParentWorldMatrix.invert();
  52639. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  52640. this._target.parent = this._parent;
  52641. };
  52642. SetParentAction.prototype.serialize = function (parent) {
  52643. return _super.prototype._serialize.call(this, {
  52644. name: "SetParentAction",
  52645. properties: [
  52646. BABYLON.Action._GetTargetProperty(this._target),
  52647. BABYLON.Action._GetTargetProperty(this._parent),
  52648. ]
  52649. }, parent);
  52650. };
  52651. return SetParentAction;
  52652. }(BABYLON.Action));
  52653. BABYLON.SetParentAction = SetParentAction;
  52654. var PlaySoundAction = /** @class */ (function (_super) {
  52655. __extends(PlaySoundAction, _super);
  52656. function PlaySoundAction(triggerOptions, sound, condition) {
  52657. var _this = _super.call(this, triggerOptions, condition) || this;
  52658. _this._sound = sound;
  52659. return _this;
  52660. }
  52661. PlaySoundAction.prototype._prepare = function () {
  52662. };
  52663. PlaySoundAction.prototype.execute = function () {
  52664. if (this._sound !== undefined)
  52665. this._sound.play();
  52666. };
  52667. PlaySoundAction.prototype.serialize = function (parent) {
  52668. return _super.prototype._serialize.call(this, {
  52669. name: "PlaySoundAction",
  52670. properties: [{ name: "sound", value: this._sound.name }]
  52671. }, parent);
  52672. };
  52673. return PlaySoundAction;
  52674. }(BABYLON.Action));
  52675. BABYLON.PlaySoundAction = PlaySoundAction;
  52676. var StopSoundAction = /** @class */ (function (_super) {
  52677. __extends(StopSoundAction, _super);
  52678. function StopSoundAction(triggerOptions, sound, condition) {
  52679. var _this = _super.call(this, triggerOptions, condition) || this;
  52680. _this._sound = sound;
  52681. return _this;
  52682. }
  52683. StopSoundAction.prototype._prepare = function () {
  52684. };
  52685. StopSoundAction.prototype.execute = function () {
  52686. if (this._sound !== undefined)
  52687. this._sound.stop();
  52688. };
  52689. StopSoundAction.prototype.serialize = function (parent) {
  52690. return _super.prototype._serialize.call(this, {
  52691. name: "StopSoundAction",
  52692. properties: [{ name: "sound", value: this._sound.name }]
  52693. }, parent);
  52694. };
  52695. return StopSoundAction;
  52696. }(BABYLON.Action));
  52697. BABYLON.StopSoundAction = StopSoundAction;
  52698. })(BABYLON || (BABYLON = {}));
  52699. //# sourceMappingURL=babylon.directActions.js.map
  52700. "use strict";
  52701. var BABYLON;
  52702. (function (BABYLON) {
  52703. var SpriteManager = /** @class */ (function () {
  52704. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  52705. if (epsilon === void 0) { epsilon = 0.01; }
  52706. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52707. this.name = name;
  52708. this.sprites = new Array();
  52709. this.renderingGroupId = 0;
  52710. this.layerMask = 0x0FFFFFFF;
  52711. this.fogEnabled = true;
  52712. this.isPickable = false;
  52713. /**
  52714. * An event triggered when the manager is disposed.
  52715. */
  52716. this.onDisposeObservable = new BABYLON.Observable();
  52717. this._vertexBuffers = {};
  52718. this._capacity = capacity;
  52719. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  52720. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52721. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52722. if (cellSize.width && cellSize.height) {
  52723. this.cellWidth = cellSize.width;
  52724. this.cellHeight = cellSize.height;
  52725. }
  52726. else if (cellSize !== undefined) {
  52727. this.cellWidth = cellSize;
  52728. this.cellHeight = cellSize;
  52729. }
  52730. else {
  52731. return;
  52732. }
  52733. this._epsilon = epsilon;
  52734. this._scene = scene;
  52735. this._scene.spriteManagers.push(this);
  52736. var indices = [];
  52737. var index = 0;
  52738. for (var count = 0; count < capacity; count++) {
  52739. indices.push(index);
  52740. indices.push(index + 1);
  52741. indices.push(index + 2);
  52742. indices.push(index);
  52743. indices.push(index + 2);
  52744. indices.push(index + 3);
  52745. index += 4;
  52746. }
  52747. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  52748. // VBO
  52749. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  52750. this._vertexData = new Float32Array(capacity * 16 * 4);
  52751. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  52752. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  52753. var options = this._buffer.createVertexBuffer("options", 4, 4);
  52754. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  52755. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  52756. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  52757. this._vertexBuffers["options"] = options;
  52758. this._vertexBuffers["cellInfo"] = cellInfo;
  52759. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  52760. // Effects
  52761. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  52762. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  52763. }
  52764. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  52765. set: function (callback) {
  52766. if (this._onDisposeObserver) {
  52767. this.onDisposeObservable.remove(this._onDisposeObserver);
  52768. }
  52769. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52770. },
  52771. enumerable: true,
  52772. configurable: true
  52773. });
  52774. Object.defineProperty(SpriteManager.prototype, "texture", {
  52775. get: function () {
  52776. return this._spriteTexture;
  52777. },
  52778. set: function (value) {
  52779. this._spriteTexture = value;
  52780. },
  52781. enumerable: true,
  52782. configurable: true
  52783. });
  52784. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  52785. var arrayOffset = index * 16;
  52786. if (offsetX === 0)
  52787. offsetX = this._epsilon;
  52788. else if (offsetX === 1)
  52789. offsetX = 1 - this._epsilon;
  52790. if (offsetY === 0)
  52791. offsetY = this._epsilon;
  52792. else if (offsetY === 1)
  52793. offsetY = 1 - this._epsilon;
  52794. this._vertexData[arrayOffset] = sprite.position.x;
  52795. this._vertexData[arrayOffset + 1] = sprite.position.y;
  52796. this._vertexData[arrayOffset + 2] = sprite.position.z;
  52797. this._vertexData[arrayOffset + 3] = sprite.angle;
  52798. this._vertexData[arrayOffset + 4] = sprite.width;
  52799. this._vertexData[arrayOffset + 5] = sprite.height;
  52800. this._vertexData[arrayOffset + 6] = offsetX;
  52801. this._vertexData[arrayOffset + 7] = offsetY;
  52802. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  52803. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  52804. var offset = (sprite.cellIndex / rowSize) >> 0;
  52805. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  52806. this._vertexData[arrayOffset + 11] = offset;
  52807. // Color
  52808. this._vertexData[arrayOffset + 12] = sprite.color.r;
  52809. this._vertexData[arrayOffset + 13] = sprite.color.g;
  52810. this._vertexData[arrayOffset + 14] = sprite.color.b;
  52811. this._vertexData[arrayOffset + 15] = sprite.color.a;
  52812. };
  52813. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  52814. var count = Math.min(this._capacity, this.sprites.length);
  52815. var min = BABYLON.Vector3.Zero();
  52816. var max = BABYLON.Vector3.Zero();
  52817. var distance = Number.MAX_VALUE;
  52818. var currentSprite = null;
  52819. var cameraSpacePosition = BABYLON.Vector3.Zero();
  52820. var cameraView = camera.getViewMatrix();
  52821. for (var index = 0; index < count; index++) {
  52822. var sprite = this.sprites[index];
  52823. if (!sprite) {
  52824. continue;
  52825. }
  52826. if (predicate) {
  52827. if (!predicate(sprite)) {
  52828. continue;
  52829. }
  52830. }
  52831. else if (!sprite.isPickable) {
  52832. continue;
  52833. }
  52834. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  52835. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  52836. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  52837. if (ray.intersectsBoxMinMax(min, max)) {
  52838. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  52839. if (distance > currentDistance) {
  52840. distance = currentDistance;
  52841. currentSprite = sprite;
  52842. if (fastCheck) {
  52843. break;
  52844. }
  52845. }
  52846. }
  52847. }
  52848. if (currentSprite) {
  52849. var result = new BABYLON.PickingInfo();
  52850. result.hit = true;
  52851. result.pickedSprite = currentSprite;
  52852. result.distance = distance;
  52853. return result;
  52854. }
  52855. return null;
  52856. };
  52857. SpriteManager.prototype.render = function () {
  52858. // Check
  52859. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  52860. return;
  52861. var engine = this._scene.getEngine();
  52862. var baseSize = this._spriteTexture.getBaseSize();
  52863. // Sprites
  52864. var deltaTime = engine.getDeltaTime();
  52865. var max = Math.min(this._capacity, this.sprites.length);
  52866. var rowSize = baseSize.width / this.cellWidth;
  52867. var offset = 0;
  52868. for (var index = 0; index < max; index++) {
  52869. var sprite = this.sprites[index];
  52870. if (!sprite) {
  52871. continue;
  52872. }
  52873. sprite._animate(deltaTime);
  52874. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  52875. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  52876. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  52877. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  52878. }
  52879. this._buffer.update(this._vertexData);
  52880. // Render
  52881. var effect = this._effectBase;
  52882. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52883. effect = this._effectFog;
  52884. }
  52885. engine.enableEffect(effect);
  52886. var viewMatrix = this._scene.getViewMatrix();
  52887. effect.setTexture("diffuseSampler", this._spriteTexture);
  52888. effect.setMatrix("view", viewMatrix);
  52889. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52890. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  52891. // Fog
  52892. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  52893. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  52894. effect.setColor3("vFogColor", this._scene.fogColor);
  52895. }
  52896. // VBOs
  52897. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52898. // Draw order
  52899. engine.setDepthFunctionToLessOrEqual();
  52900. effect.setBool("alphaTest", true);
  52901. engine.setColorWrite(false);
  52902. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  52903. engine.setColorWrite(true);
  52904. effect.setBool("alphaTest", false);
  52905. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52906. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  52907. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52908. };
  52909. SpriteManager.prototype.dispose = function () {
  52910. if (this._buffer) {
  52911. this._buffer.dispose();
  52912. this._buffer = null;
  52913. }
  52914. if (this._indexBuffer) {
  52915. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52916. this._indexBuffer = null;
  52917. }
  52918. if (this._spriteTexture) {
  52919. this._spriteTexture.dispose();
  52920. this._spriteTexture = null;
  52921. }
  52922. // Remove from scene
  52923. var index = this._scene.spriteManagers.indexOf(this);
  52924. this._scene.spriteManagers.splice(index, 1);
  52925. // Callback
  52926. this.onDisposeObservable.notifyObservers(this);
  52927. this.onDisposeObservable.clear();
  52928. };
  52929. return SpriteManager;
  52930. }());
  52931. BABYLON.SpriteManager = SpriteManager;
  52932. })(BABYLON || (BABYLON = {}));
  52933. //# sourceMappingURL=babylon.spriteManager.js.map
  52934. "use strict";
  52935. var BABYLON;
  52936. (function (BABYLON) {
  52937. var Sprite = /** @class */ (function () {
  52938. function Sprite(name, manager) {
  52939. this.name = name;
  52940. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52941. this.width = 1.0;
  52942. this.height = 1.0;
  52943. this.angle = 0;
  52944. this.cellIndex = 0;
  52945. this.invertU = 0;
  52946. this.invertV = 0;
  52947. this.animations = new Array();
  52948. this.isPickable = false;
  52949. this._animationStarted = false;
  52950. this._loopAnimation = false;
  52951. this._fromIndex = 0;
  52952. this._toIndex = 0;
  52953. this._delay = 0;
  52954. this._direction = 1;
  52955. this._time = 0;
  52956. this._manager = manager;
  52957. this._manager.sprites.push(this);
  52958. this.position = BABYLON.Vector3.Zero();
  52959. }
  52960. Object.defineProperty(Sprite.prototype, "size", {
  52961. get: function () {
  52962. return this.width;
  52963. },
  52964. set: function (value) {
  52965. this.width = value;
  52966. this.height = value;
  52967. },
  52968. enumerable: true,
  52969. configurable: true
  52970. });
  52971. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  52972. this._fromIndex = from;
  52973. this._toIndex = to;
  52974. this._loopAnimation = loop;
  52975. this._delay = delay;
  52976. this._animationStarted = true;
  52977. this._direction = from < to ? 1 : -1;
  52978. this.cellIndex = from;
  52979. this._time = 0;
  52980. this._onAnimationEnd = onAnimationEnd;
  52981. };
  52982. Sprite.prototype.stopAnimation = function () {
  52983. this._animationStarted = false;
  52984. };
  52985. Sprite.prototype._animate = function (deltaTime) {
  52986. if (!this._animationStarted)
  52987. return;
  52988. this._time += deltaTime;
  52989. if (this._time > this._delay) {
  52990. this._time = this._time % this._delay;
  52991. this.cellIndex += this._direction;
  52992. if (this.cellIndex > this._toIndex) {
  52993. if (this._loopAnimation) {
  52994. this.cellIndex = this._fromIndex;
  52995. }
  52996. else {
  52997. this.cellIndex = this._toIndex;
  52998. this._animationStarted = false;
  52999. if (this._onAnimationEnd) {
  53000. this._onAnimationEnd();
  53001. }
  53002. if (this.disposeWhenFinishedAnimating) {
  53003. this.dispose();
  53004. }
  53005. }
  53006. }
  53007. }
  53008. };
  53009. Sprite.prototype.dispose = function () {
  53010. for (var i = 0; i < this._manager.sprites.length; i++) {
  53011. if (this._manager.sprites[i] == this) {
  53012. this._manager.sprites.splice(i, 1);
  53013. }
  53014. }
  53015. };
  53016. return Sprite;
  53017. }());
  53018. BABYLON.Sprite = Sprite;
  53019. })(BABYLON || (BABYLON = {}));
  53020. //# sourceMappingURL=babylon.sprite.js.map
  53021. "use strict";
  53022. var BABYLON;
  53023. (function (BABYLON) {
  53024. var IntersectionInfo = /** @class */ (function () {
  53025. function IntersectionInfo(bu, bv, distance) {
  53026. this.bu = bu;
  53027. this.bv = bv;
  53028. this.distance = distance;
  53029. this.faceId = 0;
  53030. this.subMeshId = 0;
  53031. }
  53032. return IntersectionInfo;
  53033. }());
  53034. BABYLON.IntersectionInfo = IntersectionInfo;
  53035. var PickingInfo = /** @class */ (function () {
  53036. function PickingInfo() {
  53037. this.hit = false;
  53038. this.distance = 0;
  53039. this.pickedPoint = null;
  53040. this.pickedMesh = null;
  53041. this.bu = 0;
  53042. this.bv = 0;
  53043. this.faceId = -1;
  53044. this.subMeshId = 0;
  53045. this.pickedSprite = null;
  53046. }
  53047. // Methods
  53048. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53049. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53050. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53051. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53052. return null;
  53053. }
  53054. var indices = this.pickedMesh.getIndices();
  53055. if (!indices) {
  53056. return null;
  53057. }
  53058. var result;
  53059. if (useVerticesNormals) {
  53060. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53061. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53062. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53063. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53064. normal0 = normal0.scale(this.bu);
  53065. normal1 = normal1.scale(this.bv);
  53066. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53067. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53068. }
  53069. else {
  53070. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53071. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53072. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53073. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53074. var p1p2 = vertex1.subtract(vertex2);
  53075. var p3p2 = vertex3.subtract(vertex2);
  53076. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53077. }
  53078. if (useWorldCoordinates) {
  53079. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53080. }
  53081. return BABYLON.Vector3.Normalize(result);
  53082. };
  53083. PickingInfo.prototype.getTextureCoordinates = function () {
  53084. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53085. return null;
  53086. }
  53087. var indices = this.pickedMesh.getIndices();
  53088. if (!indices) {
  53089. return null;
  53090. }
  53091. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53092. if (!uvs) {
  53093. return null;
  53094. }
  53095. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53096. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53097. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53098. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53099. uv1 = uv1.scale(this.bu);
  53100. uv2 = uv2.scale(this.bv);
  53101. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53102. };
  53103. return PickingInfo;
  53104. }());
  53105. BABYLON.PickingInfo = PickingInfo;
  53106. })(BABYLON || (BABYLON = {}));
  53107. //# sourceMappingURL=babylon.pickingInfo.js.map
  53108. "use strict";
  53109. var BABYLON;
  53110. (function (BABYLON) {
  53111. var Ray = /** @class */ (function () {
  53112. function Ray(origin, direction, length) {
  53113. if (length === void 0) { length = Number.MAX_VALUE; }
  53114. this.origin = origin;
  53115. this.direction = direction;
  53116. this.length = length;
  53117. }
  53118. // Methods
  53119. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53120. var d = 0.0;
  53121. var maxValue = Number.MAX_VALUE;
  53122. var inv;
  53123. var min;
  53124. var max;
  53125. var temp;
  53126. if (Math.abs(this.direction.x) < 0.0000001) {
  53127. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53128. return false;
  53129. }
  53130. }
  53131. else {
  53132. inv = 1.0 / this.direction.x;
  53133. min = (minimum.x - this.origin.x) * inv;
  53134. max = (maximum.x - this.origin.x) * inv;
  53135. if (max === -Infinity) {
  53136. max = Infinity;
  53137. }
  53138. if (min > max) {
  53139. temp = min;
  53140. min = max;
  53141. max = temp;
  53142. }
  53143. d = Math.max(min, d);
  53144. maxValue = Math.min(max, maxValue);
  53145. if (d > maxValue) {
  53146. return false;
  53147. }
  53148. }
  53149. if (Math.abs(this.direction.y) < 0.0000001) {
  53150. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53151. return false;
  53152. }
  53153. }
  53154. else {
  53155. inv = 1.0 / this.direction.y;
  53156. min = (minimum.y - this.origin.y) * inv;
  53157. max = (maximum.y - this.origin.y) * inv;
  53158. if (max === -Infinity) {
  53159. max = Infinity;
  53160. }
  53161. if (min > max) {
  53162. temp = min;
  53163. min = max;
  53164. max = temp;
  53165. }
  53166. d = Math.max(min, d);
  53167. maxValue = Math.min(max, maxValue);
  53168. if (d > maxValue) {
  53169. return false;
  53170. }
  53171. }
  53172. if (Math.abs(this.direction.z) < 0.0000001) {
  53173. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53174. return false;
  53175. }
  53176. }
  53177. else {
  53178. inv = 1.0 / this.direction.z;
  53179. min = (minimum.z - this.origin.z) * inv;
  53180. max = (maximum.z - this.origin.z) * inv;
  53181. if (max === -Infinity) {
  53182. max = Infinity;
  53183. }
  53184. if (min > max) {
  53185. temp = min;
  53186. min = max;
  53187. max = temp;
  53188. }
  53189. d = Math.max(min, d);
  53190. maxValue = Math.min(max, maxValue);
  53191. if (d > maxValue) {
  53192. return false;
  53193. }
  53194. }
  53195. return true;
  53196. };
  53197. Ray.prototype.intersectsBox = function (box) {
  53198. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53199. };
  53200. Ray.prototype.intersectsSphere = function (sphere) {
  53201. var x = sphere.center.x - this.origin.x;
  53202. var y = sphere.center.y - this.origin.y;
  53203. var z = sphere.center.z - this.origin.z;
  53204. var pyth = (x * x) + (y * y) + (z * z);
  53205. var rr = sphere.radius * sphere.radius;
  53206. if (pyth <= rr) {
  53207. return true;
  53208. }
  53209. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53210. if (dot < 0.0) {
  53211. return false;
  53212. }
  53213. var temp = pyth - (dot * dot);
  53214. return temp <= rr;
  53215. };
  53216. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53217. if (!this._edge1) {
  53218. this._edge1 = BABYLON.Vector3.Zero();
  53219. this._edge2 = BABYLON.Vector3.Zero();
  53220. this._pvec = BABYLON.Vector3.Zero();
  53221. this._tvec = BABYLON.Vector3.Zero();
  53222. this._qvec = BABYLON.Vector3.Zero();
  53223. }
  53224. vertex1.subtractToRef(vertex0, this._edge1);
  53225. vertex2.subtractToRef(vertex0, this._edge2);
  53226. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53227. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53228. if (det === 0) {
  53229. return null;
  53230. }
  53231. var invdet = 1 / det;
  53232. this.origin.subtractToRef(vertex0, this._tvec);
  53233. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53234. if (bu < 0 || bu > 1.0) {
  53235. return null;
  53236. }
  53237. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53238. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53239. if (bv < 0 || bu + bv > 1.0) {
  53240. return null;
  53241. }
  53242. //check if the distance is longer than the predefined length.
  53243. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53244. if (distance > this.length) {
  53245. return null;
  53246. }
  53247. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53248. };
  53249. Ray.prototype.intersectsPlane = function (plane) {
  53250. var distance;
  53251. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53252. if (Math.abs(result1) < 9.99999997475243E-07) {
  53253. return null;
  53254. }
  53255. else {
  53256. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53257. distance = (-plane.d - result2) / result1;
  53258. if (distance < 0.0) {
  53259. if (distance < -9.99999997475243E-07) {
  53260. return null;
  53261. }
  53262. else {
  53263. return 0;
  53264. }
  53265. }
  53266. return distance;
  53267. }
  53268. };
  53269. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53270. var tm = BABYLON.Tmp.Matrix[0];
  53271. mesh.getWorldMatrix().invertToRef(tm);
  53272. if (this._tmpRay) {
  53273. Ray.TransformToRef(this, tm, this._tmpRay);
  53274. }
  53275. else {
  53276. this._tmpRay = Ray.Transform(this, tm);
  53277. }
  53278. return mesh.intersects(this._tmpRay, fastCheck);
  53279. };
  53280. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53281. if (results) {
  53282. results.length = 0;
  53283. }
  53284. else {
  53285. results = [];
  53286. }
  53287. for (var i = 0; i < meshes.length; i++) {
  53288. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53289. if (pickInfo.hit) {
  53290. results.push(pickInfo);
  53291. }
  53292. }
  53293. results.sort(this._comparePickingInfo);
  53294. return results;
  53295. };
  53296. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53297. if (pickingInfoA.distance < pickingInfoB.distance) {
  53298. return -1;
  53299. }
  53300. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53301. return 1;
  53302. }
  53303. else {
  53304. return 0;
  53305. }
  53306. };
  53307. /**
  53308. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53309. * @param sega the first point of the segment to test the intersection against
  53310. * @param segb the second point of the segment to test the intersection against
  53311. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53312. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53313. */
  53314. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53315. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53316. var u = segb.subtract(sega);
  53317. var v = rsegb.subtract(this.origin);
  53318. var w = sega.subtract(this.origin);
  53319. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53320. var b = BABYLON.Vector3.Dot(u, v);
  53321. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53322. var d = BABYLON.Vector3.Dot(u, w);
  53323. var e = BABYLON.Vector3.Dot(v, w);
  53324. var D = a * c - b * b; // always >= 0
  53325. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53326. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53327. // compute the line parameters of the two closest points
  53328. if (D < Ray.smallnum) {
  53329. sN = 0.0; // force using point P0 on segment S1
  53330. sD = 1.0; // to prevent possible division by 0.0 later
  53331. tN = e;
  53332. tD = c;
  53333. }
  53334. else {
  53335. sN = (b * e - c * d);
  53336. tN = (a * e - b * d);
  53337. if (sN < 0.0) {
  53338. sN = 0.0;
  53339. tN = e;
  53340. tD = c;
  53341. }
  53342. else if (sN > sD) {
  53343. sN = sD;
  53344. tN = e + b;
  53345. tD = c;
  53346. }
  53347. }
  53348. if (tN < 0.0) {
  53349. tN = 0.0;
  53350. // recompute sc for this edge
  53351. if (-d < 0.0) {
  53352. sN = 0.0;
  53353. }
  53354. else if (-d > a)
  53355. sN = sD;
  53356. else {
  53357. sN = -d;
  53358. sD = a;
  53359. }
  53360. }
  53361. else if (tN > tD) {
  53362. tN = tD;
  53363. // recompute sc for this edge
  53364. if ((-d + b) < 0.0) {
  53365. sN = 0;
  53366. }
  53367. else if ((-d + b) > a) {
  53368. sN = sD;
  53369. }
  53370. else {
  53371. sN = (-d + b);
  53372. sD = a;
  53373. }
  53374. }
  53375. // finally do the division to get sc and tc
  53376. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  53377. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  53378. // get the difference of the two closest points
  53379. var qtc = v.multiplyByFloats(tc, tc, tc);
  53380. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  53381. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  53382. if (isIntersected) {
  53383. return qtc.length();
  53384. }
  53385. return -1;
  53386. };
  53387. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53388. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  53389. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  53390. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  53391. this.direction.normalize();
  53392. return this;
  53393. };
  53394. // Statics
  53395. Ray.Zero = function () {
  53396. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  53397. };
  53398. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  53399. var result = Ray.Zero();
  53400. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  53401. };
  53402. /**
  53403. * 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
  53404. * transformed to the given world matrix.
  53405. * @param origin The origin point
  53406. * @param end The end point
  53407. * @param world a matrix to transform the ray to. Default is the identity matrix.
  53408. */
  53409. Ray.CreateNewFromTo = function (origin, end, world) {
  53410. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  53411. var direction = end.subtract(origin);
  53412. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  53413. direction.normalize();
  53414. return Ray.Transform(new Ray(origin, direction, length), world);
  53415. };
  53416. Ray.Transform = function (ray, matrix) {
  53417. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  53418. Ray.TransformToRef(ray, matrix, result);
  53419. return result;
  53420. };
  53421. Ray.TransformToRef = function (ray, matrix, result) {
  53422. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  53423. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  53424. result.length = ray.length;
  53425. var dir = result.direction;
  53426. var len = dir.length();
  53427. if (!(len === 0 || len === 1)) {
  53428. var num = 1.0 / len;
  53429. dir.x *= num;
  53430. dir.y *= num;
  53431. dir.z *= num;
  53432. result.length *= len;
  53433. }
  53434. };
  53435. Ray.smallnum = 0.00000001;
  53436. Ray.rayl = 10e8;
  53437. return Ray;
  53438. }());
  53439. BABYLON.Ray = Ray;
  53440. })(BABYLON || (BABYLON = {}));
  53441. //# sourceMappingURL=babylon.ray.js.map
  53442. "use strict";
  53443. var BABYLON;
  53444. (function (BABYLON) {
  53445. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  53446. if (boxMin.x > sphereCenter.x + sphereRadius)
  53447. return false;
  53448. if (sphereCenter.x - sphereRadius > boxMax.x)
  53449. return false;
  53450. if (boxMin.y > sphereCenter.y + sphereRadius)
  53451. return false;
  53452. if (sphereCenter.y - sphereRadius > boxMax.y)
  53453. return false;
  53454. if (boxMin.z > sphereCenter.z + sphereRadius)
  53455. return false;
  53456. if (sphereCenter.z - sphereRadius > boxMax.z)
  53457. return false;
  53458. return true;
  53459. };
  53460. var getLowestRoot = (function () {
  53461. var result = { root: 0, found: false };
  53462. return function (a, b, c, maxR) {
  53463. result.root = 0;
  53464. result.found = false;
  53465. var determinant = b * b - 4.0 * a * c;
  53466. if (determinant < 0)
  53467. return result;
  53468. var sqrtD = Math.sqrt(determinant);
  53469. var r1 = (-b - sqrtD) / (2.0 * a);
  53470. var r2 = (-b + sqrtD) / (2.0 * a);
  53471. if (r1 > r2) {
  53472. var temp = r2;
  53473. r2 = r1;
  53474. r1 = temp;
  53475. }
  53476. if (r1 > 0 && r1 < maxR) {
  53477. result.root = r1;
  53478. result.found = true;
  53479. return result;
  53480. }
  53481. if (r2 > 0 && r2 < maxR) {
  53482. result.root = r2;
  53483. result.found = true;
  53484. return result;
  53485. }
  53486. return result;
  53487. };
  53488. })();
  53489. var Collider = /** @class */ (function () {
  53490. function Collider() {
  53491. this._collisionPoint = BABYLON.Vector3.Zero();
  53492. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  53493. this._tempVector = BABYLON.Vector3.Zero();
  53494. this._tempVector2 = BABYLON.Vector3.Zero();
  53495. this._tempVector3 = BABYLON.Vector3.Zero();
  53496. this._tempVector4 = BABYLON.Vector3.Zero();
  53497. this._edge = BABYLON.Vector3.Zero();
  53498. this._baseToVertex = BABYLON.Vector3.Zero();
  53499. this._destinationPoint = BABYLON.Vector3.Zero();
  53500. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  53501. this._displacementVector = BABYLON.Vector3.Zero();
  53502. this._radius = BABYLON.Vector3.One();
  53503. this._retry = 0;
  53504. this._basePointWorld = BABYLON.Vector3.Zero();
  53505. this._velocityWorld = BABYLON.Vector3.Zero();
  53506. this._normalizedVelocity = BABYLON.Vector3.Zero();
  53507. this._collisionMask = -1;
  53508. }
  53509. Object.defineProperty(Collider.prototype, "collisionMask", {
  53510. get: function () {
  53511. return this._collisionMask;
  53512. },
  53513. set: function (mask) {
  53514. this._collisionMask = !isNaN(mask) ? mask : -1;
  53515. },
  53516. enumerable: true,
  53517. configurable: true
  53518. });
  53519. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  53520. /**
  53521. * Gets the plane normal used to compute the sliding response (in local space)
  53522. */
  53523. get: function () {
  53524. return this._slidePlaneNormal;
  53525. },
  53526. enumerable: true,
  53527. configurable: true
  53528. });
  53529. // Methods
  53530. Collider.prototype._initialize = function (source, dir, e) {
  53531. this._velocity = dir;
  53532. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  53533. this._basePoint = source;
  53534. source.multiplyToRef(this._radius, this._basePointWorld);
  53535. dir.multiplyToRef(this._radius, this._velocityWorld);
  53536. this._velocityWorldLength = this._velocityWorld.length();
  53537. this._epsilon = e;
  53538. this.collisionFound = false;
  53539. };
  53540. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  53541. pa.subtractToRef(point, this._tempVector);
  53542. pb.subtractToRef(point, this._tempVector2);
  53543. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  53544. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53545. if (d < 0)
  53546. return false;
  53547. pc.subtractToRef(point, this._tempVector3);
  53548. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  53549. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53550. if (d < 0)
  53551. return false;
  53552. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  53553. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  53554. return d >= 0;
  53555. };
  53556. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  53557. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  53558. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  53559. if (distance > this._velocityWorldLength + max + sphereRadius) {
  53560. return false;
  53561. }
  53562. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  53563. return false;
  53564. return true;
  53565. };
  53566. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  53567. var t0;
  53568. var embeddedInPlane = false;
  53569. //defensive programming, actually not needed.
  53570. if (!trianglePlaneArray) {
  53571. trianglePlaneArray = [];
  53572. }
  53573. if (!trianglePlaneArray[faceIndex]) {
  53574. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  53575. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  53576. }
  53577. var trianglePlane = trianglePlaneArray[faceIndex];
  53578. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  53579. return;
  53580. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  53581. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  53582. if (normalDotVelocity == 0) {
  53583. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  53584. return;
  53585. embeddedInPlane = true;
  53586. t0 = 0;
  53587. }
  53588. else {
  53589. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53590. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  53591. if (t0 > t1) {
  53592. var temp = t1;
  53593. t1 = t0;
  53594. t0 = temp;
  53595. }
  53596. if (t0 > 1.0 || t1 < 0.0)
  53597. return;
  53598. if (t0 < 0)
  53599. t0 = 0;
  53600. if (t0 > 1.0)
  53601. t0 = 1.0;
  53602. }
  53603. this._collisionPoint.copyFromFloats(0, 0, 0);
  53604. var found = false;
  53605. var t = 1.0;
  53606. if (!embeddedInPlane) {
  53607. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  53608. this._velocity.scaleToRef(t0, this._tempVector);
  53609. this._planeIntersectionPoint.addInPlace(this._tempVector);
  53610. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  53611. found = true;
  53612. t = t0;
  53613. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  53614. }
  53615. }
  53616. if (!found) {
  53617. var velocitySquaredLength = this._velocity.lengthSquared();
  53618. var a = velocitySquaredLength;
  53619. this._basePoint.subtractToRef(p1, this._tempVector);
  53620. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53621. var c = this._tempVector.lengthSquared() - 1.0;
  53622. var lowestRoot = getLowestRoot(a, b, c, t);
  53623. if (lowestRoot.found) {
  53624. t = lowestRoot.root;
  53625. found = true;
  53626. this._collisionPoint.copyFrom(p1);
  53627. }
  53628. this._basePoint.subtractToRef(p2, this._tempVector);
  53629. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53630. c = this._tempVector.lengthSquared() - 1.0;
  53631. lowestRoot = getLowestRoot(a, b, c, t);
  53632. if (lowestRoot.found) {
  53633. t = lowestRoot.root;
  53634. found = true;
  53635. this._collisionPoint.copyFrom(p2);
  53636. }
  53637. this._basePoint.subtractToRef(p3, this._tempVector);
  53638. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  53639. c = this._tempVector.lengthSquared() - 1.0;
  53640. lowestRoot = getLowestRoot(a, b, c, t);
  53641. if (lowestRoot.found) {
  53642. t = lowestRoot.root;
  53643. found = true;
  53644. this._collisionPoint.copyFrom(p3);
  53645. }
  53646. p2.subtractToRef(p1, this._edge);
  53647. p1.subtractToRef(this._basePoint, this._baseToVertex);
  53648. var edgeSquaredLength = this._edge.lengthSquared();
  53649. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53650. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53651. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53652. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53653. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53654. lowestRoot = getLowestRoot(a, b, c, t);
  53655. if (lowestRoot.found) {
  53656. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53657. if (f >= 0.0 && f <= 1.0) {
  53658. t = lowestRoot.root;
  53659. found = true;
  53660. this._edge.scaleInPlace(f);
  53661. p1.addToRef(this._edge, this._collisionPoint);
  53662. }
  53663. }
  53664. p3.subtractToRef(p2, this._edge);
  53665. p2.subtractToRef(this._basePoint, this._baseToVertex);
  53666. edgeSquaredLength = this._edge.lengthSquared();
  53667. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53668. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53669. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53670. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53671. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53672. lowestRoot = getLowestRoot(a, b, c, t);
  53673. if (lowestRoot.found) {
  53674. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53675. if (f >= 0.0 && f <= 1.0) {
  53676. t = lowestRoot.root;
  53677. found = true;
  53678. this._edge.scaleInPlace(f);
  53679. p2.addToRef(this._edge, this._collisionPoint);
  53680. }
  53681. }
  53682. p1.subtractToRef(p3, this._edge);
  53683. p3.subtractToRef(this._basePoint, this._baseToVertex);
  53684. edgeSquaredLength = this._edge.lengthSquared();
  53685. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  53686. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  53687. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  53688. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  53689. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  53690. lowestRoot = getLowestRoot(a, b, c, t);
  53691. if (lowestRoot.found) {
  53692. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  53693. if (f >= 0.0 && f <= 1.0) {
  53694. t = lowestRoot.root;
  53695. found = true;
  53696. this._edge.scaleInPlace(f);
  53697. p3.addToRef(this._edge, this._collisionPoint);
  53698. }
  53699. }
  53700. }
  53701. if (found) {
  53702. var distToCollision = t * this._velocity.length();
  53703. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  53704. if (!this.intersectionPoint) {
  53705. this.intersectionPoint = this._collisionPoint.clone();
  53706. }
  53707. else {
  53708. this.intersectionPoint.copyFrom(this._collisionPoint);
  53709. }
  53710. this._nearestDistance = distToCollision;
  53711. this.collisionFound = true;
  53712. }
  53713. }
  53714. };
  53715. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  53716. for (var i = indexStart; i < indexEnd; i += 3) {
  53717. var p1 = pts[indices[i] - decal];
  53718. var p2 = pts[indices[i + 1] - decal];
  53719. var p3 = pts[indices[i + 2] - decal];
  53720. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  53721. }
  53722. };
  53723. Collider.prototype._getResponse = function (pos, vel) {
  53724. pos.addToRef(vel, this._destinationPoint);
  53725. vel.scaleInPlace((this._nearestDistance / vel.length()));
  53726. this._basePoint.addToRef(vel, pos);
  53727. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  53728. this._slidePlaneNormal.normalize();
  53729. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  53730. pos.addInPlace(this._displacementVector);
  53731. this.intersectionPoint.addInPlace(this._displacementVector);
  53732. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  53733. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  53734. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  53735. };
  53736. return Collider;
  53737. }());
  53738. BABYLON.Collider = Collider;
  53739. })(BABYLON || (BABYLON = {}));
  53740. //# sourceMappingURL=babylon.collider.js.map
  53741. "use strict";
  53742. var BABYLON;
  53743. (function (BABYLON) {
  53744. //WebWorker code will be inserted to this variable.
  53745. BABYLON.CollisionWorker = "";
  53746. var WorkerTaskType;
  53747. (function (WorkerTaskType) {
  53748. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  53749. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  53750. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  53751. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  53752. var WorkerReplyType;
  53753. (function (WorkerReplyType) {
  53754. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  53755. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  53756. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  53757. var CollisionCoordinatorWorker = /** @class */ (function () {
  53758. function CollisionCoordinatorWorker() {
  53759. var _this = this;
  53760. this._scaledPosition = BABYLON.Vector3.Zero();
  53761. this._scaledVelocity = BABYLON.Vector3.Zero();
  53762. this.onMeshUpdated = function (transformNode) {
  53763. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  53764. };
  53765. this.onGeometryUpdated = function (geometry) {
  53766. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  53767. };
  53768. this._afterRender = function () {
  53769. if (!_this._init)
  53770. return;
  53771. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  53772. return;
  53773. }
  53774. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  53775. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  53776. if (_this._runningUpdated > 4) {
  53777. return;
  53778. }
  53779. ++_this._runningUpdated;
  53780. var payload = {
  53781. updatedMeshes: _this._addUpdateMeshesList,
  53782. updatedGeometries: _this._addUpdateGeometriesList,
  53783. removedGeometries: _this._toRemoveGeometryArray,
  53784. removedMeshes: _this._toRemoveMeshesArray
  53785. };
  53786. var message = {
  53787. payload: payload,
  53788. taskType: WorkerTaskType.UPDATE
  53789. };
  53790. var serializable = [];
  53791. for (var id in payload.updatedGeometries) {
  53792. if (payload.updatedGeometries.hasOwnProperty(id)) {
  53793. //prepare transferables
  53794. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  53795. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  53796. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  53797. }
  53798. }
  53799. _this._worker.postMessage(message, serializable);
  53800. _this._addUpdateMeshesList = {};
  53801. _this._addUpdateGeometriesList = {};
  53802. _this._toRemoveGeometryArray = [];
  53803. _this._toRemoveMeshesArray = [];
  53804. };
  53805. this._onMessageFromWorker = function (e) {
  53806. var returnData = e.data;
  53807. if (returnData.error != WorkerReplyType.SUCCESS) {
  53808. //TODO what errors can be returned from the worker?
  53809. BABYLON.Tools.Warn("error returned from worker!");
  53810. return;
  53811. }
  53812. switch (returnData.taskType) {
  53813. case WorkerTaskType.INIT:
  53814. _this._init = true;
  53815. //Update the worked with ALL of the scene's current state
  53816. _this._scene.meshes.forEach(function (mesh) {
  53817. _this.onMeshAdded(mesh);
  53818. });
  53819. _this._scene.getGeometries().forEach(function (geometry) {
  53820. _this.onGeometryAdded(geometry);
  53821. });
  53822. break;
  53823. case WorkerTaskType.UPDATE:
  53824. _this._runningUpdated--;
  53825. break;
  53826. case WorkerTaskType.COLLIDE:
  53827. var returnPayload = returnData.payload;
  53828. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  53829. return;
  53830. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  53831. if (callback) {
  53832. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  53833. if (mesh) {
  53834. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  53835. }
  53836. }
  53837. //cleanup
  53838. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  53839. break;
  53840. }
  53841. };
  53842. this._collisionsCallbackArray = [];
  53843. this._init = false;
  53844. this._runningUpdated = 0;
  53845. this._addUpdateMeshesList = {};
  53846. this._addUpdateGeometriesList = {};
  53847. this._toRemoveGeometryArray = [];
  53848. this._toRemoveMeshesArray = [];
  53849. }
  53850. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  53851. if (!this._init)
  53852. return;
  53853. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  53854. return;
  53855. position.divideToRef(collider._radius, this._scaledPosition);
  53856. displacement.divideToRef(collider._radius, this._scaledVelocity);
  53857. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  53858. var payload = {
  53859. collider: {
  53860. position: this._scaledPosition.asArray(),
  53861. velocity: this._scaledVelocity.asArray(),
  53862. radius: collider._radius.asArray()
  53863. },
  53864. collisionId: collisionIndex,
  53865. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  53866. maximumRetry: maximumRetry
  53867. };
  53868. var message = {
  53869. payload: payload,
  53870. taskType: WorkerTaskType.COLLIDE
  53871. };
  53872. this._worker.postMessage(message);
  53873. };
  53874. CollisionCoordinatorWorker.prototype.init = function (scene) {
  53875. this._scene = scene;
  53876. this._scene.registerAfterRender(this._afterRender);
  53877. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  53878. this._worker = new Worker(workerUrl);
  53879. this._worker.onmessage = this._onMessageFromWorker;
  53880. var message = {
  53881. payload: {},
  53882. taskType: WorkerTaskType.INIT
  53883. };
  53884. this._worker.postMessage(message);
  53885. };
  53886. CollisionCoordinatorWorker.prototype.destroy = function () {
  53887. this._scene.unregisterAfterRender(this._afterRender);
  53888. this._worker.terminate();
  53889. };
  53890. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  53891. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  53892. this.onMeshUpdated(mesh);
  53893. };
  53894. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  53895. this._toRemoveMeshesArray.push(mesh.uniqueId);
  53896. };
  53897. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  53898. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  53899. geometry.onGeometryUpdated = this.onGeometryUpdated;
  53900. this.onGeometryUpdated(geometry);
  53901. };
  53902. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  53903. this._toRemoveGeometryArray.push(geometry.id);
  53904. };
  53905. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  53906. var submeshes = [];
  53907. if (mesh.subMeshes) {
  53908. submeshes = mesh.subMeshes.map(function (sm, idx) {
  53909. var boundingInfo = sm.getBoundingInfo();
  53910. return {
  53911. position: idx,
  53912. verticesStart: sm.verticesStart,
  53913. verticesCount: sm.verticesCount,
  53914. indexStart: sm.indexStart,
  53915. indexCount: sm.indexCount,
  53916. hasMaterial: !!sm.getMaterial(),
  53917. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  53918. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  53919. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  53920. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  53921. };
  53922. });
  53923. }
  53924. var geometryId = null;
  53925. if (mesh instanceof BABYLON.Mesh) {
  53926. var geometry = mesh.geometry;
  53927. geometryId = geometry ? geometry.id : null;
  53928. }
  53929. else if (mesh instanceof BABYLON.InstancedMesh) {
  53930. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  53931. geometryId = geometry ? geometry.id : null;
  53932. }
  53933. var boundingInfo = mesh.getBoundingInfo();
  53934. return {
  53935. uniqueId: mesh.uniqueId,
  53936. id: mesh.id,
  53937. name: mesh.name,
  53938. geometryId: geometryId,
  53939. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  53940. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  53941. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  53942. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  53943. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  53944. subMeshes: submeshes,
  53945. checkCollisions: mesh.checkCollisions
  53946. };
  53947. };
  53948. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  53949. return {
  53950. id: geometry.id,
  53951. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  53952. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  53953. indices: new Uint32Array(geometry.getIndices() || []),
  53954. };
  53955. };
  53956. return CollisionCoordinatorWorker;
  53957. }());
  53958. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  53959. var CollisionCoordinatorLegacy = /** @class */ (function () {
  53960. function CollisionCoordinatorLegacy() {
  53961. this._scaledPosition = BABYLON.Vector3.Zero();
  53962. this._scaledVelocity = BABYLON.Vector3.Zero();
  53963. this._finalPosition = BABYLON.Vector3.Zero();
  53964. }
  53965. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  53966. position.divideToRef(collider._radius, this._scaledPosition);
  53967. displacement.divideToRef(collider._radius, this._scaledVelocity);
  53968. collider.collidedMesh = null;
  53969. collider._retry = 0;
  53970. collider._initialVelocity = this._scaledVelocity;
  53971. collider._initialPosition = this._scaledPosition;
  53972. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  53973. this._finalPosition.multiplyInPlace(collider._radius);
  53974. //run the callback
  53975. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  53976. };
  53977. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  53978. this._scene = scene;
  53979. };
  53980. CollisionCoordinatorLegacy.prototype.destroy = function () {
  53981. //Legacy need no destruction method.
  53982. };
  53983. //No update in legacy mode
  53984. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  53985. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  53986. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  53987. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  53988. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  53989. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  53990. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  53991. if (excludedMesh === void 0) { excludedMesh = null; }
  53992. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  53993. if (collider._retry >= maximumRetry) {
  53994. finalPosition.copyFrom(position);
  53995. return;
  53996. }
  53997. // Check if this is a mesh else camera or -1
  53998. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  53999. collider._initialize(position, velocity, closeDistance);
  54000. // Check all meshes
  54001. for (var index = 0; index < this._scene.meshes.length; index++) {
  54002. var mesh = this._scene.meshes[index];
  54003. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54004. mesh._checkCollision(collider);
  54005. }
  54006. }
  54007. if (!collider.collisionFound) {
  54008. position.addToRef(velocity, finalPosition);
  54009. return;
  54010. }
  54011. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54012. collider._getResponse(position, velocity);
  54013. }
  54014. if (velocity.length() <= closeDistance) {
  54015. finalPosition.copyFrom(position);
  54016. return;
  54017. }
  54018. collider._retry++;
  54019. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54020. };
  54021. return CollisionCoordinatorLegacy;
  54022. }());
  54023. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54024. })(BABYLON || (BABYLON = {}));
  54025. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54026. "use strict";
  54027. var BABYLON;
  54028. (function (BABYLON) {
  54029. /**
  54030. * A particle represents one of the element emitted by a particle system.
  54031. * This is mainly define by its coordinates, direction, velocity and age.
  54032. */
  54033. var Particle = /** @class */ (function () {
  54034. /**
  54035. * Creates a new instance Particle
  54036. * @param particleSystem the particle system the particle belongs to
  54037. */
  54038. function Particle(
  54039. /**
  54040. * particleSystem the particle system the particle belongs to.
  54041. */
  54042. particleSystem) {
  54043. this.particleSystem = particleSystem;
  54044. /**
  54045. * The world position of the particle in the scene.
  54046. */
  54047. this.position = BABYLON.Vector3.Zero();
  54048. /**
  54049. * The world direction of the particle in the scene.
  54050. */
  54051. this.direction = BABYLON.Vector3.Zero();
  54052. /**
  54053. * The color of the particle.
  54054. */
  54055. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54056. /**
  54057. * The color change of the particle per step.
  54058. */
  54059. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54060. /**
  54061. * Defines how long will the life of the particle be.
  54062. */
  54063. this.lifeTime = 1.0;
  54064. /**
  54065. * The current age of the particle.
  54066. */
  54067. this.age = 0;
  54068. /**
  54069. * The current size of the particle.
  54070. */
  54071. this.size = 0;
  54072. /**
  54073. * The current angle of the particle.
  54074. */
  54075. this.angle = 0;
  54076. /**
  54077. * Defines how fast is the angle changing.
  54078. */
  54079. this.angularSpeed = 0;
  54080. /**
  54081. * Defines the cell index used by the particle to be rendered from a sprite.
  54082. */
  54083. this.cellIndex = 0;
  54084. this._currentFrameCounter = 0;
  54085. if (!this.particleSystem.isAnimationSheetEnabled) {
  54086. return;
  54087. }
  54088. this.updateCellInfoFromSystem();
  54089. }
  54090. Particle.prototype.updateCellInfoFromSystem = function () {
  54091. this.cellIndex = this.particleSystem.startSpriteCellID;
  54092. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54093. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54094. }
  54095. else {
  54096. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54097. }
  54098. };
  54099. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54100. // (ageOffset / scaledUpdateSpeed) / available cells
  54101. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54102. this._currentFrameCounter += scaledUpdateSpeed;
  54103. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54104. this._currentFrameCounter = 0;
  54105. this.cellIndex++;
  54106. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54107. this.cellIndex = this.particleSystem.endSpriteCellID;
  54108. }
  54109. }
  54110. };
  54111. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54112. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54113. this.cellIndex++;
  54114. this._currentFrameCounter = 0;
  54115. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54116. if (this.particleSystem.spriteCellLoop) {
  54117. this.cellIndex = this.particleSystem.startSpriteCellID;
  54118. }
  54119. else {
  54120. this.cellIndex = this.particleSystem.endSpriteCellID;
  54121. }
  54122. }
  54123. }
  54124. else {
  54125. this._currentFrameCounter++;
  54126. }
  54127. };
  54128. /**
  54129. * Copy the properties of particle to another one.
  54130. * @param other the particle to copy the information to.
  54131. */
  54132. Particle.prototype.copyTo = function (other) {
  54133. other.position.copyFrom(this.position);
  54134. other.direction.copyFrom(this.direction);
  54135. other.color.copyFrom(this.color);
  54136. other.colorStep.copyFrom(this.colorStep);
  54137. other.lifeTime = this.lifeTime;
  54138. other.age = this.age;
  54139. other.size = this.size;
  54140. other.angle = this.angle;
  54141. other.angularSpeed = this.angularSpeed;
  54142. other.particleSystem = this.particleSystem;
  54143. other.cellIndex = this.cellIndex;
  54144. };
  54145. return Particle;
  54146. }());
  54147. BABYLON.Particle = Particle;
  54148. })(BABYLON || (BABYLON = {}));
  54149. //# sourceMappingURL=babylon.particle.js.map
  54150. "use strict";
  54151. var BABYLON;
  54152. (function (BABYLON) {
  54153. /**
  54154. * This represents a particle system in Babylon.
  54155. * 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.
  54156. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54157. * @example https://doc.babylonjs.com/babylon101/particles
  54158. */
  54159. var ParticleSystem = /** @class */ (function () {
  54160. /**
  54161. * Instantiates a particle system.
  54162. * 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.
  54163. * @param name The name of the particle system
  54164. * @param capacity The max number of particles alive at the same time
  54165. * @param scene The scene the particle system belongs to
  54166. * @param customEffect a custom effect used to change the way particles are rendered by default
  54167. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54168. * @param epsilon Offset used to render the particles
  54169. */
  54170. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54171. if (customEffect === void 0) { customEffect = null; }
  54172. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54173. if (epsilon === void 0) { epsilon = 0.01; }
  54174. var _this = this;
  54175. /**
  54176. * List of animations used by the particle system.
  54177. */
  54178. this.animations = [];
  54179. /**
  54180. * The rendering group used by the Particle system to chose when to render.
  54181. */
  54182. this.renderingGroupId = 0;
  54183. /**
  54184. * The emitter represents the Mesh or position we are attaching the particle system to.
  54185. */
  54186. this.emitter = null;
  54187. /**
  54188. * The maximum number of particles to emit per frame
  54189. */
  54190. this.emitRate = 10;
  54191. /**
  54192. * If you want to launch only a few particles at once, that can be done, as well.
  54193. */
  54194. this.manualEmitCount = -1;
  54195. /**
  54196. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54197. */
  54198. this.updateSpeed = 0.01;
  54199. /**
  54200. * The amount of time the particle system is running (depends of the overall update speed).
  54201. */
  54202. this.targetStopDuration = 0;
  54203. /**
  54204. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54205. */
  54206. this.disposeOnStop = false;
  54207. /**
  54208. * Minimum power of emitting particles.
  54209. */
  54210. this.minEmitPower = 1;
  54211. /**
  54212. * Maximum power of emitting particles.
  54213. */
  54214. this.maxEmitPower = 1;
  54215. /**
  54216. * Minimum life time of emitting particles.
  54217. */
  54218. this.minLifeTime = 1;
  54219. /**
  54220. * Maximum life time of emitting particles.
  54221. */
  54222. this.maxLifeTime = 1;
  54223. /**
  54224. * Minimum Size of emitting particles.
  54225. */
  54226. this.minSize = 1;
  54227. /**
  54228. * Maximum Size of emitting particles.
  54229. */
  54230. this.maxSize = 1;
  54231. /**
  54232. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54233. */
  54234. this.minAngularSpeed = 0;
  54235. /**
  54236. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54237. */
  54238. this.maxAngularSpeed = 0;
  54239. /**
  54240. * The layer mask we are rendering the particles through.
  54241. */
  54242. this.layerMask = 0x0FFFFFFF;
  54243. /**
  54244. * This can help using your own shader to render the particle system.
  54245. * The according effect will be created
  54246. */
  54247. this.customShader = null;
  54248. /**
  54249. * By default particle system starts as soon as they are created. This prevents the
  54250. * automatic start to happen and let you decide when to start emitting particles.
  54251. */
  54252. this.preventAutoStart = false;
  54253. /**
  54254. * Callback triggered when the particle animation is ending.
  54255. */
  54256. this.onAnimationEnd = null;
  54257. /**
  54258. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54259. */
  54260. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54261. /**
  54262. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54263. * to override the particles.
  54264. */
  54265. this.forceDepthWrite = false;
  54266. /**
  54267. * You can use gravity if you want to give an orientation to your particles.
  54268. */
  54269. this.gravity = BABYLON.Vector3.Zero();
  54270. /**
  54271. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54272. */
  54273. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54274. /**
  54275. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  54276. */
  54277. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54278. /**
  54279. * Color the particle will have at the end of its lifetime.
  54280. */
  54281. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  54282. /**
  54283. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  54284. */
  54285. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54286. /**
  54287. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  54288. */
  54289. this.spriteCellLoop = true;
  54290. /**
  54291. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  54292. */
  54293. this.spriteCellChangeSpeed = 0;
  54294. /**
  54295. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  54296. */
  54297. this.startSpriteCellID = 0;
  54298. /**
  54299. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  54300. */
  54301. this.endSpriteCellID = 0;
  54302. /**
  54303. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  54304. */
  54305. this.spriteCellWidth = 0;
  54306. /**
  54307. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  54308. */
  54309. this.spriteCellHeight = 0;
  54310. /**
  54311. * An event triggered when the system is disposed.
  54312. */
  54313. this.onDisposeObservable = new BABYLON.Observable();
  54314. this._particles = new Array();
  54315. this._stockParticles = new Array();
  54316. this._newPartsExcess = 0;
  54317. this._vertexBuffers = {};
  54318. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  54319. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  54320. this._scaledDirection = BABYLON.Vector3.Zero();
  54321. this._scaledGravity = BABYLON.Vector3.Zero();
  54322. this._currentRenderId = -1;
  54323. this._started = false;
  54324. this._stopped = false;
  54325. this._actualFrame = 0;
  54326. this._vertexBufferSize = 11;
  54327. // start of sub system methods
  54328. /**
  54329. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  54330. * Its lifetime will start back at 0.
  54331. */
  54332. this.recycleParticle = function (particle) {
  54333. var lastParticle = _this._particles.pop();
  54334. if (lastParticle !== particle) {
  54335. lastParticle.copyTo(particle);
  54336. }
  54337. _this._stockParticles.push(lastParticle);
  54338. };
  54339. this._createParticle = function () {
  54340. var particle;
  54341. if (_this._stockParticles.length !== 0) {
  54342. particle = _this._stockParticles.pop();
  54343. particle.age = 0;
  54344. particle.cellIndex = _this.startSpriteCellID;
  54345. }
  54346. else {
  54347. particle = new BABYLON.Particle(_this);
  54348. }
  54349. return particle;
  54350. };
  54351. this._emitFromParticle = function (particle) {
  54352. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  54353. return;
  54354. }
  54355. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  54356. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  54357. subSystem._rootParticleSystem = _this;
  54358. _this.activeSubSystems.push(subSystem);
  54359. subSystem.start();
  54360. };
  54361. this._appendParticleVertexes = null;
  54362. this.id = name;
  54363. this.name = name;
  54364. this._capacity = capacity;
  54365. this._epsilon = epsilon;
  54366. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  54367. if (isAnimationSheetEnabled) {
  54368. this._vertexBufferSize = 12;
  54369. }
  54370. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54371. this._customEffect = customEffect;
  54372. scene.particleSystems.push(this);
  54373. this._createIndexBuffer();
  54374. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  54375. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  54376. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  54377. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  54378. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  54379. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  54380. if (this._isAnimationSheetEnabled) {
  54381. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  54382. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  54383. }
  54384. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54385. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54386. this._vertexBuffers["options"] = options;
  54387. // Default emitter type
  54388. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54389. this.updateFunction = function (particles) {
  54390. for (var index = 0; index < particles.length; index++) {
  54391. var particle = particles[index];
  54392. particle.age += _this._scaledUpdateSpeed;
  54393. if (particle.age >= particle.lifeTime) {
  54394. _this._emitFromParticle(particle);
  54395. _this.recycleParticle(particle);
  54396. index--;
  54397. continue;
  54398. }
  54399. else {
  54400. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  54401. particle.color.addInPlace(_this._scaledColorStep);
  54402. if (particle.color.a < 0)
  54403. particle.color.a = 0;
  54404. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  54405. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  54406. particle.position.addInPlace(_this._scaledDirection);
  54407. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  54408. particle.direction.addInPlace(_this._scaledGravity);
  54409. if (_this._isAnimationSheetEnabled) {
  54410. particle.updateCellIndex(_this._scaledUpdateSpeed);
  54411. }
  54412. }
  54413. }
  54414. };
  54415. }
  54416. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  54417. /**
  54418. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54419. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54420. */
  54421. get: function () {
  54422. if (this.particleEmitterType.direction1) {
  54423. return this.particleEmitterType.direction1;
  54424. }
  54425. return BABYLON.Vector3.Zero();
  54426. },
  54427. set: function (value) {
  54428. if (this.particleEmitterType.direction1) {
  54429. this.particleEmitterType.direction1 = value;
  54430. }
  54431. },
  54432. enumerable: true,
  54433. configurable: true
  54434. });
  54435. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  54436. /**
  54437. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54438. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54439. */
  54440. get: function () {
  54441. if (this.particleEmitterType.direction2) {
  54442. return this.particleEmitterType.direction2;
  54443. }
  54444. return BABYLON.Vector3.Zero();
  54445. },
  54446. set: function (value) {
  54447. if (this.particleEmitterType.direction2) {
  54448. this.particleEmitterType.direction2 = value;
  54449. }
  54450. },
  54451. enumerable: true,
  54452. configurable: true
  54453. });
  54454. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  54455. /**
  54456. * 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.
  54457. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54458. */
  54459. get: function () {
  54460. if (this.particleEmitterType.minEmitBox) {
  54461. return this.particleEmitterType.minEmitBox;
  54462. }
  54463. return BABYLON.Vector3.Zero();
  54464. },
  54465. set: function (value) {
  54466. if (this.particleEmitterType.minEmitBox) {
  54467. this.particleEmitterType.minEmitBox = value;
  54468. }
  54469. },
  54470. enumerable: true,
  54471. configurable: true
  54472. });
  54473. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  54474. /**
  54475. * 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.
  54476. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54477. */
  54478. get: function () {
  54479. if (this.particleEmitterType.maxEmitBox) {
  54480. return this.particleEmitterType.maxEmitBox;
  54481. }
  54482. return BABYLON.Vector3.Zero();
  54483. },
  54484. set: function (value) {
  54485. if (this.particleEmitterType.maxEmitBox) {
  54486. this.particleEmitterType.maxEmitBox = value;
  54487. }
  54488. },
  54489. enumerable: true,
  54490. configurable: true
  54491. });
  54492. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  54493. /**
  54494. * Sets a callback that will be triggered when the system is disposed.
  54495. */
  54496. set: function (callback) {
  54497. if (this._onDisposeObserver) {
  54498. this.onDisposeObservable.remove(this._onDisposeObserver);
  54499. }
  54500. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54501. },
  54502. enumerable: true,
  54503. configurable: true
  54504. });
  54505. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  54506. /**
  54507. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  54508. */
  54509. get: function () {
  54510. return this._isAnimationSheetEnabled;
  54511. },
  54512. enumerable: true,
  54513. configurable: true
  54514. });
  54515. Object.defineProperty(ParticleSystem.prototype, "particles", {
  54516. //end of Sub-emitter
  54517. /**
  54518. * Gets the current list of active particles
  54519. */
  54520. get: function () {
  54521. return this._particles;
  54522. },
  54523. enumerable: true,
  54524. configurable: true
  54525. });
  54526. /**
  54527. * Returns the string "ParticleSystem"
  54528. * @returns a string containing the class name
  54529. */
  54530. ParticleSystem.prototype.getClassName = function () {
  54531. return "ParticleSystem";
  54532. };
  54533. ParticleSystem.prototype._createIndexBuffer = function () {
  54534. var indices = [];
  54535. var index = 0;
  54536. for (var count = 0; count < this._capacity; count++) {
  54537. indices.push(index);
  54538. indices.push(index + 1);
  54539. indices.push(index + 2);
  54540. indices.push(index);
  54541. indices.push(index + 2);
  54542. indices.push(index + 3);
  54543. index += 4;
  54544. }
  54545. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  54546. };
  54547. /**
  54548. * Gets the maximum number of particles active at the same time.
  54549. * @returns The max number of active particles.
  54550. */
  54551. ParticleSystem.prototype.getCapacity = function () {
  54552. return this._capacity;
  54553. };
  54554. /**
  54555. * Gets Wether there are still active particles in the system.
  54556. * @returns True if it is alive, otherwise false.
  54557. */
  54558. ParticleSystem.prototype.isAlive = function () {
  54559. return this._alive;
  54560. };
  54561. /**
  54562. * Gets Wether the system has been started.
  54563. * @returns True if it has been started, otherwise false.
  54564. */
  54565. ParticleSystem.prototype.isStarted = function () {
  54566. return this._started;
  54567. };
  54568. /**
  54569. * Starts the particle system and begins to emit.
  54570. */
  54571. ParticleSystem.prototype.start = function () {
  54572. this._started = true;
  54573. this._stopped = false;
  54574. this._actualFrame = 0;
  54575. if (this.subEmitters && this.subEmitters.length != 0) {
  54576. this.activeSubSystems = new Array();
  54577. }
  54578. };
  54579. /**
  54580. * Stops the particle system.
  54581. * @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.
  54582. */
  54583. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  54584. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  54585. this._stopped = true;
  54586. if (stopSubEmitters) {
  54587. this._stopSubEmitters();
  54588. }
  54589. };
  54590. // animation sheet
  54591. /**
  54592. * Remove all active particles
  54593. */
  54594. ParticleSystem.prototype.reset = function () {
  54595. this._stockParticles = [];
  54596. this._particles = [];
  54597. };
  54598. /**
  54599. * @ignore (for internal use only)
  54600. */
  54601. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  54602. var offset = index * this._vertexBufferSize;
  54603. this._vertexData[offset] = particle.position.x;
  54604. this._vertexData[offset + 1] = particle.position.y;
  54605. this._vertexData[offset + 2] = particle.position.z;
  54606. this._vertexData[offset + 3] = particle.color.r;
  54607. this._vertexData[offset + 4] = particle.color.g;
  54608. this._vertexData[offset + 5] = particle.color.b;
  54609. this._vertexData[offset + 6] = particle.color.a;
  54610. this._vertexData[offset + 7] = particle.angle;
  54611. this._vertexData[offset + 8] = particle.size;
  54612. this._vertexData[offset + 9] = offsetX;
  54613. this._vertexData[offset + 10] = offsetY;
  54614. };
  54615. /**
  54616. * @ignore (for internal use only)
  54617. */
  54618. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  54619. if (offsetX === 0)
  54620. offsetX = this._epsilon;
  54621. else if (offsetX === 1)
  54622. offsetX = 1 - this._epsilon;
  54623. if (offsetY === 0)
  54624. offsetY = this._epsilon;
  54625. else if (offsetY === 1)
  54626. offsetY = 1 - this._epsilon;
  54627. var offset = index * this._vertexBufferSize;
  54628. this._vertexData[offset] = particle.position.x;
  54629. this._vertexData[offset + 1] = particle.position.y;
  54630. this._vertexData[offset + 2] = particle.position.z;
  54631. this._vertexData[offset + 3] = particle.color.r;
  54632. this._vertexData[offset + 4] = particle.color.g;
  54633. this._vertexData[offset + 5] = particle.color.b;
  54634. this._vertexData[offset + 6] = particle.color.a;
  54635. this._vertexData[offset + 7] = particle.angle;
  54636. this._vertexData[offset + 8] = particle.size;
  54637. this._vertexData[offset + 9] = offsetX;
  54638. this._vertexData[offset + 10] = offsetY;
  54639. this._vertexData[offset + 11] = particle.cellIndex;
  54640. };
  54641. ParticleSystem.prototype._stopSubEmitters = function () {
  54642. if (!this.activeSubSystems) {
  54643. return;
  54644. }
  54645. this.activeSubSystems.forEach(function (subSystem) {
  54646. subSystem.stop(true);
  54647. });
  54648. this.activeSubSystems = new Array();
  54649. };
  54650. ParticleSystem.prototype._removeFromRoot = function () {
  54651. if (!this._rootParticleSystem) {
  54652. return;
  54653. }
  54654. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  54655. if (index !== -1) {
  54656. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  54657. }
  54658. };
  54659. // end of sub system methods
  54660. ParticleSystem.prototype._update = function (newParticles) {
  54661. // Update current
  54662. this._alive = this._particles.length > 0;
  54663. this.updateFunction(this._particles);
  54664. // Add new ones
  54665. var worldMatrix;
  54666. if (this.emitter.position) {
  54667. var emitterMesh = this.emitter;
  54668. worldMatrix = emitterMesh.getWorldMatrix();
  54669. }
  54670. else {
  54671. var emitterPosition = this.emitter;
  54672. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  54673. }
  54674. var particle;
  54675. for (var index = 0; index < newParticles; index++) {
  54676. if (this._particles.length === this._capacity) {
  54677. break;
  54678. }
  54679. particle = this._createParticle();
  54680. this._particles.push(particle);
  54681. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  54682. if (this.startPositionFunction) {
  54683. this.startPositionFunction(worldMatrix, particle.position, particle);
  54684. }
  54685. else {
  54686. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  54687. }
  54688. if (this.startDirectionFunction) {
  54689. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54690. }
  54691. else {
  54692. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  54693. }
  54694. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  54695. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  54696. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  54697. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  54698. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  54699. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  54700. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  54701. }
  54702. };
  54703. ParticleSystem.prototype._getEffect = function () {
  54704. if (this._customEffect) {
  54705. return this._customEffect;
  54706. }
  54707. ;
  54708. var defines = [];
  54709. if (this._scene.clipPlane) {
  54710. defines.push("#define CLIPPLANE");
  54711. }
  54712. if (this._isAnimationSheetEnabled) {
  54713. defines.push("#define ANIMATESHEET");
  54714. }
  54715. // Effect
  54716. var join = defines.join("\n");
  54717. if (this._cachedDefines !== join) {
  54718. this._cachedDefines = join;
  54719. var attributesNamesOrOptions;
  54720. var effectCreationOption;
  54721. if (this._isAnimationSheetEnabled) {
  54722. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  54723. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  54724. }
  54725. else {
  54726. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  54727. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  54728. }
  54729. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  54730. }
  54731. return this._effect;
  54732. };
  54733. /**
  54734. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  54735. */
  54736. ParticleSystem.prototype.animate = function () {
  54737. if (!this._started)
  54738. return;
  54739. var effect = this._getEffect();
  54740. // Check
  54741. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  54742. return;
  54743. if (this._currentRenderId === this._scene.getRenderId()) {
  54744. return;
  54745. }
  54746. this._currentRenderId = this._scene.getRenderId();
  54747. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  54748. // determine the number of particles we need to create
  54749. var newParticles;
  54750. if (this.manualEmitCount > -1) {
  54751. newParticles = this.manualEmitCount;
  54752. this._newPartsExcess = 0;
  54753. this.manualEmitCount = 0;
  54754. }
  54755. else {
  54756. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  54757. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  54758. }
  54759. if (this._newPartsExcess > 1.0) {
  54760. newParticles += this._newPartsExcess >> 0;
  54761. this._newPartsExcess -= this._newPartsExcess >> 0;
  54762. }
  54763. this._alive = false;
  54764. if (!this._stopped) {
  54765. this._actualFrame += this._scaledUpdateSpeed;
  54766. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  54767. this.stop();
  54768. }
  54769. else {
  54770. newParticles = 0;
  54771. }
  54772. this._update(newParticles);
  54773. // Stopped?
  54774. if (this._stopped) {
  54775. if (!this._alive) {
  54776. this._started = false;
  54777. if (this.onAnimationEnd) {
  54778. this.onAnimationEnd();
  54779. }
  54780. if (this.disposeOnStop) {
  54781. this._scene._toBeDisposed.push(this);
  54782. }
  54783. }
  54784. }
  54785. // Animation sheet
  54786. if (this._isAnimationSheetEnabled) {
  54787. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  54788. }
  54789. else {
  54790. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  54791. }
  54792. // Update VBO
  54793. var offset = 0;
  54794. for (var index = 0; index < this._particles.length; index++) {
  54795. var particle = this._particles[index];
  54796. this._appendParticleVertexes(offset, particle);
  54797. offset += 4;
  54798. }
  54799. if (this._vertexBuffer) {
  54800. this._vertexBuffer.update(this._vertexData);
  54801. }
  54802. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  54803. this.stop();
  54804. }
  54805. };
  54806. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  54807. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  54808. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  54809. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  54810. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  54811. };
  54812. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  54813. this._appendParticleVertex(offset++, particle, 0, 0);
  54814. this._appendParticleVertex(offset++, particle, 1, 0);
  54815. this._appendParticleVertex(offset++, particle, 1, 1);
  54816. this._appendParticleVertex(offset++, particle, 0, 1);
  54817. };
  54818. /**
  54819. * Rebuilds the particle system.
  54820. */
  54821. ParticleSystem.prototype.rebuild = function () {
  54822. this._createIndexBuffer();
  54823. if (this._vertexBuffer) {
  54824. this._vertexBuffer._rebuild();
  54825. }
  54826. };
  54827. /**
  54828. * Is this system ready to be used/rendered
  54829. * @return true if the system is ready
  54830. */
  54831. ParticleSystem.prototype.isReady = function () {
  54832. var effect = this._getEffect();
  54833. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  54834. return false;
  54835. }
  54836. return true;
  54837. };
  54838. /**
  54839. * Renders the particle system in its current state.
  54840. * @returns the current number of particles
  54841. */
  54842. ParticleSystem.prototype.render = function () {
  54843. var effect = this._getEffect();
  54844. // Check
  54845. if (!this.isReady() || !this._particles.length) {
  54846. return 0;
  54847. }
  54848. var engine = this._scene.getEngine();
  54849. // Render
  54850. engine.enableEffect(effect);
  54851. engine.setState(false);
  54852. var viewMatrix = this._scene.getViewMatrix();
  54853. effect.setTexture("diffuseSampler", this.particleTexture);
  54854. effect.setMatrix("view", viewMatrix);
  54855. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54856. if (this._isAnimationSheetEnabled && this.particleTexture) {
  54857. var baseSize = this.particleTexture.getBaseSize();
  54858. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  54859. }
  54860. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  54861. if (this._scene.clipPlane) {
  54862. var clipPlane = this._scene.clipPlane;
  54863. var invView = viewMatrix.clone();
  54864. invView.invert();
  54865. effect.setMatrix("invView", invView);
  54866. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  54867. }
  54868. // VBOs
  54869. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54870. // Draw order
  54871. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  54872. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  54873. }
  54874. else {
  54875. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54876. }
  54877. if (this.forceDepthWrite) {
  54878. engine.setDepthWrite(true);
  54879. }
  54880. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  54881. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54882. return this._particles.length;
  54883. };
  54884. /**
  54885. * Disposes the particle system and free the associated resources
  54886. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  54887. */
  54888. ParticleSystem.prototype.dispose = function (disposeTexture) {
  54889. if (disposeTexture === void 0) { disposeTexture = true; }
  54890. if (this._vertexBuffer) {
  54891. this._vertexBuffer.dispose();
  54892. this._vertexBuffer = null;
  54893. }
  54894. if (this._indexBuffer) {
  54895. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54896. this._indexBuffer = null;
  54897. }
  54898. if (disposeTexture && this.particleTexture) {
  54899. this.particleTexture.dispose();
  54900. this.particleTexture = null;
  54901. }
  54902. this._removeFromRoot();
  54903. // Remove from scene
  54904. var index = this._scene.particleSystems.indexOf(this);
  54905. if (index > -1) {
  54906. this._scene.particleSystems.splice(index, 1);
  54907. }
  54908. // Callback
  54909. this.onDisposeObservable.notifyObservers(this);
  54910. this.onDisposeObservable.clear();
  54911. };
  54912. /**
  54913. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  54914. * @param radius The radius of the sphere to emit from
  54915. * @returns the emitter
  54916. */
  54917. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  54918. if (radius === void 0) { radius = 1; }
  54919. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  54920. this.particleEmitterType = particleEmitter;
  54921. return particleEmitter;
  54922. };
  54923. /**
  54924. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  54925. * @param radius The radius of the sphere to emit from
  54926. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  54927. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  54928. * @returns the emitter
  54929. */
  54930. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  54931. if (radius === void 0) { radius = 1; }
  54932. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  54933. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  54934. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  54935. this.particleEmitterType = particleEmitter;
  54936. return particleEmitter;
  54937. };
  54938. /**
  54939. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  54940. * @param radius The radius of the cone to emit from
  54941. * @param angle The base angle of the cone
  54942. * @returns the emitter
  54943. */
  54944. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  54945. if (radius === void 0) { radius = 1; }
  54946. if (angle === void 0) { angle = Math.PI / 4; }
  54947. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  54948. this.particleEmitterType = particleEmitter;
  54949. return particleEmitter;
  54950. };
  54951. // 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.
  54952. /**
  54953. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  54954. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  54955. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  54956. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  54957. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  54958. * @returns the emitter
  54959. */
  54960. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  54961. var particleEmitter = new BABYLON.BoxParticleEmitter();
  54962. this.particleEmitterType = particleEmitter;
  54963. this.direction1 = direction1;
  54964. this.direction2 = direction2;
  54965. this.minEmitBox = minEmitBox;
  54966. this.maxEmitBox = maxEmitBox;
  54967. return particleEmitter;
  54968. };
  54969. // Clone
  54970. /**
  54971. * Clones the particle system.
  54972. * @param name The name of the cloned object
  54973. * @param newEmitter The new emitter to use
  54974. * @returns the cloned particle system
  54975. */
  54976. ParticleSystem.prototype.clone = function (name, newEmitter) {
  54977. var custom = null;
  54978. var program = null;
  54979. if (this.customShader != null) {
  54980. program = this.customShader;
  54981. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  54982. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  54983. }
  54984. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  54985. result.customShader = program;
  54986. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  54987. if (newEmitter === undefined) {
  54988. newEmitter = this.emitter;
  54989. }
  54990. result.emitter = newEmitter;
  54991. if (this.particleTexture) {
  54992. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  54993. }
  54994. if (!this.preventAutoStart) {
  54995. result.start();
  54996. }
  54997. return result;
  54998. };
  54999. /**
  55000. * Serializes the particle system to a JSON object.
  55001. * @returns the JSON object
  55002. */
  55003. ParticleSystem.prototype.serialize = function () {
  55004. var serializationObject = {};
  55005. serializationObject.name = this.name;
  55006. serializationObject.id = this.id;
  55007. // Emitter
  55008. if (this.emitter.position) {
  55009. var emitterMesh = this.emitter;
  55010. serializationObject.emitterId = emitterMesh.id;
  55011. }
  55012. else {
  55013. var emitterPosition = this.emitter;
  55014. serializationObject.emitter = emitterPosition.asArray();
  55015. }
  55016. serializationObject.capacity = this.getCapacity();
  55017. if (this.particleTexture) {
  55018. serializationObject.textureName = this.particleTexture.name;
  55019. }
  55020. // Animations
  55021. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55022. // Particle system
  55023. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55024. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55025. serializationObject.minSize = this.minSize;
  55026. serializationObject.maxSize = this.maxSize;
  55027. serializationObject.minEmitPower = this.minEmitPower;
  55028. serializationObject.maxEmitPower = this.maxEmitPower;
  55029. serializationObject.minLifeTime = this.minLifeTime;
  55030. serializationObject.maxLifeTime = this.maxLifeTime;
  55031. serializationObject.emitRate = this.emitRate;
  55032. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55033. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55034. serializationObject.gravity = this.gravity.asArray();
  55035. serializationObject.direction1 = this.direction1.asArray();
  55036. serializationObject.direction2 = this.direction2.asArray();
  55037. serializationObject.color1 = this.color1.asArray();
  55038. serializationObject.color2 = this.color2.asArray();
  55039. serializationObject.colorDead = this.colorDead.asArray();
  55040. serializationObject.updateSpeed = this.updateSpeed;
  55041. serializationObject.targetStopDuration = this.targetStopDuration;
  55042. serializationObject.textureMask = this.textureMask.asArray();
  55043. serializationObject.blendMode = this.blendMode;
  55044. serializationObject.customShader = this.customShader;
  55045. serializationObject.preventAutoStart = this.preventAutoStart;
  55046. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55047. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55048. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55049. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55050. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55051. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55052. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55053. // Emitter
  55054. if (this.particleEmitterType) {
  55055. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  55056. }
  55057. return serializationObject;
  55058. };
  55059. /**
  55060. * Parses a JSON object to create a particle system.
  55061. * @param parsedParticleSystem The JSON object to parse
  55062. * @param scene The scene to create the particle system in
  55063. * @param rootUrl The root url to use to load external dependencies like texture
  55064. * @returns the Parsed particle system
  55065. */
  55066. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  55067. var name = parsedParticleSystem.name;
  55068. var custom = null;
  55069. var program = null;
  55070. if (parsedParticleSystem.customShader) {
  55071. program = parsedParticleSystem.customShader;
  55072. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55073. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55074. }
  55075. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  55076. particleSystem.customShader = program;
  55077. if (parsedParticleSystem.id) {
  55078. particleSystem.id = parsedParticleSystem.id;
  55079. }
  55080. // Auto start
  55081. if (parsedParticleSystem.preventAutoStart) {
  55082. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  55083. }
  55084. // Texture
  55085. if (parsedParticleSystem.textureName) {
  55086. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  55087. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  55088. }
  55089. // Emitter
  55090. if (parsedParticleSystem.emitterId) {
  55091. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  55092. }
  55093. else {
  55094. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  55095. }
  55096. // Animations
  55097. if (parsedParticleSystem.animations) {
  55098. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  55099. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  55100. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  55101. }
  55102. }
  55103. if (parsedParticleSystem.autoAnimate) {
  55104. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  55105. }
  55106. // Particle system
  55107. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  55108. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  55109. particleSystem.minSize = parsedParticleSystem.minSize;
  55110. particleSystem.maxSize = parsedParticleSystem.maxSize;
  55111. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  55112. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  55113. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  55114. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  55115. particleSystem.emitRate = parsedParticleSystem.emitRate;
  55116. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  55117. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  55118. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  55119. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  55120. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  55121. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  55122. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  55123. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  55124. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  55125. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  55126. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  55127. particleSystem.blendMode = parsedParticleSystem.blendMode;
  55128. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  55129. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  55130. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  55131. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  55132. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  55133. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  55134. if (!particleSystem.preventAutoStart) {
  55135. particleSystem.start();
  55136. }
  55137. return particleSystem;
  55138. };
  55139. /**
  55140. * Source color is added to the destination color without alpha affecting the result.
  55141. */
  55142. ParticleSystem.BLENDMODE_ONEONE = 0;
  55143. /**
  55144. * Blend current color and particle color using particle’s alpha.
  55145. */
  55146. ParticleSystem.BLENDMODE_STANDARD = 1;
  55147. return ParticleSystem;
  55148. }());
  55149. BABYLON.ParticleSystem = ParticleSystem;
  55150. })(BABYLON || (BABYLON = {}));
  55151. //# sourceMappingURL=babylon.particleSystem.js.map
  55152. "use strict";
  55153. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  55154. "use strict";
  55155. var BABYLON;
  55156. (function (BABYLON) {
  55157. /**
  55158. * Particle emitter emitting particles from the inside of a box.
  55159. * It emits the particles randomly between 2 given directions.
  55160. */
  55161. var BoxParticleEmitter = /** @class */ (function () {
  55162. /**
  55163. * Creates a new instance BoxParticleEmitter
  55164. */
  55165. function BoxParticleEmitter() {
  55166. /**
  55167. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55168. */
  55169. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  55170. /**
  55171. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55172. */
  55173. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  55174. /**
  55175. * 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.
  55176. */
  55177. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  55178. /**
  55179. * 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.
  55180. */
  55181. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  55182. }
  55183. /**
  55184. * Called by the particle System when the direction is computed for the created particle.
  55185. * @param emitPower is the power of the particle (speed)
  55186. * @param worldMatrix is the world matrix of the particle system
  55187. * @param directionToUpdate is the direction vector to update with the result
  55188. * @param particle is the particle we are computed the direction for
  55189. */
  55190. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55191. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55192. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55193. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55194. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55195. };
  55196. /**
  55197. * Called by the particle System when the position is computed for the created particle.
  55198. * @param worldMatrix is the world matrix of the particle system
  55199. * @param positionToUpdate is the position vector to update with the result
  55200. * @param particle is the particle we are computed the position for
  55201. */
  55202. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55203. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  55204. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  55205. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  55206. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55207. };
  55208. /**
  55209. * Clones the current emitter and returns a copy of it
  55210. * @returns the new emitter
  55211. */
  55212. BoxParticleEmitter.prototype.clone = function () {
  55213. var newOne = new BoxParticleEmitter();
  55214. BABYLON.Tools.DeepCopy(this, newOne);
  55215. return newOne;
  55216. };
  55217. /**
  55218. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55219. * @param effect defines the update shader
  55220. */
  55221. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  55222. effect.setVector3("direction1", this.direction1);
  55223. effect.setVector3("direction2", this.direction2);
  55224. effect.setVector3("minEmitBox", this.minEmitBox);
  55225. effect.setVector3("maxEmitBox", this.maxEmitBox);
  55226. };
  55227. /**
  55228. * Returns a string to use to update the GPU particles update shader
  55229. * @returns a string containng the defines string
  55230. */
  55231. BoxParticleEmitter.prototype.getEffectDefines = function () {
  55232. return "#define BOXEMITTER";
  55233. };
  55234. /**
  55235. * Returns the string "BoxEmitter"
  55236. * @returns a string containing the class name
  55237. */
  55238. BoxParticleEmitter.prototype.getClassName = function () {
  55239. return "BoxEmitter";
  55240. };
  55241. /**
  55242. * Serializes the particle system to a JSON object.
  55243. * @returns the JSON object
  55244. */
  55245. BoxParticleEmitter.prototype.serialize = function () {
  55246. var serializationObject = {};
  55247. serializationObject.type = this.getClassName();
  55248. serializationObject.direction1 = this.direction1.asArray();
  55249. ;
  55250. serializationObject.direction2 = this.direction2.asArray();
  55251. ;
  55252. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55253. ;
  55254. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55255. ;
  55256. return serializationObject;
  55257. };
  55258. /**
  55259. * Parse properties from a JSON object
  55260. * @param serializationObject defines the JSON object
  55261. */
  55262. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  55263. this.direction1.copyFrom(serializationObject.direction1);
  55264. this.direction2.copyFrom(serializationObject.direction2);
  55265. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  55266. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  55267. };
  55268. return BoxParticleEmitter;
  55269. }());
  55270. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  55271. })(BABYLON || (BABYLON = {}));
  55272. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  55273. "use strict";
  55274. var BABYLON;
  55275. (function (BABYLON) {
  55276. /**
  55277. * Particle emitter emitting particles from the inside of a cone.
  55278. * It emits the particles alongside the cone volume from the base to the particle.
  55279. * The emission direction might be randomized.
  55280. */
  55281. var ConeParticleEmitter = /** @class */ (function () {
  55282. /**
  55283. * Creates a new instance ConeParticleEmitter
  55284. * @param radius the radius of the emission cone (1 by default)
  55285. * @param angles the cone base angle (PI by default)
  55286. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55287. */
  55288. function ConeParticleEmitter(radius,
  55289. /**
  55290. * The radius of the emission cone.
  55291. */
  55292. angle,
  55293. /**
  55294. * The cone base angle.
  55295. */
  55296. directionRandomizer) {
  55297. if (radius === void 0) { radius = 1; }
  55298. if (angle === void 0) { angle = Math.PI; }
  55299. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55300. this.angle = angle;
  55301. this.directionRandomizer = directionRandomizer;
  55302. this.radius = radius;
  55303. }
  55304. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  55305. /**
  55306. * Gets the radius of the emission cone.
  55307. */
  55308. get: function () {
  55309. return this._radius;
  55310. },
  55311. /**
  55312. * Sets the radius of the emission cone.
  55313. */
  55314. set: function (value) {
  55315. this._radius = value;
  55316. if (this.angle !== 0) {
  55317. this._height = value / Math.tan(this.angle / 2);
  55318. }
  55319. else {
  55320. this._height = 1;
  55321. }
  55322. },
  55323. enumerable: true,
  55324. configurable: true
  55325. });
  55326. /**
  55327. * Called by the particle System when the direction is computed for the created particle.
  55328. * @param emitPower is the power of the particle (speed)
  55329. * @param worldMatrix is the world matrix of the particle system
  55330. * @param directionToUpdate is the direction vector to update with the result
  55331. * @param particle is the particle we are computed the direction for
  55332. */
  55333. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55334. if (this.angle === 0) {
  55335. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  55336. }
  55337. else {
  55338. // measure the direction Vector from the emitter to the particle.
  55339. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55340. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55341. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55342. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55343. direction.x += randX;
  55344. direction.y += randY;
  55345. direction.z += randZ;
  55346. direction.normalize();
  55347. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55348. }
  55349. };
  55350. /**
  55351. * Called by the particle System when the position is computed for the created particle.
  55352. * @param worldMatrix is the world matrix of the particle system
  55353. * @param positionToUpdate is the position vector to update with the result
  55354. * @param particle is the particle we are computed the position for
  55355. */
  55356. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55357. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  55358. var h = BABYLON.Scalar.RandomRange(0, 1);
  55359. // Better distribution in a cone at normal angles.
  55360. h = 1 - h * h;
  55361. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  55362. radius = radius * h;
  55363. var randX = radius * Math.sin(s);
  55364. var randZ = radius * Math.cos(s);
  55365. var randY = h * this._height;
  55366. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55367. };
  55368. /**
  55369. * Clones the current emitter and returns a copy of it
  55370. * @returns the new emitter
  55371. */
  55372. ConeParticleEmitter.prototype.clone = function () {
  55373. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  55374. BABYLON.Tools.DeepCopy(this, newOne);
  55375. return newOne;
  55376. };
  55377. /**
  55378. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55379. * @param effect defines the update shader
  55380. */
  55381. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  55382. effect.setFloat("radius", this.radius);
  55383. effect.setFloat("angle", this.angle);
  55384. effect.setFloat("height", this._height);
  55385. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55386. };
  55387. /**
  55388. * Returns a string to use to update the GPU particles update shader
  55389. * @returns a string containng the defines string
  55390. */
  55391. ConeParticleEmitter.prototype.getEffectDefines = function () {
  55392. return "#define CONEEMITTER";
  55393. };
  55394. /**
  55395. * Returns the string "BoxEmitter"
  55396. * @returns a string containing the class name
  55397. */
  55398. ConeParticleEmitter.prototype.getClassName = function () {
  55399. return "ConeEmitter";
  55400. };
  55401. /**
  55402. * Serializes the particle system to a JSON object.
  55403. * @returns the JSON object
  55404. */
  55405. ConeParticleEmitter.prototype.serialize = function () {
  55406. var serializationObject = {};
  55407. serializationObject.type = this.getClassName();
  55408. serializationObject.radius = this.radius;
  55409. serializationObject.angle = this.angle;
  55410. serializationObject.directionRandomizer = this.directionRandomizer;
  55411. return serializationObject;
  55412. };
  55413. /**
  55414. * Parse properties from a JSON object
  55415. * @param serializationObject defines the JSON object
  55416. */
  55417. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  55418. this.radius = serializationObject.radius;
  55419. this.angle = serializationObject.angle;
  55420. this.directionRandomizer = serializationObject.directionRandomizer;
  55421. };
  55422. return ConeParticleEmitter;
  55423. }());
  55424. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  55425. })(BABYLON || (BABYLON = {}));
  55426. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  55427. "use strict";
  55428. var BABYLON;
  55429. (function (BABYLON) {
  55430. /**
  55431. * Particle emitter emitting particles from the inside of a sphere.
  55432. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  55433. */
  55434. var SphereParticleEmitter = /** @class */ (function () {
  55435. /**
  55436. * Creates a new instance SphereParticleEmitter
  55437. * @param radius the radius of the emission sphere (1 by default)
  55438. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  55439. */
  55440. function SphereParticleEmitter(
  55441. /**
  55442. * The radius of the emission sphere.
  55443. */
  55444. radius,
  55445. /**
  55446. * How much to randomize the particle direction [0-1].
  55447. */
  55448. directionRandomizer) {
  55449. if (radius === void 0) { radius = 1; }
  55450. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  55451. this.radius = radius;
  55452. this.directionRandomizer = directionRandomizer;
  55453. }
  55454. /**
  55455. * Called by the particle System when the direction is computed for the created particle.
  55456. * @param emitPower is the power of the particle (speed)
  55457. * @param worldMatrix is the world matrix of the particle system
  55458. * @param directionToUpdate is the direction vector to update with the result
  55459. * @param particle is the particle we are computed the direction for
  55460. */
  55461. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55462. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  55463. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55464. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55465. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  55466. direction.x += randX;
  55467. direction.y += randY;
  55468. direction.z += randZ;
  55469. direction.normalize();
  55470. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  55471. };
  55472. /**
  55473. * Called by the particle System when the position is computed for the created particle.
  55474. * @param worldMatrix is the world matrix of the particle system
  55475. * @param positionToUpdate is the position vector to update with the result
  55476. * @param particle is the particle we are computed the position for
  55477. */
  55478. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  55479. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  55480. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  55481. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  55482. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  55483. var randY = randRadius * Math.cos(theta);
  55484. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  55485. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  55486. };
  55487. /**
  55488. * Clones the current emitter and returns a copy of it
  55489. * @returns the new emitter
  55490. */
  55491. SphereParticleEmitter.prototype.clone = function () {
  55492. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  55493. BABYLON.Tools.DeepCopy(this, newOne);
  55494. return newOne;
  55495. };
  55496. /**
  55497. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55498. * @param effect defines the update shader
  55499. */
  55500. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  55501. effect.setFloat("radius", this.radius);
  55502. effect.setFloat("directionRandomizer", this.directionRandomizer);
  55503. };
  55504. /**
  55505. * Returns a string to use to update the GPU particles update shader
  55506. * @returns a string containng the defines string
  55507. */
  55508. SphereParticleEmitter.prototype.getEffectDefines = function () {
  55509. return "#define SPHEREEMITTER";
  55510. };
  55511. /**
  55512. * Returns the string "SphereParticleEmitter"
  55513. * @returns a string containing the class name
  55514. */
  55515. SphereParticleEmitter.prototype.getClassName = function () {
  55516. return "SphereParticleEmitter";
  55517. };
  55518. /**
  55519. * Serializes the particle system to a JSON object.
  55520. * @returns the JSON object
  55521. */
  55522. SphereParticleEmitter.prototype.serialize = function () {
  55523. var serializationObject = {};
  55524. serializationObject.type = this.getClassName();
  55525. serializationObject.radius = this.radius;
  55526. serializationObject.directionRandomizer = this.directionRandomizer;
  55527. return serializationObject;
  55528. };
  55529. /**
  55530. * Parse properties from a JSON object
  55531. * @param serializationObject defines the JSON object
  55532. */
  55533. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  55534. this.radius = serializationObject.radius;
  55535. this.directionRandomizer = serializationObject.directionRandomizer;
  55536. };
  55537. return SphereParticleEmitter;
  55538. }());
  55539. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  55540. /**
  55541. * Particle emitter emitting particles from the inside of a sphere.
  55542. * It emits the particles randomly between two vectors.
  55543. */
  55544. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  55545. __extends(SphereDirectedParticleEmitter, _super);
  55546. /**
  55547. * Creates a new instance SphereDirectedParticleEmitter
  55548. * @param radius the radius of the emission sphere (1 by default)
  55549. * @param direction1 the min limit of the emission direction (up vector by default)
  55550. * @param direction2 the max limit of the emission direction (up vector by default)
  55551. */
  55552. function SphereDirectedParticleEmitter(radius,
  55553. /**
  55554. * The min limit of the emission direction.
  55555. */
  55556. direction1,
  55557. /**
  55558. * The max limit of the emission direction.
  55559. */
  55560. direction2) {
  55561. if (radius === void 0) { radius = 1; }
  55562. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  55563. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  55564. var _this = _super.call(this, radius) || this;
  55565. _this.direction1 = direction1;
  55566. _this.direction2 = direction2;
  55567. return _this;
  55568. }
  55569. /**
  55570. * Called by the particle System when the direction is computed for the created particle.
  55571. * @param emitPower is the power of the particle (speed)
  55572. * @param worldMatrix is the world matrix of the particle system
  55573. * @param directionToUpdate is the direction vector to update with the result
  55574. * @param particle is the particle we are computed the direction for
  55575. */
  55576. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  55577. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  55578. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  55579. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  55580. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  55581. };
  55582. /**
  55583. * Clones the current emitter and returns a copy of it
  55584. * @returns the new emitter
  55585. */
  55586. SphereDirectedParticleEmitter.prototype.clone = function () {
  55587. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  55588. BABYLON.Tools.DeepCopy(this, newOne);
  55589. return newOne;
  55590. };
  55591. /**
  55592. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  55593. * @param effect defines the update shader
  55594. */
  55595. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  55596. effect.setFloat("radius", this.radius);
  55597. effect.setVector3("direction1", this.direction1);
  55598. effect.setVector3("direction2", this.direction2);
  55599. };
  55600. /**
  55601. * Returns a string to use to update the GPU particles update shader
  55602. * @returns a string containng the defines string
  55603. */
  55604. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  55605. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  55606. };
  55607. /**
  55608. * Returns the string "SphereDirectedParticleEmitter"
  55609. * @returns a string containing the class name
  55610. */
  55611. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  55612. return "SphereDirectedParticleEmitter";
  55613. };
  55614. /**
  55615. * Serializes the particle system to a JSON object.
  55616. * @returns the JSON object
  55617. */
  55618. SphereDirectedParticleEmitter.prototype.serialize = function () {
  55619. var serializationObject = _super.prototype.serialize.call(this);
  55620. ;
  55621. serializationObject.direction1 = this.direction1.asArray();
  55622. ;
  55623. serializationObject.direction2 = this.direction2.asArray();
  55624. ;
  55625. return serializationObject;
  55626. };
  55627. /**
  55628. * Parse properties from a JSON object
  55629. * @param serializationObject defines the JSON object
  55630. */
  55631. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  55632. _super.prototype.parse.call(this, serializationObject);
  55633. this.direction1.copyFrom(serializationObject.direction1);
  55634. this.direction2.copyFrom(serializationObject.direction2);
  55635. };
  55636. return SphereDirectedParticleEmitter;
  55637. }(SphereParticleEmitter));
  55638. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  55639. })(BABYLON || (BABYLON = {}));
  55640. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  55641. "use strict";
  55642. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55643. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55644. s = arguments[i];
  55645. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55646. t[p] = s[p];
  55647. }
  55648. return t;
  55649. };
  55650. var BABYLON;
  55651. (function (BABYLON) {
  55652. /**
  55653. * This represents a GPU particle system in Babylon
  55654. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  55655. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  55656. */
  55657. var GPUParticleSystem = /** @class */ (function () {
  55658. /**
  55659. * Instantiates a GPU particle system.
  55660. * 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.
  55661. * @param name The name of the particle system
  55662. * @param capacity The max number of particles alive at the same time
  55663. * @param scene The scene the particle system belongs to
  55664. */
  55665. function GPUParticleSystem(name, options, scene) {
  55666. /**
  55667. * The emitter represents the Mesh or position we are attaching the particle system to.
  55668. */
  55669. this.emitter = null;
  55670. /**
  55671. * The rendering group used by the Particle system to chose when to render.
  55672. */
  55673. this.renderingGroupId = 0;
  55674. /**
  55675. * The layer mask we are rendering the particles through.
  55676. */
  55677. this.layerMask = 0x0FFFFFFF;
  55678. this._targetIndex = 0;
  55679. this._currentRenderId = -1;
  55680. this._started = false;
  55681. this._stopped = false;
  55682. this._timeDelta = 0;
  55683. this._attributesStrideSize = 14;
  55684. this._actualFrame = 0;
  55685. /**
  55686. * List of animations used by the particle system.
  55687. */
  55688. this.animations = [];
  55689. /**
  55690. * An event triggered when the system is disposed.
  55691. */
  55692. this.onDisposeObservable = new BABYLON.Observable();
  55693. /**
  55694. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55695. */
  55696. this.updateSpeed = 0.01;
  55697. /**
  55698. * The amount of time the particle system is running (depends of the overall update speed).
  55699. */
  55700. this.targetStopDuration = 0;
  55701. /**
  55702. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55703. */
  55704. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55705. /**
  55706. * Minimum life time of emitting particles.
  55707. */
  55708. this.minLifeTime = 1;
  55709. /**
  55710. * Maximum life time of emitting particles.
  55711. */
  55712. this.maxLifeTime = 1;
  55713. /**
  55714. * Minimum Size of emitting particles.
  55715. */
  55716. this.minSize = 1;
  55717. /**
  55718. * Maximum Size of emitting particles.
  55719. */
  55720. this.maxSize = 1;
  55721. /**
  55722. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55723. */
  55724. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55725. /**
  55726. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55727. */
  55728. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55729. /**
  55730. * Color the particle will have at the end of its lifetime.
  55731. */
  55732. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  55733. /**
  55734. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  55735. */
  55736. this.emitRate = 100;
  55737. /**
  55738. * You can use gravity if you want to give an orientation to your particles.
  55739. */
  55740. this.gravity = BABYLON.Vector3.Zero();
  55741. /**
  55742. * Minimum power of emitting particles.
  55743. */
  55744. this.minEmitPower = 1;
  55745. /**
  55746. * Maximum power of emitting particles.
  55747. */
  55748. this.maxEmitPower = 1;
  55749. /**
  55750. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55751. * to override the particles.
  55752. */
  55753. this.forceDepthWrite = false;
  55754. this.id = name;
  55755. this.name = name;
  55756. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55757. this._engine = this._scene.getEngine();
  55758. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  55759. this._capacity = fullOptions.capacity;
  55760. this._activeCount = fullOptions.capacity;
  55761. this._currentActiveCount = 0;
  55762. this._scene.particleSystems.push(this);
  55763. this._updateEffectOptions = {
  55764. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  55765. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  55766. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  55767. uniformBuffersNames: [],
  55768. samplers: ["randomSampler"],
  55769. defines: "",
  55770. fallbacks: null,
  55771. onCompiled: null,
  55772. onError: null,
  55773. indexParameters: null,
  55774. maxSimultaneousLights: 0,
  55775. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  55776. };
  55777. // Random data
  55778. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  55779. var d = [];
  55780. for (var i = 0; i < maxTextureSize; ++i) {
  55781. d.push(Math.random());
  55782. d.push(Math.random());
  55783. d.push(Math.random());
  55784. d.push(Math.random());
  55785. }
  55786. 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);
  55787. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55788. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55789. this._randomTextureSize = maxTextureSize;
  55790. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55791. }
  55792. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  55793. /**
  55794. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  55795. */
  55796. get: function () {
  55797. if (!BABYLON.Engine.LastCreatedEngine) {
  55798. return false;
  55799. }
  55800. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  55801. },
  55802. enumerable: true,
  55803. configurable: true
  55804. });
  55805. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  55806. /**
  55807. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55808. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55809. */
  55810. get: function () {
  55811. if (this.particleEmitterType.direction1) {
  55812. return this.particleEmitterType.direction1;
  55813. }
  55814. return BABYLON.Vector3.Zero();
  55815. },
  55816. set: function (value) {
  55817. if (this.particleEmitterType.direction1) {
  55818. this.particleEmitterType.direction1 = value;
  55819. }
  55820. },
  55821. enumerable: true,
  55822. configurable: true
  55823. });
  55824. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  55825. /**
  55826. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55827. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55828. */
  55829. get: function () {
  55830. if (this.particleEmitterType.direction2) {
  55831. return this.particleEmitterType.direction2;
  55832. }
  55833. return BABYLON.Vector3.Zero();
  55834. },
  55835. set: function (value) {
  55836. if (this.particleEmitterType.direction2) {
  55837. this.particleEmitterType.direction2 = value;
  55838. }
  55839. },
  55840. enumerable: true,
  55841. configurable: true
  55842. });
  55843. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  55844. /**
  55845. * 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.
  55846. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55847. */
  55848. get: function () {
  55849. if (this.particleEmitterType.minEmitBox) {
  55850. return this.particleEmitterType.minEmitBox;
  55851. }
  55852. return BABYLON.Vector3.Zero();
  55853. },
  55854. set: function (value) {
  55855. if (this.particleEmitterType.minEmitBox) {
  55856. this.particleEmitterType.minEmitBox = value;
  55857. }
  55858. },
  55859. enumerable: true,
  55860. configurable: true
  55861. });
  55862. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  55863. /**
  55864. * 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.
  55865. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55866. */
  55867. get: function () {
  55868. if (this.particleEmitterType.maxEmitBox) {
  55869. return this.particleEmitterType.maxEmitBox;
  55870. }
  55871. return BABYLON.Vector3.Zero();
  55872. },
  55873. set: function (value) {
  55874. if (this.particleEmitterType.maxEmitBox) {
  55875. this.particleEmitterType.maxEmitBox = value;
  55876. }
  55877. },
  55878. enumerable: true,
  55879. configurable: true
  55880. });
  55881. /**
  55882. * Gets the maximum number of particles active at the same time.
  55883. * @returns The max number of active particles.
  55884. */
  55885. GPUParticleSystem.prototype.getCapacity = function () {
  55886. return this._capacity;
  55887. };
  55888. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  55889. /**
  55890. * Gets or set the number of active particles
  55891. */
  55892. get: function () {
  55893. return this._activeCount;
  55894. },
  55895. set: function (value) {
  55896. this._activeCount = Math.min(value, this._capacity);
  55897. },
  55898. enumerable: true,
  55899. configurable: true
  55900. });
  55901. /**
  55902. * Is this system ready to be used/rendered
  55903. * @return true if the system is ready
  55904. */
  55905. GPUParticleSystem.prototype.isReady = function () {
  55906. if (!this._updateEffect) {
  55907. this._recreateUpdateEffect();
  55908. this._recreateRenderEffect();
  55909. return false;
  55910. }
  55911. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55912. return false;
  55913. }
  55914. return true;
  55915. };
  55916. /**
  55917. * Gets Wether the system has been started.
  55918. * @returns True if it has been started, otherwise false.
  55919. */
  55920. GPUParticleSystem.prototype.isStarted = function () {
  55921. return this._started;
  55922. };
  55923. /**
  55924. * Starts the particle system and begins to emit.
  55925. */
  55926. GPUParticleSystem.prototype.start = function () {
  55927. this._started = true;
  55928. this._stopped = false;
  55929. };
  55930. /**
  55931. * Stops the particle system.
  55932. */
  55933. GPUParticleSystem.prototype.stop = function () {
  55934. this._stopped = true;
  55935. };
  55936. /**
  55937. * Remove all active particles
  55938. */
  55939. GPUParticleSystem.prototype.reset = function () {
  55940. this._releaseBuffers();
  55941. this._releaseVAOs();
  55942. this._currentActiveCount = 0;
  55943. this._targetIndex = 0;
  55944. };
  55945. /**
  55946. * Returns the string "GPUParticleSystem"
  55947. * @returns a string containing the class name
  55948. */
  55949. GPUParticleSystem.prototype.getClassName = function () {
  55950. return "GPUParticleSystem";
  55951. };
  55952. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  55953. var updateVertexBuffers = {};
  55954. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  55955. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  55956. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  55957. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  55958. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  55959. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  55960. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  55961. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  55962. this._engine.bindArrayBuffer(null);
  55963. return vao;
  55964. };
  55965. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  55966. var renderVertexBuffers = {};
  55967. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  55968. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  55969. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  55970. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  55971. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  55972. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  55973. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  55974. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  55975. this._engine.bindArrayBuffer(null);
  55976. return vao;
  55977. };
  55978. GPUParticleSystem.prototype._initialize = function (force) {
  55979. if (force === void 0) { force = false; }
  55980. if (this._buffer0 && !force) {
  55981. return;
  55982. }
  55983. var engine = this._scene.getEngine();
  55984. var data = new Array();
  55985. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  55986. // position
  55987. data.push(0.0);
  55988. data.push(0.0);
  55989. data.push(0.0);
  55990. // Age and life
  55991. data.push(0.0); // create the particle as a dead one to create a new one at start
  55992. data.push(0.0);
  55993. // Seed
  55994. data.push(Math.random());
  55995. // Size
  55996. data.push(0.0);
  55997. // color
  55998. data.push(0.0);
  55999. data.push(0.0);
  56000. data.push(0.0);
  56001. data.push(0.0);
  56002. // direction
  56003. data.push(0.0);
  56004. data.push(0.0);
  56005. data.push(0.0);
  56006. }
  56007. // Sprite data
  56008. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56009. -0.5, 0.5, 0, 1,
  56010. -0.5, -0.5, 0, 0,
  56011. 0.5, -0.5, 1, 0]);
  56012. // Buffers
  56013. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56014. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56015. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56016. // Update VAO
  56017. this._updateVAO = [];
  56018. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56019. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56020. // Render VAO
  56021. this._renderVAO = [];
  56022. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56023. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56024. // Links
  56025. this._sourceBuffer = this._buffer0;
  56026. this._targetBuffer = this._buffer1;
  56027. };
  56028. /** @ignore */
  56029. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56030. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56031. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56032. return;
  56033. }
  56034. this._updateEffectOptions.defines = defines;
  56035. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56036. };
  56037. /** @ignore */
  56038. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56039. var defines = "";
  56040. if (this._scene.clipPlane) {
  56041. defines = "\n#define CLIPPLANE";
  56042. }
  56043. if (this._renderEffect && this._renderEffect.defines === defines) {
  56044. return;
  56045. }
  56046. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56047. };
  56048. /**
  56049. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56050. */
  56051. GPUParticleSystem.prototype.animate = function () {
  56052. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  56053. this._actualFrame += this._timeDelta;
  56054. if (!this._stopped) {
  56055. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  56056. this.stop();
  56057. }
  56058. }
  56059. };
  56060. /**
  56061. * Renders the particle system in its current state.
  56062. * @returns the current number of particles
  56063. */
  56064. GPUParticleSystem.prototype.render = function () {
  56065. if (!this._started) {
  56066. return 0;
  56067. }
  56068. this._recreateUpdateEffect();
  56069. this._recreateRenderEffect();
  56070. if (!this.isReady()) {
  56071. return 0;
  56072. }
  56073. if (this._currentRenderId === this._scene.getRenderId()) {
  56074. return 0;
  56075. }
  56076. this._currentRenderId = this._scene.getRenderId();
  56077. // Get everything ready to render
  56078. this._initialize();
  56079. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  56080. // Enable update effect
  56081. this._engine.enableEffect(this._updateEffect);
  56082. this._engine.setState(false);
  56083. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  56084. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  56085. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  56086. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  56087. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  56088. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  56089. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  56090. this._updateEffect.setDirectColor4("color1", this.color1);
  56091. this._updateEffect.setDirectColor4("color2", this.color2);
  56092. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  56093. this._updateEffect.setVector3("gravity", this.gravity);
  56094. if (this.particleEmitterType) {
  56095. this.particleEmitterType.applyToShader(this._updateEffect);
  56096. }
  56097. var emitterWM;
  56098. if (this.emitter.position) {
  56099. var emitterMesh = this.emitter;
  56100. emitterWM = emitterMesh.getWorldMatrix();
  56101. }
  56102. else {
  56103. var emitterPosition = this.emitter;
  56104. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56105. }
  56106. this._updateEffect.setMatrix("emitterWM", emitterWM);
  56107. // Bind source VAO
  56108. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  56109. // Update
  56110. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  56111. this._engine.setRasterizerState(false);
  56112. this._engine.beginTransformFeedback();
  56113. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  56114. this._engine.endTransformFeedback();
  56115. this._engine.setRasterizerState(true);
  56116. this._engine.bindTransformFeedbackBuffer(null);
  56117. // Enable render effect
  56118. this._engine.enableEffect(this._renderEffect);
  56119. var viewMatrix = this._scene.getViewMatrix();
  56120. this._renderEffect.setMatrix("view", viewMatrix);
  56121. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  56122. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  56123. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  56124. if (this._scene.clipPlane) {
  56125. var clipPlane = this._scene.clipPlane;
  56126. var invView = viewMatrix.clone();
  56127. invView.invert();
  56128. this._renderEffect.setMatrix("invView", invView);
  56129. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56130. }
  56131. // Draw order
  56132. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  56133. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56134. }
  56135. else {
  56136. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56137. }
  56138. if (this.forceDepthWrite) {
  56139. this._engine.setDepthWrite(true);
  56140. }
  56141. // Bind source VAO
  56142. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  56143. // Render
  56144. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  56145. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56146. // Switch VAOs
  56147. this._targetIndex++;
  56148. if (this._targetIndex === 2) {
  56149. this._targetIndex = 0;
  56150. }
  56151. // Switch buffers
  56152. var tmpBuffer = this._sourceBuffer;
  56153. this._sourceBuffer = this._targetBuffer;
  56154. this._targetBuffer = tmpBuffer;
  56155. return this._currentActiveCount;
  56156. };
  56157. /**
  56158. * Rebuilds the particle system
  56159. */
  56160. GPUParticleSystem.prototype.rebuild = function () {
  56161. this._initialize(true);
  56162. };
  56163. GPUParticleSystem.prototype._releaseBuffers = function () {
  56164. if (this._buffer0) {
  56165. this._buffer0.dispose();
  56166. this._buffer0 = null;
  56167. }
  56168. if (this._buffer1) {
  56169. this._buffer1.dispose();
  56170. this._buffer1 = null;
  56171. }
  56172. if (this._spriteBuffer) {
  56173. this._spriteBuffer.dispose();
  56174. this._spriteBuffer = null;
  56175. }
  56176. };
  56177. GPUParticleSystem.prototype._releaseVAOs = function () {
  56178. if (!this._updateVAO) {
  56179. return;
  56180. }
  56181. for (var index = 0; index < this._updateVAO.length; index++) {
  56182. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  56183. }
  56184. this._updateVAO = [];
  56185. for (var index = 0; index < this._renderVAO.length; index++) {
  56186. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  56187. }
  56188. this._renderVAO = [];
  56189. };
  56190. /**
  56191. * Disposes the particle system and free the associated resources
  56192. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56193. */
  56194. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  56195. if (disposeTexture === void 0) { disposeTexture = true; }
  56196. var index = this._scene.particleSystems.indexOf(this);
  56197. if (index > -1) {
  56198. this._scene.particleSystems.splice(index, 1);
  56199. }
  56200. this._releaseBuffers();
  56201. this._releaseVAOs();
  56202. if (this._randomTexture) {
  56203. this._randomTexture.dispose();
  56204. this._randomTexture = null;
  56205. }
  56206. if (disposeTexture && this.particleTexture) {
  56207. this.particleTexture.dispose();
  56208. this.particleTexture = null;
  56209. }
  56210. // Callback
  56211. this.onDisposeObservable.notifyObservers(this);
  56212. this.onDisposeObservable.clear();
  56213. };
  56214. /**
  56215. * Clones the particle system.
  56216. * @param name The name of the cloned object
  56217. * @param newEmitter The new emitter to use
  56218. * @returns the cloned particle system
  56219. */
  56220. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  56221. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  56222. BABYLON.Tools.DeepCopy(this, result);
  56223. if (newEmitter === undefined) {
  56224. newEmitter = this.emitter;
  56225. }
  56226. result.emitter = newEmitter;
  56227. if (this.particleTexture) {
  56228. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56229. }
  56230. return result;
  56231. };
  56232. /**
  56233. * Serializes the particle system to a JSON object.
  56234. * @returns the JSON object
  56235. */
  56236. GPUParticleSystem.prototype.serialize = function () {
  56237. var serializationObject = {};
  56238. serializationObject.name = this.name;
  56239. serializationObject.id = this.id;
  56240. // Emitter
  56241. if (this.emitter.position) {
  56242. var emitterMesh = this.emitter;
  56243. serializationObject.emitterId = emitterMesh.id;
  56244. }
  56245. else {
  56246. var emitterPosition = this.emitter;
  56247. serializationObject.emitter = emitterPosition.asArray();
  56248. }
  56249. serializationObject.capacity = this.getCapacity();
  56250. if (this.particleTexture) {
  56251. serializationObject.textureName = this.particleTexture.name;
  56252. }
  56253. // Animations
  56254. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56255. // Particle system
  56256. serializationObject.activeParticleCount = this.activeParticleCount;
  56257. serializationObject.randomTextureSize = this._randomTextureSize;
  56258. serializationObject.minSize = this.minSize;
  56259. serializationObject.maxSize = this.maxSize;
  56260. serializationObject.minEmitPower = this.minEmitPower;
  56261. serializationObject.maxEmitPower = this.maxEmitPower;
  56262. serializationObject.minLifeTime = this.minLifeTime;
  56263. serializationObject.maxLifeTime = this.maxLifeTime;
  56264. serializationObject.emitRate = this.emitRate;
  56265. serializationObject.gravity = this.gravity.asArray();
  56266. serializationObject.color1 = this.color1.asArray();
  56267. serializationObject.color2 = this.color2.asArray();
  56268. serializationObject.colorDead = this.colorDead.asArray();
  56269. serializationObject.updateSpeed = this.updateSpeed;
  56270. serializationObject.targetStopDuration = this.targetStopDuration;
  56271. serializationObject.blendMode = this.blendMode;
  56272. // Emitter
  56273. if (this.particleEmitterType) {
  56274. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56275. }
  56276. return serializationObject;
  56277. };
  56278. /**
  56279. * Parses a JSON object to create a GPU particle system.
  56280. * @param parsedParticleSystem The JSON object to parse
  56281. * @param scene The scene to create the particle system in
  56282. * @param rootUrl The root url to use to load external dependencies like texture
  56283. * @returns the parsed GPU particle system
  56284. */
  56285. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56286. var name = parsedParticleSystem.name;
  56287. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  56288. if (parsedParticleSystem.id) {
  56289. particleSystem.id = parsedParticleSystem.id;
  56290. }
  56291. // Texture
  56292. if (parsedParticleSystem.textureName) {
  56293. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56294. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56295. }
  56296. // Emitter
  56297. if (parsedParticleSystem.emitterId) {
  56298. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56299. }
  56300. else {
  56301. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56302. }
  56303. // Animations
  56304. if (parsedParticleSystem.animations) {
  56305. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56306. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56307. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56308. }
  56309. }
  56310. // Particle system
  56311. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  56312. particleSystem.minSize = parsedParticleSystem.minSize;
  56313. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56314. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56315. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56316. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56317. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56318. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56319. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56320. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56321. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56322. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56323. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56324. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56325. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56326. // Emitter
  56327. if (parsedParticleSystem.particleEmitterType) {
  56328. var emitterType = void 0;
  56329. switch (parsedParticleSystem.particleEmitterType.type) {
  56330. case "SphereEmitter":
  56331. emitterType = new BABYLON.SphereParticleEmitter();
  56332. break;
  56333. case "SphereDirectedParticleEmitter":
  56334. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56335. break;
  56336. case "ConeEmitter":
  56337. emitterType = new BABYLON.ConeParticleEmitter();
  56338. break;
  56339. case "BoxEmitter":
  56340. default:
  56341. emitterType = new BABYLON.BoxParticleEmitter();
  56342. break;
  56343. }
  56344. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56345. particleSystem.particleEmitterType = emitterType;
  56346. }
  56347. return particleSystem;
  56348. };
  56349. return GPUParticleSystem;
  56350. }());
  56351. BABYLON.GPUParticleSystem = GPUParticleSystem;
  56352. })(BABYLON || (BABYLON = {}));
  56353. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  56354. "use strict";
  56355. var BABYLON;
  56356. (function (BABYLON) {
  56357. /**
  56358. * Represents one particle of a solid particle system.
  56359. */
  56360. var SolidParticle = /** @class */ (function () {
  56361. /**
  56362. * Creates a Solid Particle object.
  56363. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  56364. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  56365. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  56366. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  56367. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  56368. * @param shapeId (integer) is the model shape identifier in the SPS.
  56369. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  56370. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  56371. */
  56372. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  56373. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  56374. /**
  56375. * particle global index
  56376. */
  56377. this.idx = 0;
  56378. /**
  56379. * The color of the particle
  56380. */
  56381. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56382. /**
  56383. * The world space position of the particle.
  56384. */
  56385. this.position = BABYLON.Vector3.Zero();
  56386. /**
  56387. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  56388. */
  56389. this.rotation = BABYLON.Vector3.Zero();
  56390. /**
  56391. * The scaling of the particle.
  56392. */
  56393. this.scaling = BABYLON.Vector3.One();
  56394. /**
  56395. * The uvs of the particle.
  56396. */
  56397. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  56398. /**
  56399. * The current speed of the particle.
  56400. */
  56401. this.velocity = BABYLON.Vector3.Zero();
  56402. /**
  56403. * The pivot point in the particle local space.
  56404. */
  56405. this.pivot = BABYLON.Vector3.Zero();
  56406. /**
  56407. * Must the particle be translated from its pivot point in its local space ?
  56408. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  56409. * Default : false
  56410. */
  56411. this.translateFromPivot = false;
  56412. /**
  56413. * Is the particle active or not ?
  56414. */
  56415. this.alive = true;
  56416. /**
  56417. * Is the particle visible or not ?
  56418. */
  56419. this.isVisible = true;
  56420. /**
  56421. * Index of this particle in the global "positions" array (Internal use)
  56422. */
  56423. this._pos = 0;
  56424. /**
  56425. * Index of this particle in the global "indices" array (Internal use)
  56426. */
  56427. this._ind = 0;
  56428. /**
  56429. * ModelShape id of this particle
  56430. */
  56431. this.shapeId = 0;
  56432. /**
  56433. * Index of the particle in its shape id (Internal use)
  56434. */
  56435. this.idxInShape = 0;
  56436. /**
  56437. * Still set as invisible in order to skip useless computations (Internal use)
  56438. */
  56439. this._stillInvisible = false;
  56440. /**
  56441. * Last computed particle rotation matrix
  56442. */
  56443. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  56444. /**
  56445. * Parent particle Id, if any.
  56446. * Default null.
  56447. */
  56448. this.parentId = null;
  56449. /**
  56450. * Internal global position in the SPS.
  56451. */
  56452. this._globalPosition = BABYLON.Vector3.Zero();
  56453. this.idx = particleIndex;
  56454. this._pos = positionIndex;
  56455. this._ind = indiceIndex;
  56456. this._model = model;
  56457. this.shapeId = shapeId;
  56458. this.idxInShape = idxInShape;
  56459. this._sps = sps;
  56460. if (modelBoundingInfo) {
  56461. this._modelBoundingInfo = modelBoundingInfo;
  56462. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  56463. }
  56464. }
  56465. Object.defineProperty(SolidParticle.prototype, "scale", {
  56466. /**
  56467. * Legacy support, changed scale to scaling
  56468. */
  56469. get: function () {
  56470. return this.scaling;
  56471. },
  56472. /**
  56473. * Legacy support, changed scale to scaling
  56474. */
  56475. set: function (scale) {
  56476. this.scaling = scale;
  56477. },
  56478. enumerable: true,
  56479. configurable: true
  56480. });
  56481. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56482. /**
  56483. * Legacy support, changed quaternion to rotationQuaternion
  56484. */
  56485. get: function () {
  56486. return this.rotationQuaternion;
  56487. },
  56488. /**
  56489. * Legacy support, changed quaternion to rotationQuaternion
  56490. */
  56491. set: function (q) {
  56492. this.rotationQuaternion = q;
  56493. },
  56494. enumerable: true,
  56495. configurable: true
  56496. });
  56497. /**
  56498. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  56499. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  56500. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  56501. * @returns true if it intersects
  56502. */
  56503. SolidParticle.prototype.intersectsMesh = function (target) {
  56504. if (!this._boundingInfo || !target._boundingInfo) {
  56505. return false;
  56506. }
  56507. if (this._sps._bSphereOnly) {
  56508. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  56509. }
  56510. return this._boundingInfo.intersects(target._boundingInfo, false);
  56511. };
  56512. return SolidParticle;
  56513. }());
  56514. BABYLON.SolidParticle = SolidParticle;
  56515. /**
  56516. * Represents the shape of the model used by one particle of a solid particle system.
  56517. * SPS internal tool, don't use it manually.
  56518. */
  56519. var ModelShape = /** @class */ (function () {
  56520. /**
  56521. * 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.
  56522. * SPS internal tool, don't use it manually.
  56523. * @ignore
  56524. */
  56525. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  56526. /**
  56527. * length of the shape in the model indices array (internal use)
  56528. */
  56529. this._indicesLength = 0;
  56530. this.shapeID = id;
  56531. this._shape = shape;
  56532. this._indicesLength = indicesLength;
  56533. this._shapeUV = shapeUV;
  56534. this._positionFunction = posFunction;
  56535. this._vertexFunction = vtxFunction;
  56536. }
  56537. return ModelShape;
  56538. }());
  56539. BABYLON.ModelShape = ModelShape;
  56540. /**
  56541. * Represents a Depth Sorted Particle in the solid particle system.
  56542. */
  56543. var DepthSortedParticle = /** @class */ (function () {
  56544. function DepthSortedParticle() {
  56545. /**
  56546. * Index of the particle in the "indices" array
  56547. */
  56548. this.ind = 0;
  56549. /**
  56550. * Length of the particle shape in the "indices" array
  56551. */
  56552. this.indicesLength = 0;
  56553. /**
  56554. * Squared distance from the particle to the camera
  56555. */
  56556. this.sqDistance = 0.0;
  56557. }
  56558. return DepthSortedParticle;
  56559. }());
  56560. BABYLON.DepthSortedParticle = DepthSortedParticle;
  56561. })(BABYLON || (BABYLON = {}));
  56562. //# sourceMappingURL=babylon.solidParticle.js.map
  56563. "use strict";
  56564. var BABYLON;
  56565. (function (BABYLON) {
  56566. /**
  56567. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  56568. *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.
  56569. * The SPS is also a particle system. It provides some methods to manage the particles.
  56570. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  56571. *
  56572. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56573. */
  56574. var SolidParticleSystem = /** @class */ (function () {
  56575. /**
  56576. * Creates a SPS (Solid Particle System) object.
  56577. * @param name (String) is the SPS name, this will be the underlying mesh name.
  56578. * @param scene (Scene) is the scene in which the SPS is added.
  56579. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  56580. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  56581. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  56582. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  56583. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  56584. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  56585. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  56586. */
  56587. function SolidParticleSystem(name, scene, options) {
  56588. /**
  56589. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56590. * Example : var p = SPS.particles[i];
  56591. */
  56592. this.particles = new Array();
  56593. /**
  56594. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56595. */
  56596. this.nbParticles = 0;
  56597. /**
  56598. * If the particles must ever face the camera (default false). Useful for planar particles.
  56599. */
  56600. this.billboard = false;
  56601. /**
  56602. * Recompute normals when adding a shape
  56603. */
  56604. this.recomputeNormals = true;
  56605. /**
  56606. * This a counter ofr your own usage. It's not set by any SPS functions.
  56607. */
  56608. this.counter = 0;
  56609. /**
  56610. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56611. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56612. */
  56613. this.vars = {};
  56614. /**
  56615. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  56616. */
  56617. this._bSphereOnly = false;
  56618. /**
  56619. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  56620. */
  56621. this._bSphereRadiusFactor = 1.0;
  56622. this._positions = new Array();
  56623. this._indices = new Array();
  56624. this._normals = new Array();
  56625. this._colors = new Array();
  56626. this._uvs = new Array();
  56627. this._index = 0; // indices index
  56628. this._updatable = true;
  56629. this._pickable = false;
  56630. this._isVisibilityBoxLocked = false;
  56631. this._alwaysVisible = false;
  56632. this._depthSort = false;
  56633. this._shapeCounter = 0;
  56634. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  56635. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56636. this._computeParticleColor = true;
  56637. this._computeParticleTexture = true;
  56638. this._computeParticleRotation = true;
  56639. this._computeParticleVertex = false;
  56640. this._computeBoundingBox = false;
  56641. this._depthSortParticles = true;
  56642. this._cam_axisZ = BABYLON.Vector3.Zero();
  56643. this._cam_axisY = BABYLON.Vector3.Zero();
  56644. this._cam_axisX = BABYLON.Vector3.Zero();
  56645. this._axisZ = BABYLON.Axis.Z;
  56646. this._camDir = BABYLON.Vector3.Zero();
  56647. this._camInvertedPosition = BABYLON.Vector3.Zero();
  56648. this._rotMatrix = new BABYLON.Matrix();
  56649. this._invertMatrix = new BABYLON.Matrix();
  56650. this._rotated = BABYLON.Vector3.Zero();
  56651. this._quaternion = new BABYLON.Quaternion();
  56652. this._vertex = BABYLON.Vector3.Zero();
  56653. this._normal = BABYLON.Vector3.Zero();
  56654. this._yaw = 0.0;
  56655. this._pitch = 0.0;
  56656. this._roll = 0.0;
  56657. this._halfroll = 0.0;
  56658. this._halfpitch = 0.0;
  56659. this._halfyaw = 0.0;
  56660. this._sinRoll = 0.0;
  56661. this._cosRoll = 0.0;
  56662. this._sinPitch = 0.0;
  56663. this._cosPitch = 0.0;
  56664. this._sinYaw = 0.0;
  56665. this._cosYaw = 0.0;
  56666. this._mustUnrotateFixedNormals = false;
  56667. this._minimum = BABYLON.Vector3.Zero();
  56668. this._maximum = BABYLON.Vector3.Zero();
  56669. this._minBbox = BABYLON.Vector3.Zero();
  56670. this._maxBbox = BABYLON.Vector3.Zero();
  56671. this._particlesIntersect = false;
  56672. this._depthSortFunction = function (p1, p2) {
  56673. return (p2.sqDistance - p1.sqDistance);
  56674. };
  56675. this._needs32Bits = false;
  56676. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  56677. this._scaledPivot = BABYLON.Vector3.Zero();
  56678. this._particleHasParent = false;
  56679. this.name = name;
  56680. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56681. this._camera = scene.activeCamera;
  56682. this._pickable = options ? options.isPickable : false;
  56683. this._depthSort = options ? options.enableDepthSort : false;
  56684. this._particlesIntersect = options ? options.particleIntersection : false;
  56685. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  56686. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  56687. if (options && options.updatable) {
  56688. this._updatable = options.updatable;
  56689. }
  56690. else {
  56691. this._updatable = true;
  56692. }
  56693. if (this._pickable) {
  56694. this.pickedParticles = [];
  56695. }
  56696. if (this._depthSort) {
  56697. this.depthSortedParticles = [];
  56698. }
  56699. }
  56700. /**
  56701. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56702. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56703. * @returns the created mesh
  56704. */
  56705. SolidParticleSystem.prototype.buildMesh = function () {
  56706. if (this.nbParticles === 0) {
  56707. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  56708. this.addShape(triangle, 1);
  56709. triangle.dispose();
  56710. }
  56711. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  56712. this._positions32 = new Float32Array(this._positions);
  56713. this._uvs32 = new Float32Array(this._uvs);
  56714. this._colors32 = new Float32Array(this._colors);
  56715. if (this.recomputeNormals) {
  56716. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  56717. }
  56718. this._normals32 = new Float32Array(this._normals);
  56719. this._fixedNormal32 = new Float32Array(this._normals);
  56720. if (this._mustUnrotateFixedNormals) {
  56721. this._unrotateFixedNormals();
  56722. }
  56723. var vertexData = new BABYLON.VertexData();
  56724. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  56725. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56726. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56727. if (this._uvs32) {
  56728. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56729. ;
  56730. }
  56731. if (this._colors32) {
  56732. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56733. }
  56734. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56735. vertexData.applyToMesh(mesh, this._updatable);
  56736. this.mesh = mesh;
  56737. this.mesh.isPickable = this._pickable;
  56738. // free memory
  56739. if (!this._depthSort) {
  56740. this._indices = null;
  56741. }
  56742. this._positions = null;
  56743. this._normals = null;
  56744. this._uvs = null;
  56745. this._colors = null;
  56746. if (!this._updatable) {
  56747. this.particles.length = 0;
  56748. }
  56749. return mesh;
  56750. };
  56751. /**
  56752. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56753. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56754. * Thus the particles generated from `digest()` have their property `position` set yet.
  56755. * @param mesh ( Mesh ) is the mesh to be digested
  56756. * @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
  56757. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56758. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56759. * @returns the current SPS
  56760. */
  56761. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56762. var size = (options && options.facetNb) || 1;
  56763. var number = (options && options.number) || 0;
  56764. var delta = (options && options.delta) || 0;
  56765. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56766. var meshInd = mesh.getIndices();
  56767. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56768. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56769. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56770. var f = 0; // facet counter
  56771. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  56772. // compute size from number
  56773. if (number) {
  56774. number = (number > totalFacets) ? totalFacets : number;
  56775. size = Math.round(totalFacets / number);
  56776. delta = 0;
  56777. }
  56778. else {
  56779. size = (size > totalFacets) ? totalFacets : size;
  56780. }
  56781. var facetPos = []; // submesh positions
  56782. var facetInd = []; // submesh indices
  56783. var facetUV = []; // submesh UV
  56784. var facetCol = []; // submesh colors
  56785. var barycenter = BABYLON.Vector3.Zero();
  56786. var sizeO = size;
  56787. while (f < totalFacets) {
  56788. size = sizeO + Math.floor((1 + delta) * Math.random());
  56789. if (f > totalFacets - size) {
  56790. size = totalFacets - f;
  56791. }
  56792. // reset temp arrays
  56793. facetPos.length = 0;
  56794. facetInd.length = 0;
  56795. facetUV.length = 0;
  56796. facetCol.length = 0;
  56797. // iterate over "size" facets
  56798. var fi = 0;
  56799. for (var j = f * 3; j < (f + size) * 3; j++) {
  56800. facetInd.push(fi);
  56801. var i = meshInd[j];
  56802. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  56803. if (meshUV) {
  56804. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  56805. }
  56806. if (meshCol) {
  56807. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  56808. }
  56809. fi++;
  56810. }
  56811. // create a model shape for each single particle
  56812. var idx = this.nbParticles;
  56813. var shape = this._posToShape(facetPos);
  56814. var shapeUV = this._uvsToShapeUV(facetUV);
  56815. // compute the barycenter of the shape
  56816. var v;
  56817. for (v = 0; v < shape.length; v++) {
  56818. barycenter.addInPlace(shape[v]);
  56819. }
  56820. barycenter.scaleInPlace(1 / shape.length);
  56821. // shift the shape from its barycenter to the origin
  56822. for (v = 0; v < shape.length; v++) {
  56823. shape[v].subtractInPlace(barycenter);
  56824. }
  56825. var bInfo;
  56826. if (this._particlesIntersect) {
  56827. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  56828. }
  56829. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  56830. // add the particle in the SPS
  56831. var currentPos = this._positions.length;
  56832. var currentInd = this._indices.length;
  56833. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  56834. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  56835. // initialize the particle position
  56836. this.particles[this.nbParticles].position.addInPlace(barycenter);
  56837. this._index += shape.length;
  56838. idx++;
  56839. this.nbParticles++;
  56840. this._shapeCounter++;
  56841. f += size;
  56842. }
  56843. return this;
  56844. };
  56845. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  56846. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  56847. var index = 0;
  56848. var idx = 0;
  56849. for (var p = 0; p < this.particles.length; p++) {
  56850. this._particle = this.particles[p];
  56851. this._shape = this._particle._model._shape;
  56852. if (this._particle.rotationQuaternion) {
  56853. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  56854. }
  56855. else {
  56856. this._yaw = this._particle.rotation.y;
  56857. this._pitch = this._particle.rotation.x;
  56858. this._roll = this._particle.rotation.z;
  56859. this._quaternionRotationYPR();
  56860. }
  56861. this._quaternionToRotationMatrix();
  56862. this._rotMatrix.invertToRef(this._invertMatrix);
  56863. for (var pt = 0; pt < this._shape.length; pt++) {
  56864. idx = index + pt * 3;
  56865. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  56866. this._fixedNormal32[idx] = this._normal.x;
  56867. this._fixedNormal32[idx + 1] = this._normal.y;
  56868. this._fixedNormal32[idx + 2] = this._normal.z;
  56869. }
  56870. index = idx + 3;
  56871. }
  56872. };
  56873. //reset copy
  56874. SolidParticleSystem.prototype._resetCopy = function () {
  56875. this._copy.position.x = 0;
  56876. this._copy.position.y = 0;
  56877. this._copy.position.z = 0;
  56878. this._copy.rotation.x = 0;
  56879. this._copy.rotation.y = 0;
  56880. this._copy.rotation.z = 0;
  56881. this._copy.rotationQuaternion = null;
  56882. this._copy.scaling.x = 1.0;
  56883. this._copy.scaling.y = 1.0;
  56884. this._copy.scaling.z = 1.0;
  56885. this._copy.uvs.x = 0;
  56886. this._copy.uvs.y = 0;
  56887. this._copy.uvs.z = 1.0;
  56888. this._copy.uvs.w = 1.0;
  56889. this._copy.color = null;
  56890. this._copy.translateFromPivot = false;
  56891. };
  56892. // _meshBuilder : inserts the shape model in the global SPS mesh
  56893. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  56894. var i;
  56895. var u = 0;
  56896. var c = 0;
  56897. var n = 0;
  56898. this._resetCopy();
  56899. if (options && options.positionFunction) {
  56900. options.positionFunction(this._copy, idx, idxInShape);
  56901. this._mustUnrotateFixedNormals = true;
  56902. }
  56903. if (this._copy.rotationQuaternion) {
  56904. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  56905. }
  56906. else {
  56907. this._yaw = this._copy.rotation.y;
  56908. this._pitch = this._copy.rotation.x;
  56909. this._roll = this._copy.rotation.z;
  56910. this._quaternionRotationYPR();
  56911. }
  56912. this._quaternionToRotationMatrix();
  56913. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  56914. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  56915. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  56916. if (this._copy.translateFromPivot) {
  56917. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  56918. }
  56919. else {
  56920. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  56921. }
  56922. for (i = 0; i < shape.length; i++) {
  56923. this._vertex.x = shape[i].x;
  56924. this._vertex.y = shape[i].y;
  56925. this._vertex.z = shape[i].z;
  56926. if (options && options.vertexFunction) {
  56927. options.vertexFunction(this._copy, this._vertex, i);
  56928. }
  56929. this._vertex.x *= this._copy.scaling.x;
  56930. this._vertex.y *= this._copy.scaling.y;
  56931. this._vertex.z *= this._copy.scaling.z;
  56932. this._vertex.x -= this._scaledPivot.x;
  56933. this._vertex.y -= this._scaledPivot.y;
  56934. this._vertex.z -= this._scaledPivot.z;
  56935. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  56936. this._rotated.addInPlace(this._pivotBackTranslation);
  56937. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  56938. if (meshUV) {
  56939. 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);
  56940. u += 2;
  56941. }
  56942. if (this._copy.color) {
  56943. this._color = this._copy.color;
  56944. }
  56945. else if (meshCol && meshCol[c] !== undefined) {
  56946. this._color.r = meshCol[c];
  56947. this._color.g = meshCol[c + 1];
  56948. this._color.b = meshCol[c + 2];
  56949. this._color.a = meshCol[c + 3];
  56950. }
  56951. else {
  56952. this._color.r = 1.0;
  56953. this._color.g = 1.0;
  56954. this._color.b = 1.0;
  56955. this._color.a = 1.0;
  56956. }
  56957. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  56958. c += 4;
  56959. if (!this.recomputeNormals && meshNor) {
  56960. this._normal.x = meshNor[n];
  56961. this._normal.y = meshNor[n + 1];
  56962. this._normal.z = meshNor[n + 2];
  56963. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  56964. normals.push(this._normal.x, this._normal.y, this._normal.z);
  56965. n += 3;
  56966. }
  56967. }
  56968. for (i = 0; i < meshInd.length; i++) {
  56969. var current_ind = p + meshInd[i];
  56970. indices.push(current_ind);
  56971. if (current_ind > 65535) {
  56972. this._needs32Bits = true;
  56973. }
  56974. }
  56975. if (this._pickable) {
  56976. var nbfaces = meshInd.length / 3;
  56977. for (i = 0; i < nbfaces; i++) {
  56978. this.pickedParticles.push({ idx: idx, faceId: i });
  56979. }
  56980. }
  56981. if (this._depthSort) {
  56982. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  56983. }
  56984. return this._copy;
  56985. };
  56986. // returns a shape array from positions array
  56987. SolidParticleSystem.prototype._posToShape = function (positions) {
  56988. var shape = [];
  56989. for (var i = 0; i < positions.length; i += 3) {
  56990. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  56991. }
  56992. return shape;
  56993. };
  56994. // returns a shapeUV array from a Vector4 uvs
  56995. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  56996. var shapeUV = [];
  56997. if (uvs) {
  56998. for (var i = 0; i < uvs.length; i++)
  56999. shapeUV.push(uvs[i]);
  57000. }
  57001. return shapeUV;
  57002. };
  57003. // adds a new particle object in the particles array
  57004. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57005. if (bInfo === void 0) { bInfo = null; }
  57006. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57007. this.particles.push(sp);
  57008. return sp;
  57009. };
  57010. /**
  57011. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57012. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57013. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57014. * @param nb (positive integer) the number of particles to be created from this model
  57015. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57016. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57017. * @returns the number of shapes in the system
  57018. */
  57019. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57020. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57021. var meshInd = mesh.getIndices();
  57022. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57023. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57024. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57025. var bbInfo;
  57026. if (this._particlesIntersect) {
  57027. bbInfo = mesh.getBoundingInfo();
  57028. }
  57029. var shape = this._posToShape(meshPos);
  57030. var shapeUV = this._uvsToShapeUV(meshUV);
  57031. var posfunc = options ? options.positionFunction : null;
  57032. var vtxfunc = options ? options.vertexFunction : null;
  57033. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57034. // particles
  57035. var sp;
  57036. var currentCopy;
  57037. var idx = this.nbParticles;
  57038. for (var i = 0; i < nb; i++) {
  57039. var currentPos = this._positions.length;
  57040. var currentInd = this._indices.length;
  57041. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57042. if (this._updatable) {
  57043. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57044. sp.position.copyFrom(currentCopy.position);
  57045. sp.rotation.copyFrom(currentCopy.rotation);
  57046. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57047. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57048. }
  57049. if (currentCopy.color && sp.color) {
  57050. sp.color.copyFrom(currentCopy.color);
  57051. }
  57052. sp.scaling.copyFrom(currentCopy.scaling);
  57053. sp.uvs.copyFrom(currentCopy.uvs);
  57054. }
  57055. this._index += shape.length;
  57056. idx++;
  57057. }
  57058. this.nbParticles += nb;
  57059. this._shapeCounter++;
  57060. return this._shapeCounter - 1;
  57061. };
  57062. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57063. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57064. this._resetCopy();
  57065. if (particle._model._positionFunction) {
  57066. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57067. }
  57068. if (this._copy.rotationQuaternion) {
  57069. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57070. }
  57071. else {
  57072. this._yaw = this._copy.rotation.y;
  57073. this._pitch = this._copy.rotation.x;
  57074. this._roll = this._copy.rotation.z;
  57075. this._quaternionRotationYPR();
  57076. }
  57077. this._quaternionToRotationMatrix();
  57078. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57079. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57080. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57081. if (this._copy.translateFromPivot) {
  57082. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57083. }
  57084. else {
  57085. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57086. }
  57087. this._shape = particle._model._shape;
  57088. for (var pt = 0; pt < this._shape.length; pt++) {
  57089. this._vertex.x = this._shape[pt].x;
  57090. this._vertex.y = this._shape[pt].y;
  57091. this._vertex.z = this._shape[pt].z;
  57092. if (particle._model._vertexFunction) {
  57093. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57094. }
  57095. this._vertex.x *= this._copy.scaling.x;
  57096. this._vertex.y *= this._copy.scaling.y;
  57097. this._vertex.z *= this._copy.scaling.z;
  57098. this._vertex.x -= this._scaledPivot.x;
  57099. this._vertex.y -= this._scaledPivot.y;
  57100. this._vertex.z -= this._scaledPivot.z;
  57101. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57102. this._rotated.addInPlace(this._pivotBackTranslation);
  57103. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57104. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57105. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57106. }
  57107. particle.position.x = 0.0;
  57108. particle.position.y = 0.0;
  57109. particle.position.z = 0.0;
  57110. particle.rotation.x = 0.0;
  57111. particle.rotation.y = 0.0;
  57112. particle.rotation.z = 0.0;
  57113. particle.rotationQuaternion = null;
  57114. particle.scaling.x = 1.0;
  57115. particle.scaling.y = 1.0;
  57116. particle.scaling.z = 1.0;
  57117. particle.uvs.x = 0.0;
  57118. particle.uvs.y = 0.0;
  57119. particle.uvs.z = 1.0;
  57120. particle.uvs.w = 1.0;
  57121. particle.pivot.x = 0.0;
  57122. particle.pivot.y = 0.0;
  57123. particle.pivot.z = 0.0;
  57124. particle.translateFromPivot = false;
  57125. particle.parentId = null;
  57126. };
  57127. /**
  57128. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57129. * @returns the SPS.
  57130. */
  57131. SolidParticleSystem.prototype.rebuildMesh = function () {
  57132. for (var p = 0; p < this.particles.length; p++) {
  57133. this._rebuildParticle(this.particles[p]);
  57134. }
  57135. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57136. return this;
  57137. };
  57138. /**
  57139. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57140. * This method calls `updateParticle()` for each particle of the SPS.
  57141. * For an animated SPS, it is usually called within the render loop.
  57142. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57143. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57144. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57145. * @returns the SPS.
  57146. */
  57147. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57148. if (start === void 0) { start = 0; }
  57149. if (end === void 0) { end = this.nbParticles - 1; }
  57150. if (update === void 0) { update = true; }
  57151. if (!this._updatable) {
  57152. return this;
  57153. }
  57154. // custom beforeUpdate
  57155. this.beforeUpdateParticles(start, end, update);
  57156. this._cam_axisX.x = 1.0;
  57157. this._cam_axisX.y = 0.0;
  57158. this._cam_axisX.z = 0.0;
  57159. this._cam_axisY.x = 0.0;
  57160. this._cam_axisY.y = 1.0;
  57161. this._cam_axisY.z = 0.0;
  57162. this._cam_axisZ.x = 0.0;
  57163. this._cam_axisZ.y = 0.0;
  57164. this._cam_axisZ.z = 1.0;
  57165. // cases when the World Matrix is to be computed first
  57166. if (this.billboard || this._depthSort) {
  57167. this.mesh.computeWorldMatrix(true);
  57168. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  57169. }
  57170. // if the particles will always face the camera
  57171. if (this.billboard) {
  57172. // compute the camera position and un-rotate it by the current mesh rotation
  57173. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  57174. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57175. this._cam_axisZ.normalize();
  57176. // same for camera up vector extracted from the cam view matrix
  57177. var view = this._camera.getViewMatrix(true);
  57178. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  57179. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57180. this._cam_axisY.normalize();
  57181. this._cam_axisX.normalize();
  57182. }
  57183. // if depthSort, compute the camera global position in the mesh local system
  57184. if (this._depthSort) {
  57185. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  57186. }
  57187. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57188. var idx = 0; // current position index in the global array positions32
  57189. var index = 0; // position start index in the global array positions32 of the current particle
  57190. var colidx = 0; // current color index in the global array colors32
  57191. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  57192. var uvidx = 0; // current uv index in the global array uvs32
  57193. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  57194. var pt = 0; // current index in the particle model shape
  57195. if (this.mesh.isFacetDataEnabled) {
  57196. this._computeBoundingBox = true;
  57197. }
  57198. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  57199. if (this._computeBoundingBox) {
  57200. if (start == 0 && end == this.nbParticles - 1) {
  57201. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57202. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57203. }
  57204. else {
  57205. if (this.mesh._boundingInfo) {
  57206. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  57207. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  57208. }
  57209. }
  57210. }
  57211. // particle loop
  57212. index = this.particles[start]._pos;
  57213. var vpos = (index / 3) | 0;
  57214. colorIndex = vpos * 4;
  57215. uvIndex = vpos * 2;
  57216. for (var p = start; p <= end; p++) {
  57217. this._particle = this.particles[p];
  57218. this._shape = this._particle._model._shape;
  57219. this._shapeUV = this._particle._model._shapeUV;
  57220. // call to custom user function to update the particle properties
  57221. this.updateParticle(this._particle);
  57222. // camera-particle distance for depth sorting
  57223. if (this._depthSort && this._depthSortParticles) {
  57224. var dsp = this.depthSortedParticles[p];
  57225. dsp.ind = this._particle._ind;
  57226. dsp.indicesLength = this._particle._model._indicesLength;
  57227. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  57228. }
  57229. // skip the computations for inactive or already invisible particles
  57230. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  57231. // increment indexes for the next particle
  57232. pt = this._shape.length;
  57233. index += pt * 3;
  57234. colorIndex += pt * 4;
  57235. uvIndex += pt * 2;
  57236. continue;
  57237. }
  57238. if (this._particle.isVisible) {
  57239. this._particle._stillInvisible = false; // un-mark permanent invisibility
  57240. this._particleHasParent = (this._particle.parentId !== null);
  57241. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  57242. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  57243. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  57244. // particle rotation matrix
  57245. if (this.billboard) {
  57246. this._particle.rotation.x = 0.0;
  57247. this._particle.rotation.y = 0.0;
  57248. }
  57249. if (this._computeParticleRotation || this.billboard) {
  57250. if (this._particle.rotationQuaternion) {
  57251. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57252. }
  57253. else {
  57254. this._yaw = this._particle.rotation.y;
  57255. this._pitch = this._particle.rotation.x;
  57256. this._roll = this._particle.rotation.z;
  57257. this._quaternionRotationYPR();
  57258. }
  57259. this._quaternionToRotationMatrix();
  57260. }
  57261. if (this._particleHasParent) {
  57262. this._parent = this.particles[this._particle.parentId];
  57263. 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];
  57264. 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];
  57265. 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];
  57266. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  57267. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  57268. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  57269. if (this._computeParticleRotation || this.billboard) {
  57270. 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];
  57271. 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];
  57272. 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];
  57273. 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];
  57274. 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];
  57275. 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];
  57276. 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];
  57277. 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];
  57278. 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];
  57279. }
  57280. }
  57281. else {
  57282. this._particle._globalPosition.x = this._particle.position.x;
  57283. this._particle._globalPosition.y = this._particle.position.y;
  57284. this._particle._globalPosition.z = this._particle.position.z;
  57285. if (this._computeParticleRotation || this.billboard) {
  57286. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  57287. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  57288. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  57289. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  57290. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  57291. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  57292. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  57293. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  57294. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  57295. }
  57296. }
  57297. if (this._particle.translateFromPivot) {
  57298. this._pivotBackTranslation.x = 0.0;
  57299. this._pivotBackTranslation.y = 0.0;
  57300. this._pivotBackTranslation.z = 0.0;
  57301. }
  57302. else {
  57303. this._pivotBackTranslation.x = this._scaledPivot.x;
  57304. this._pivotBackTranslation.y = this._scaledPivot.y;
  57305. this._pivotBackTranslation.z = this._scaledPivot.z;
  57306. }
  57307. // particle vertex loop
  57308. for (pt = 0; pt < this._shape.length; pt++) {
  57309. idx = index + pt * 3;
  57310. colidx = colorIndex + pt * 4;
  57311. uvidx = uvIndex + pt * 2;
  57312. this._vertex.x = this._shape[pt].x;
  57313. this._vertex.y = this._shape[pt].y;
  57314. this._vertex.z = this._shape[pt].z;
  57315. if (this._computeParticleVertex) {
  57316. this.updateParticleVertex(this._particle, this._vertex, pt);
  57317. }
  57318. // positions
  57319. this._vertex.x *= this._particle.scaling.x;
  57320. this._vertex.y *= this._particle.scaling.y;
  57321. this._vertex.z *= this._particle.scaling.z;
  57322. this._vertex.x -= this._scaledPivot.x;
  57323. this._vertex.y -= this._scaledPivot.y;
  57324. this._vertex.z -= this._scaledPivot.z;
  57325. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57326. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57327. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57328. this._rotated.x += this._pivotBackTranslation.x;
  57329. this._rotated.y += this._pivotBackTranslation.y;
  57330. this._rotated.z += this._pivotBackTranslation.z;
  57331. 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;
  57332. 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;
  57333. 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;
  57334. if (this._computeBoundingBox) {
  57335. if (this._positions32[idx] < this._minimum.x) {
  57336. this._minimum.x = this._positions32[idx];
  57337. }
  57338. if (this._positions32[idx] > this._maximum.x) {
  57339. this._maximum.x = this._positions32[idx];
  57340. }
  57341. if (this._positions32[idx + 1] < this._minimum.y) {
  57342. this._minimum.y = this._positions32[idx + 1];
  57343. }
  57344. if (this._positions32[idx + 1] > this._maximum.y) {
  57345. this._maximum.y = this._positions32[idx + 1];
  57346. }
  57347. if (this._positions32[idx + 2] < this._minimum.z) {
  57348. this._minimum.z = this._positions32[idx + 2];
  57349. }
  57350. if (this._positions32[idx + 2] > this._maximum.z) {
  57351. this._maximum.z = this._positions32[idx + 2];
  57352. }
  57353. }
  57354. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  57355. if (!this._computeParticleVertex) {
  57356. this._normal.x = this._fixedNormal32[idx];
  57357. this._normal.y = this._fixedNormal32[idx + 1];
  57358. this._normal.z = this._fixedNormal32[idx + 2];
  57359. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  57360. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  57361. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  57362. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57363. 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;
  57364. 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;
  57365. }
  57366. if (this._computeParticleColor && this._particle.color) {
  57367. this._colors32[colidx] = this._particle.color.r;
  57368. this._colors32[colidx + 1] = this._particle.color.g;
  57369. this._colors32[colidx + 2] = this._particle.color.b;
  57370. this._colors32[colidx + 3] = this._particle.color.a;
  57371. }
  57372. if (this._computeParticleTexture) {
  57373. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57374. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57375. }
  57376. }
  57377. }
  57378. else {
  57379. this._particle._stillInvisible = true; // mark the particle as invisible
  57380. for (pt = 0; pt < this._shape.length; pt++) {
  57381. idx = index + pt * 3;
  57382. colidx = colorIndex + pt * 4;
  57383. uvidx = uvIndex + pt * 2;
  57384. this._positions32[idx] = 0.0;
  57385. this._positions32[idx + 1] = 0.0;
  57386. this._positions32[idx + 2] = 0.0;
  57387. this._normals32[idx] = 0.0;
  57388. this._normals32[idx + 1] = 0.0;
  57389. this._normals32[idx + 2] = 0.0;
  57390. if (this._computeParticleColor && this._particle.color) {
  57391. this._colors32[colidx] = this._particle.color.r;
  57392. this._colors32[colidx + 1] = this._particle.color.g;
  57393. this._colors32[colidx + 2] = this._particle.color.b;
  57394. this._colors32[colidx + 3] = this._particle.color.a;
  57395. }
  57396. if (this._computeParticleTexture) {
  57397. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57398. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57399. }
  57400. }
  57401. }
  57402. // if the particle intersections must be computed : update the bbInfo
  57403. if (this._particlesIntersect) {
  57404. var bInfo = this._particle._boundingInfo;
  57405. var bBox = bInfo.boundingBox;
  57406. var bSphere = bInfo.boundingSphere;
  57407. if (!this._bSphereOnly) {
  57408. // place, scale and rotate the particle bbox within the SPS local system, then update it
  57409. for (var b = 0; b < bBox.vectors.length; b++) {
  57410. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  57411. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  57412. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  57413. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  57414. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  57415. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  57416. 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;
  57417. 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;
  57418. 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;
  57419. }
  57420. bBox._update(this.mesh._worldMatrix);
  57421. }
  57422. // place and scale the particle bouding sphere in the SPS local system, then update it
  57423. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  57424. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  57425. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  57426. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  57427. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  57428. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  57429. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  57430. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  57431. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  57432. 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));
  57433. bSphere._update(this.mesh._worldMatrix);
  57434. }
  57435. // increment indexes for the next particle
  57436. index = idx + 3;
  57437. colorIndex = colidx + 4;
  57438. uvIndex = uvidx + 2;
  57439. }
  57440. // if the VBO must be updated
  57441. if (update) {
  57442. if (this._computeParticleColor) {
  57443. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57444. }
  57445. if (this._computeParticleTexture) {
  57446. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57447. }
  57448. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57449. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  57450. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  57451. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57452. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  57453. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  57454. for (var i = 0; i < this._normals32.length; i++) {
  57455. this._fixedNormal32[i] = this._normals32[i];
  57456. }
  57457. }
  57458. if (!this.mesh.areNormalsFrozen) {
  57459. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57460. }
  57461. }
  57462. if (this._depthSort && this._depthSortParticles) {
  57463. this.depthSortedParticles.sort(this._depthSortFunction);
  57464. var dspl = this.depthSortedParticles.length;
  57465. var sorted = 0;
  57466. var lind = 0;
  57467. var sind = 0;
  57468. var sid = 0;
  57469. for (sorted = 0; sorted < dspl; sorted++) {
  57470. lind = this.depthSortedParticles[sorted].indicesLength;
  57471. sind = this.depthSortedParticles[sorted].ind;
  57472. for (var i = 0; i < lind; i++) {
  57473. this._indices32[sid] = this._indices[sind + i];
  57474. sid++;
  57475. }
  57476. }
  57477. this.mesh.updateIndices(this._indices32);
  57478. }
  57479. }
  57480. if (this._computeBoundingBox) {
  57481. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57482. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57483. }
  57484. this.afterUpdateParticles(start, end, update);
  57485. return this;
  57486. };
  57487. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57488. this._halfroll = this._roll * 0.5;
  57489. this._halfpitch = this._pitch * 0.5;
  57490. this._halfyaw = this._yaw * 0.5;
  57491. this._sinRoll = Math.sin(this._halfroll);
  57492. this._cosRoll = Math.cos(this._halfroll);
  57493. this._sinPitch = Math.sin(this._halfpitch);
  57494. this._cosPitch = Math.cos(this._halfpitch);
  57495. this._sinYaw = Math.sin(this._halfyaw);
  57496. this._cosYaw = Math.cos(this._halfyaw);
  57497. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  57498. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  57499. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  57500. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  57501. };
  57502. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57503. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57504. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57505. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57506. this._rotMatrix.m[3] = 0;
  57507. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57508. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57509. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57510. this._rotMatrix.m[7] = 0;
  57511. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57512. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57513. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57514. this._rotMatrix.m[11] = 0;
  57515. this._rotMatrix.m[12] = 0;
  57516. this._rotMatrix.m[13] = 0;
  57517. this._rotMatrix.m[14] = 0;
  57518. this._rotMatrix.m[15] = 1.0;
  57519. };
  57520. /**
  57521. * Disposes the SPS.
  57522. */
  57523. SolidParticleSystem.prototype.dispose = function () {
  57524. this.mesh.dispose();
  57525. this.vars = null;
  57526. // drop references to internal big arrays for the GC
  57527. this._positions = null;
  57528. this._indices = null;
  57529. this._normals = null;
  57530. this._uvs = null;
  57531. this._colors = null;
  57532. this._indices32 = null;
  57533. this._positions32 = null;
  57534. this._normals32 = null;
  57535. this._fixedNormal32 = null;
  57536. this._uvs32 = null;
  57537. this._colors32 = null;
  57538. this.pickedParticles = null;
  57539. };
  57540. /**
  57541. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57542. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57543. * @returns the SPS.
  57544. */
  57545. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57546. if (!this._isVisibilityBoxLocked) {
  57547. this.mesh.refreshBoundingInfo();
  57548. }
  57549. return this;
  57550. };
  57551. /**
  57552. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57553. * @param size the size (float) of the visibility box
  57554. * note : this doesn't lock the SPS mesh bounding box.
  57555. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57556. */
  57557. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57558. var vis = size / 2;
  57559. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57560. };
  57561. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57562. /**
  57563. * Gets whether the SPS as always visible or not
  57564. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57565. */
  57566. get: function () {
  57567. return this._alwaysVisible;
  57568. },
  57569. /**
  57570. * Sets the SPS as always visible or not
  57571. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57572. */
  57573. set: function (val) {
  57574. this._alwaysVisible = val;
  57575. this.mesh.alwaysSelectAsActiveMesh = val;
  57576. },
  57577. enumerable: true,
  57578. configurable: true
  57579. });
  57580. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57581. /**
  57582. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57583. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57584. */
  57585. get: function () {
  57586. return this._isVisibilityBoxLocked;
  57587. },
  57588. /**
  57589. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57590. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57591. */
  57592. set: function (val) {
  57593. this._isVisibilityBoxLocked = val;
  57594. var boundingInfo = this.mesh.getBoundingInfo();
  57595. boundingInfo.isLocked = val;
  57596. },
  57597. enumerable: true,
  57598. configurable: true
  57599. });
  57600. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57601. /**
  57602. * Gets if `setParticles()` computes the particle rotations or not.
  57603. * Default value : true. The SPS is faster when it's set to false.
  57604. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57605. */
  57606. get: function () {
  57607. return this._computeParticleRotation;
  57608. },
  57609. /**
  57610. * Tells to `setParticles()` to compute the particle rotations or not.
  57611. * Default value : true. The SPS is faster when it's set to false.
  57612. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57613. */
  57614. set: function (val) {
  57615. this._computeParticleRotation = val;
  57616. },
  57617. enumerable: true,
  57618. configurable: true
  57619. });
  57620. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57621. /**
  57622. * Gets if `setParticles()` computes the particle colors or not.
  57623. * Default value : true. The SPS is faster when it's set to false.
  57624. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57625. */
  57626. get: function () {
  57627. return this._computeParticleColor;
  57628. },
  57629. /**
  57630. * Tells to `setParticles()` to compute the particle colors or not.
  57631. * Default value : true. The SPS is faster when it's set to false.
  57632. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57633. */
  57634. set: function (val) {
  57635. this._computeParticleColor = val;
  57636. },
  57637. enumerable: true,
  57638. configurable: true
  57639. });
  57640. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57641. /**
  57642. * Gets if `setParticles()` computes the particle textures or not.
  57643. * Default value : true. The SPS is faster when it's set to false.
  57644. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57645. */
  57646. get: function () {
  57647. return this._computeParticleTexture;
  57648. },
  57649. set: function (val) {
  57650. this._computeParticleTexture = val;
  57651. },
  57652. enumerable: true,
  57653. configurable: true
  57654. });
  57655. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57656. /**
  57657. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  57658. * Default value : false. The SPS is faster when it's set to false.
  57659. * Note : the particle custom vertex positions aren't stored values.
  57660. */
  57661. get: function () {
  57662. return this._computeParticleVertex;
  57663. },
  57664. /**
  57665. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57666. * Default value : false. The SPS is faster when it's set to false.
  57667. * Note : the particle custom vertex positions aren't stored values.
  57668. */
  57669. set: function (val) {
  57670. this._computeParticleVertex = val;
  57671. },
  57672. enumerable: true,
  57673. configurable: true
  57674. });
  57675. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57676. /**
  57677. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  57678. */
  57679. get: function () {
  57680. return this._computeBoundingBox;
  57681. },
  57682. /**
  57683. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57684. */
  57685. set: function (val) {
  57686. this._computeBoundingBox = val;
  57687. },
  57688. enumerable: true,
  57689. configurable: true
  57690. });
  57691. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  57692. /**
  57693. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  57694. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57695. * Default : `true`
  57696. */
  57697. get: function () {
  57698. return this._depthSortParticles;
  57699. },
  57700. /**
  57701. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  57702. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  57703. * Default : `true`
  57704. */
  57705. set: function (val) {
  57706. this._depthSortParticles = val;
  57707. },
  57708. enumerable: true,
  57709. configurable: true
  57710. });
  57711. // =======================================================================
  57712. // Particle behavior logic
  57713. // these following methods may be overwritten by the user to fit his needs
  57714. /**
  57715. * This function does nothing. It may be overwritten to set all the particle first values.
  57716. * The SPS doesn't call this function, you may have to call it by your own.
  57717. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57718. */
  57719. SolidParticleSystem.prototype.initParticles = function () {
  57720. };
  57721. /**
  57722. * This function does nothing. It may be overwritten to recycle a particle.
  57723. * The SPS doesn't call this function, you may have to call it by your own.
  57724. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57725. * @param particle The particle to recycle
  57726. * @returns the recycled particle
  57727. */
  57728. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57729. return particle;
  57730. };
  57731. /**
  57732. * Updates a particle : this function should be overwritten by the user.
  57733. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57734. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57735. * @example : just set a particle position or velocity and recycle conditions
  57736. * @param particle The particle to update
  57737. * @returns the updated particle
  57738. */
  57739. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57740. return particle;
  57741. };
  57742. /**
  57743. * Updates a vertex of a particle : it can be overwritten by the user.
  57744. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57745. * @param particle the current particle
  57746. * @param vertex the current index of the current particle
  57747. * @param pt the index of the current vertex in the particle shape
  57748. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57749. * @example : just set a vertex particle position
  57750. * @returns the updated vertex
  57751. */
  57752. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57753. return vertex;
  57754. };
  57755. /**
  57756. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57757. * This does nothing and may be overwritten by the user.
  57758. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57759. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57760. * @param update the boolean update value actually passed to setParticles()
  57761. */
  57762. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57763. };
  57764. /**
  57765. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57766. * This will be passed three parameters.
  57767. * This does nothing and may be overwritten by the user.
  57768. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57769. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57770. * @param update the boolean update value actually passed to setParticles()
  57771. */
  57772. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  57773. };
  57774. return SolidParticleSystem;
  57775. }());
  57776. BABYLON.SolidParticleSystem = SolidParticleSystem;
  57777. })(BABYLON || (BABYLON = {}));
  57778. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  57779. "use strict";
  57780. var BABYLON;
  57781. (function (BABYLON) {
  57782. var ShaderMaterial = /** @class */ (function (_super) {
  57783. __extends(ShaderMaterial, _super);
  57784. function ShaderMaterial(name, scene, shaderPath, options) {
  57785. var _this = _super.call(this, name, scene) || this;
  57786. _this._textures = {};
  57787. _this._textureArrays = {};
  57788. _this._floats = {};
  57789. _this._ints = {};
  57790. _this._floatsArrays = {};
  57791. _this._colors3 = {};
  57792. _this._colors3Arrays = {};
  57793. _this._colors4 = {};
  57794. _this._vectors2 = {};
  57795. _this._vectors3 = {};
  57796. _this._vectors4 = {};
  57797. _this._matrices = {};
  57798. _this._matrices3x3 = {};
  57799. _this._matrices2x2 = {};
  57800. _this._vectors2Arrays = {};
  57801. _this._vectors3Arrays = {};
  57802. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57803. _this._shaderPath = shaderPath;
  57804. options.needAlphaBlending = options.needAlphaBlending || false;
  57805. options.needAlphaTesting = options.needAlphaTesting || false;
  57806. options.attributes = options.attributes || ["position", "normal", "uv"];
  57807. options.uniforms = options.uniforms || ["worldViewProjection"];
  57808. options.uniformBuffers = options.uniformBuffers || [];
  57809. options.samplers = options.samplers || [];
  57810. options.defines = options.defines || [];
  57811. _this._options = options;
  57812. return _this;
  57813. }
  57814. ShaderMaterial.prototype.getClassName = function () {
  57815. return "ShaderMaterial";
  57816. };
  57817. ShaderMaterial.prototype.needAlphaBlending = function () {
  57818. return this._options.needAlphaBlending;
  57819. };
  57820. ShaderMaterial.prototype.needAlphaTesting = function () {
  57821. return this._options.needAlphaTesting;
  57822. };
  57823. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57824. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57825. this._options.uniforms.push(uniformName);
  57826. }
  57827. };
  57828. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57829. if (this._options.samplers.indexOf(name) === -1) {
  57830. this._options.samplers.push(name);
  57831. }
  57832. this._textures[name] = texture;
  57833. return this;
  57834. };
  57835. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57836. if (this._options.samplers.indexOf(name) === -1) {
  57837. this._options.samplers.push(name);
  57838. }
  57839. this._checkUniform(name);
  57840. this._textureArrays[name] = textures;
  57841. return this;
  57842. };
  57843. ShaderMaterial.prototype.setFloat = function (name, value) {
  57844. this._checkUniform(name);
  57845. this._floats[name] = value;
  57846. return this;
  57847. };
  57848. ShaderMaterial.prototype.setInt = function (name, value) {
  57849. this._checkUniform(name);
  57850. this._ints[name] = value;
  57851. return this;
  57852. };
  57853. ShaderMaterial.prototype.setFloats = function (name, value) {
  57854. this._checkUniform(name);
  57855. this._floatsArrays[name] = value;
  57856. return this;
  57857. };
  57858. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57859. this._checkUniform(name);
  57860. this._colors3[name] = value;
  57861. return this;
  57862. };
  57863. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57864. this._checkUniform(name);
  57865. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57866. color.toArray(arr, arr.length);
  57867. return arr;
  57868. }, []);
  57869. return this;
  57870. };
  57871. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57872. this._checkUniform(name);
  57873. this._colors4[name] = value;
  57874. return this;
  57875. };
  57876. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57877. this._checkUniform(name);
  57878. this._vectors2[name] = value;
  57879. return this;
  57880. };
  57881. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57882. this._checkUniform(name);
  57883. this._vectors3[name] = value;
  57884. return this;
  57885. };
  57886. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57887. this._checkUniform(name);
  57888. this._vectors4[name] = value;
  57889. return this;
  57890. };
  57891. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57892. this._checkUniform(name);
  57893. this._matrices[name] = value;
  57894. return this;
  57895. };
  57896. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57897. this._checkUniform(name);
  57898. this._matrices3x3[name] = value;
  57899. return this;
  57900. };
  57901. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57902. this._checkUniform(name);
  57903. this._matrices2x2[name] = value;
  57904. return this;
  57905. };
  57906. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57907. this._checkUniform(name);
  57908. this._vectors2Arrays[name] = value;
  57909. return this;
  57910. };
  57911. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57912. this._checkUniform(name);
  57913. this._vectors3Arrays[name] = value;
  57914. return this;
  57915. };
  57916. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57917. if (!mesh) {
  57918. return true;
  57919. }
  57920. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57921. return false;
  57922. }
  57923. return false;
  57924. };
  57925. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57926. var scene = this.getScene();
  57927. var engine = scene.getEngine();
  57928. if (!this.checkReadyOnEveryCall) {
  57929. if (this._renderId === scene.getRenderId()) {
  57930. if (this._checkCache(scene, mesh, useInstances)) {
  57931. return true;
  57932. }
  57933. }
  57934. }
  57935. // Instances
  57936. var defines = [];
  57937. var attribs = [];
  57938. var fallbacks = new BABYLON.EffectFallbacks();
  57939. if (useInstances) {
  57940. defines.push("#define INSTANCES");
  57941. }
  57942. for (var index = 0; index < this._options.defines.length; index++) {
  57943. defines.push(this._options.defines[index]);
  57944. }
  57945. for (var index = 0; index < this._options.attributes.length; index++) {
  57946. attribs.push(this._options.attributes[index]);
  57947. }
  57948. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57949. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57950. defines.push("#define VERTEXCOLOR");
  57951. }
  57952. // Bones
  57953. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57954. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57955. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57956. if (mesh.numBoneInfluencers > 4) {
  57957. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57958. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57959. }
  57960. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57961. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57962. fallbacks.addCPUSkinningFallback(0, mesh);
  57963. if (this._options.uniforms.indexOf("mBones") === -1) {
  57964. this._options.uniforms.push("mBones");
  57965. }
  57966. }
  57967. else {
  57968. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57969. }
  57970. // Textures
  57971. for (var name in this._textures) {
  57972. if (!this._textures[name].isReady()) {
  57973. return false;
  57974. }
  57975. }
  57976. // Alpha test
  57977. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57978. defines.push("#define ALPHATEST");
  57979. }
  57980. var previousEffect = this._effect;
  57981. var join = defines.join("\n");
  57982. this._effect = engine.createEffect(this._shaderPath, {
  57983. attributes: attribs,
  57984. uniformsNames: this._options.uniforms,
  57985. uniformBuffersNames: this._options.uniformBuffers,
  57986. samplers: this._options.samplers,
  57987. defines: join,
  57988. fallbacks: fallbacks,
  57989. onCompiled: this.onCompiled,
  57990. onError: this.onError
  57991. }, engine);
  57992. if (!this._effect.isReady()) {
  57993. return false;
  57994. }
  57995. if (previousEffect !== this._effect) {
  57996. scene.resetCachedMaterial();
  57997. }
  57998. this._renderId = scene.getRenderId();
  57999. return true;
  58000. };
  58001. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58002. var scene = this.getScene();
  58003. if (!this._effect) {
  58004. return;
  58005. }
  58006. if (this._options.uniforms.indexOf("world") !== -1) {
  58007. this._effect.setMatrix("world", world);
  58008. }
  58009. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58010. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58011. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58012. }
  58013. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58014. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58015. }
  58016. };
  58017. ShaderMaterial.prototype.bind = function (world, mesh) {
  58018. // Std values
  58019. this.bindOnlyWorldMatrix(world);
  58020. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58021. if (this._options.uniforms.indexOf("view") !== -1) {
  58022. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58023. }
  58024. if (this._options.uniforms.indexOf("projection") !== -1) {
  58025. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58026. }
  58027. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58028. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58029. }
  58030. // Bones
  58031. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58032. var name;
  58033. // Texture
  58034. for (name in this._textures) {
  58035. this._effect.setTexture(name, this._textures[name]);
  58036. }
  58037. // Texture arrays
  58038. for (name in this._textureArrays) {
  58039. this._effect.setTextureArray(name, this._textureArrays[name]);
  58040. }
  58041. // Int
  58042. for (name in this._ints) {
  58043. this._effect.setInt(name, this._ints[name]);
  58044. }
  58045. // Float
  58046. for (name in this._floats) {
  58047. this._effect.setFloat(name, this._floats[name]);
  58048. }
  58049. // Floats
  58050. for (name in this._floatsArrays) {
  58051. this._effect.setArray(name, this._floatsArrays[name]);
  58052. }
  58053. // Color3
  58054. for (name in this._colors3) {
  58055. this._effect.setColor3(name, this._colors3[name]);
  58056. }
  58057. for (name in this._colors3Arrays) {
  58058. this._effect.setArray3(name, this._colors3Arrays[name]);
  58059. }
  58060. // Color4
  58061. for (name in this._colors4) {
  58062. var color = this._colors4[name];
  58063. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58064. }
  58065. // Vector2
  58066. for (name in this._vectors2) {
  58067. this._effect.setVector2(name, this._vectors2[name]);
  58068. }
  58069. // Vector3
  58070. for (name in this._vectors3) {
  58071. this._effect.setVector3(name, this._vectors3[name]);
  58072. }
  58073. // Vector4
  58074. for (name in this._vectors4) {
  58075. this._effect.setVector4(name, this._vectors4[name]);
  58076. }
  58077. // Matrix
  58078. for (name in this._matrices) {
  58079. this._effect.setMatrix(name, this._matrices[name]);
  58080. }
  58081. // Matrix 3x3
  58082. for (name in this._matrices3x3) {
  58083. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58084. }
  58085. // Matrix 2x2
  58086. for (name in this._matrices2x2) {
  58087. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58088. }
  58089. // Vector2Array
  58090. for (name in this._vectors2Arrays) {
  58091. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58092. }
  58093. // Vector3Array
  58094. for (name in this._vectors3Arrays) {
  58095. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58096. }
  58097. }
  58098. this._afterBind(mesh);
  58099. };
  58100. ShaderMaterial.prototype.getActiveTextures = function () {
  58101. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58102. for (var name in this._textures) {
  58103. activeTextures.push(this._textures[name]);
  58104. }
  58105. for (var name in this._textureArrays) {
  58106. var array = this._textureArrays[name];
  58107. for (var index = 0; index < array.length; index++) {
  58108. activeTextures.push(array[index]);
  58109. }
  58110. }
  58111. return activeTextures;
  58112. };
  58113. ShaderMaterial.prototype.hasTexture = function (texture) {
  58114. if (_super.prototype.hasTexture.call(this, texture)) {
  58115. return true;
  58116. }
  58117. for (var name in this._textures) {
  58118. if (this._textures[name] === texture) {
  58119. return true;
  58120. }
  58121. }
  58122. for (var name in this._textureArrays) {
  58123. var array = this._textureArrays[name];
  58124. for (var index = 0; index < array.length; index++) {
  58125. if (array[index] === texture) {
  58126. return true;
  58127. }
  58128. }
  58129. }
  58130. return false;
  58131. };
  58132. ShaderMaterial.prototype.clone = function (name) {
  58133. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58134. return newShaderMaterial;
  58135. };
  58136. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58137. if (forceDisposeTextures) {
  58138. var name;
  58139. for (name in this._textures) {
  58140. this._textures[name].dispose();
  58141. }
  58142. for (name in this._textureArrays) {
  58143. var array = this._textureArrays[name];
  58144. for (var index = 0; index < array.length; index++) {
  58145. array[index].dispose();
  58146. }
  58147. }
  58148. }
  58149. this._textures = {};
  58150. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58151. };
  58152. ShaderMaterial.prototype.serialize = function () {
  58153. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58154. serializationObject.customType = "BABYLON.ShaderMaterial";
  58155. serializationObject.options = this._options;
  58156. serializationObject.shaderPath = this._shaderPath;
  58157. var name;
  58158. // Texture
  58159. serializationObject.textures = {};
  58160. for (name in this._textures) {
  58161. serializationObject.textures[name] = this._textures[name].serialize();
  58162. }
  58163. // Texture arrays
  58164. serializationObject.textureArrays = {};
  58165. for (name in this._textureArrays) {
  58166. serializationObject.textureArrays[name] = [];
  58167. var array = this._textureArrays[name];
  58168. for (var index = 0; index < array.length; index++) {
  58169. serializationObject.textureArrays[name].push(array[index].serialize());
  58170. }
  58171. }
  58172. // Float
  58173. serializationObject.floats = {};
  58174. for (name in this._floats) {
  58175. serializationObject.floats[name] = this._floats[name];
  58176. }
  58177. // Float s
  58178. serializationObject.FloatArrays = {};
  58179. for (name in this._floatsArrays) {
  58180. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58181. }
  58182. // Color3
  58183. serializationObject.colors3 = {};
  58184. for (name in this._colors3) {
  58185. serializationObject.colors3[name] = this._colors3[name].asArray();
  58186. }
  58187. // Color3 array
  58188. serializationObject.colors3Arrays = {};
  58189. for (name in this._colors3Arrays) {
  58190. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58191. }
  58192. // Color4
  58193. serializationObject.colors4 = {};
  58194. for (name in this._colors4) {
  58195. serializationObject.colors4[name] = this._colors4[name].asArray();
  58196. }
  58197. // Vector2
  58198. serializationObject.vectors2 = {};
  58199. for (name in this._vectors2) {
  58200. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58201. }
  58202. // Vector3
  58203. serializationObject.vectors3 = {};
  58204. for (name in this._vectors3) {
  58205. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58206. }
  58207. // Vector4
  58208. serializationObject.vectors4 = {};
  58209. for (name in this._vectors4) {
  58210. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58211. }
  58212. // Matrix
  58213. serializationObject.matrices = {};
  58214. for (name in this._matrices) {
  58215. serializationObject.matrices[name] = this._matrices[name].asArray();
  58216. }
  58217. // Matrix 3x3
  58218. serializationObject.matrices3x3 = {};
  58219. for (name in this._matrices3x3) {
  58220. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58221. }
  58222. // Matrix 2x2
  58223. serializationObject.matrices2x2 = {};
  58224. for (name in this._matrices2x2) {
  58225. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58226. }
  58227. // Vector2Array
  58228. serializationObject.vectors2Arrays = {};
  58229. for (name in this._vectors2Arrays) {
  58230. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58231. }
  58232. // Vector3Array
  58233. serializationObject.vectors3Arrays = {};
  58234. for (name in this._vectors3Arrays) {
  58235. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58236. }
  58237. return serializationObject;
  58238. };
  58239. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58240. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58241. var name;
  58242. // Texture
  58243. for (name in source.textures) {
  58244. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58245. }
  58246. // Texture arrays
  58247. for (name in source.textureArrays) {
  58248. var array = source.textureArrays[name];
  58249. var textureArray = new Array();
  58250. for (var index = 0; index < array.length; index++) {
  58251. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58252. }
  58253. material.setTextureArray(name, textureArray);
  58254. }
  58255. // Float
  58256. for (name in source.floats) {
  58257. material.setFloat(name, source.floats[name]);
  58258. }
  58259. // Float s
  58260. for (name in source.floatsArrays) {
  58261. material.setFloats(name, source.floatsArrays[name]);
  58262. }
  58263. // Color3
  58264. for (name in source.colors3) {
  58265. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58266. }
  58267. // Color3 arrays
  58268. for (name in source.colors3Arrays) {
  58269. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58270. if (i % 3 === 0) {
  58271. arr.push([num]);
  58272. }
  58273. else {
  58274. arr[arr.length - 1].push(num);
  58275. }
  58276. return arr;
  58277. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58278. material.setColor3Array(name, colors);
  58279. }
  58280. // Color4
  58281. for (name in source.colors4) {
  58282. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58283. }
  58284. // Vector2
  58285. for (name in source.vectors2) {
  58286. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58287. }
  58288. // Vector3
  58289. for (name in source.vectors3) {
  58290. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58291. }
  58292. // Vector4
  58293. for (name in source.vectors4) {
  58294. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58295. }
  58296. // Matrix
  58297. for (name in source.matrices) {
  58298. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58299. }
  58300. // Matrix 3x3
  58301. for (name in source.matrices3x3) {
  58302. material.setMatrix3x3(name, source.matrices3x3[name]);
  58303. }
  58304. // Matrix 2x2
  58305. for (name in source.matrices2x2) {
  58306. material.setMatrix2x2(name, source.matrices2x2[name]);
  58307. }
  58308. // Vector2Array
  58309. for (name in source.vectors2Arrays) {
  58310. material.setArray2(name, source.vectors2Arrays[name]);
  58311. }
  58312. // Vector3Array
  58313. for (name in source.vectors3Arrays) {
  58314. material.setArray3(name, source.vectors3Arrays[name]);
  58315. }
  58316. return material;
  58317. };
  58318. return ShaderMaterial;
  58319. }(BABYLON.Material));
  58320. BABYLON.ShaderMaterial = ShaderMaterial;
  58321. })(BABYLON || (BABYLON = {}));
  58322. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58323. "use strict";
  58324. var BABYLON;
  58325. (function (BABYLON) {
  58326. var GroundMesh = /** @class */ (function (_super) {
  58327. __extends(GroundMesh, _super);
  58328. function GroundMesh(name, scene) {
  58329. var _this = _super.call(this, name, scene) || this;
  58330. _this.generateOctree = false;
  58331. return _this;
  58332. }
  58333. GroundMesh.prototype.getClassName = function () {
  58334. return "GroundMesh";
  58335. };
  58336. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58337. get: function () {
  58338. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58339. },
  58340. enumerable: true,
  58341. configurable: true
  58342. });
  58343. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58344. get: function () {
  58345. return this._subdivisionsX;
  58346. },
  58347. enumerable: true,
  58348. configurable: true
  58349. });
  58350. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58351. get: function () {
  58352. return this._subdivisionsY;
  58353. },
  58354. enumerable: true,
  58355. configurable: true
  58356. });
  58357. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58358. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58359. this._subdivisionsX = chunksCount;
  58360. this._subdivisionsY = chunksCount;
  58361. this.subdivide(chunksCount);
  58362. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58363. };
  58364. /**
  58365. * Returns a height (y) value in the Worl system :
  58366. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58367. * Returns the ground y position if (x, z) are outside the ground surface.
  58368. */
  58369. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58370. var world = this.getWorldMatrix();
  58371. var invMat = BABYLON.Tmp.Matrix[5];
  58372. world.invertToRef(invMat);
  58373. var tmpVect = BABYLON.Tmp.Vector3[8];
  58374. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58375. x = tmpVect.x;
  58376. z = tmpVect.z;
  58377. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58378. return this.position.y;
  58379. }
  58380. if (!this._heightQuads || this._heightQuads.length == 0) {
  58381. this._initHeightQuads();
  58382. this._computeHeightQuads();
  58383. }
  58384. var facet = this._getFacetAt(x, z);
  58385. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58386. // return y in the World system
  58387. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58388. return tmpVect.y;
  58389. };
  58390. /**
  58391. * Returns a normalized vector (Vector3) orthogonal to the ground
  58392. * at the ground coordinates (x, z) expressed in the World system.
  58393. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58394. */
  58395. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58396. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58397. this.getNormalAtCoordinatesToRef(x, z, normal);
  58398. return normal;
  58399. };
  58400. /**
  58401. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58402. * at the ground coordinates (x, z) expressed in the World system.
  58403. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58404. * Returns the GroundMesh.
  58405. */
  58406. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58407. var world = this.getWorldMatrix();
  58408. var tmpMat = BABYLON.Tmp.Matrix[5];
  58409. world.invertToRef(tmpMat);
  58410. var tmpVect = BABYLON.Tmp.Vector3[8];
  58411. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58412. x = tmpVect.x;
  58413. z = tmpVect.z;
  58414. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58415. return this;
  58416. }
  58417. if (!this._heightQuads || this._heightQuads.length == 0) {
  58418. this._initHeightQuads();
  58419. this._computeHeightQuads();
  58420. }
  58421. var facet = this._getFacetAt(x, z);
  58422. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58423. return this;
  58424. };
  58425. /**
  58426. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58427. * if the ground has been updated.
  58428. * This can be used in the render loop.
  58429. * Returns the GroundMesh.
  58430. */
  58431. GroundMesh.prototype.updateCoordinateHeights = function () {
  58432. if (!this._heightQuads || this._heightQuads.length == 0) {
  58433. this._initHeightQuads();
  58434. }
  58435. this._computeHeightQuads();
  58436. return this;
  58437. };
  58438. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58439. GroundMesh.prototype._getFacetAt = function (x, z) {
  58440. // retrieve col and row from x, z coordinates in the ground local system
  58441. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58442. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58443. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58444. var facet;
  58445. if (z < quad.slope.x * x + quad.slope.y) {
  58446. facet = quad.facet1;
  58447. }
  58448. else {
  58449. facet = quad.facet2;
  58450. }
  58451. return facet;
  58452. };
  58453. // Creates and populates the heightMap array with "facet" elements :
  58454. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58455. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58456. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58457. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58458. // Returns the GroundMesh.
  58459. GroundMesh.prototype._initHeightQuads = function () {
  58460. var subdivisionsX = this._subdivisionsX;
  58461. var subdivisionsY = this._subdivisionsY;
  58462. this._heightQuads = new Array();
  58463. for (var row = 0; row < subdivisionsY; row++) {
  58464. for (var col = 0; col < subdivisionsX; col++) {
  58465. 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) };
  58466. this._heightQuads[row * subdivisionsX + col] = quad;
  58467. }
  58468. }
  58469. return this;
  58470. };
  58471. // Compute each quad element values and update the the heightMap array :
  58472. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58473. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58474. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58475. // Returns the GroundMesh.
  58476. GroundMesh.prototype._computeHeightQuads = function () {
  58477. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58478. if (!positions) {
  58479. return this;
  58480. }
  58481. var v1 = BABYLON.Tmp.Vector3[3];
  58482. var v2 = BABYLON.Tmp.Vector3[2];
  58483. var v3 = BABYLON.Tmp.Vector3[1];
  58484. var v4 = BABYLON.Tmp.Vector3[0];
  58485. var v1v2 = BABYLON.Tmp.Vector3[4];
  58486. var v1v3 = BABYLON.Tmp.Vector3[5];
  58487. var v1v4 = BABYLON.Tmp.Vector3[6];
  58488. var norm1 = BABYLON.Tmp.Vector3[7];
  58489. var norm2 = BABYLON.Tmp.Vector3[8];
  58490. var i = 0;
  58491. var j = 0;
  58492. var k = 0;
  58493. var cd = 0; // 2D slope coefficient : z = cd * x + h
  58494. var h = 0;
  58495. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  58496. var d2 = 0;
  58497. var subdivisionsX = this._subdivisionsX;
  58498. var subdivisionsY = this._subdivisionsY;
  58499. for (var row = 0; row < subdivisionsY; row++) {
  58500. for (var col = 0; col < subdivisionsX; col++) {
  58501. i = col * 3;
  58502. j = row * (subdivisionsX + 1) * 3;
  58503. k = (row + 1) * (subdivisionsX + 1) * 3;
  58504. v1.x = positions[j + i];
  58505. v1.y = positions[j + i + 1];
  58506. v1.z = positions[j + i + 2];
  58507. v2.x = positions[j + i + 3];
  58508. v2.y = positions[j + i + 4];
  58509. v2.z = positions[j + i + 5];
  58510. v3.x = positions[k + i];
  58511. v3.y = positions[k + i + 1];
  58512. v3.z = positions[k + i + 2];
  58513. v4.x = positions[k + i + 3];
  58514. v4.y = positions[k + i + 4];
  58515. v4.z = positions[k + i + 5];
  58516. // 2D slope V1V4
  58517. cd = (v4.z - v1.z) / (v4.x - v1.x);
  58518. h = v1.z - cd * v1.x; // v1 belongs to the slope
  58519. // facet equations :
  58520. // we compute each facet normal vector
  58521. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  58522. // we compute the value d by applying the equation to v1 which belongs to the plane
  58523. // then we store the facet equation in a Vector4
  58524. v2.subtractToRef(v1, v1v2);
  58525. v3.subtractToRef(v1, v1v3);
  58526. v4.subtractToRef(v1, v1v4);
  58527. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  58528. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  58529. norm1.normalize();
  58530. norm2.normalize();
  58531. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  58532. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  58533. var quad = this._heightQuads[row * subdivisionsX + col];
  58534. quad.slope.copyFromFloats(cd, h);
  58535. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  58536. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  58537. }
  58538. }
  58539. return this;
  58540. };
  58541. GroundMesh.prototype.serialize = function (serializationObject) {
  58542. _super.prototype.serialize.call(this, serializationObject);
  58543. serializationObject.subdivisionsX = this._subdivisionsX;
  58544. serializationObject.subdivisionsY = this._subdivisionsY;
  58545. serializationObject.minX = this._minX;
  58546. serializationObject.maxX = this._maxX;
  58547. serializationObject.minZ = this._minZ;
  58548. serializationObject.maxZ = this._maxZ;
  58549. serializationObject.width = this._width;
  58550. serializationObject.height = this._height;
  58551. };
  58552. GroundMesh.Parse = function (parsedMesh, scene) {
  58553. var result = new GroundMesh(parsedMesh.name, scene);
  58554. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  58555. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  58556. result._minX = parsedMesh.minX;
  58557. result._maxX = parsedMesh.maxX;
  58558. result._minZ = parsedMesh.minZ;
  58559. result._maxZ = parsedMesh.maxZ;
  58560. result._width = parsedMesh.width;
  58561. result._height = parsedMesh.height;
  58562. return result;
  58563. };
  58564. return GroundMesh;
  58565. }(BABYLON.Mesh));
  58566. BABYLON.GroundMesh = GroundMesh;
  58567. })(BABYLON || (BABYLON = {}));
  58568. //# sourceMappingURL=babylon.groundMesh.js.map
  58569. "use strict";
  58570. var BABYLON;
  58571. (function (BABYLON) {
  58572. /**
  58573. * Creates an instance based on a source mesh.
  58574. */
  58575. var InstancedMesh = /** @class */ (function (_super) {
  58576. __extends(InstancedMesh, _super);
  58577. function InstancedMesh(name, source) {
  58578. var _this = _super.call(this, name, source.getScene()) || this;
  58579. source.instances.push(_this);
  58580. _this._sourceMesh = source;
  58581. _this.position.copyFrom(source.position);
  58582. _this.rotation.copyFrom(source.rotation);
  58583. _this.scaling.copyFrom(source.scaling);
  58584. if (source.rotationQuaternion) {
  58585. _this.rotationQuaternion = source.rotationQuaternion.clone();
  58586. }
  58587. _this.infiniteDistance = source.infiniteDistance;
  58588. _this.setPivotMatrix(source.getPivotMatrix());
  58589. _this.refreshBoundingInfo();
  58590. _this._syncSubMeshes();
  58591. return _this;
  58592. }
  58593. /**
  58594. * Returns the string "InstancedMesh".
  58595. */
  58596. InstancedMesh.prototype.getClassName = function () {
  58597. return "InstancedMesh";
  58598. };
  58599. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  58600. // Methods
  58601. get: function () {
  58602. return this._sourceMesh.receiveShadows;
  58603. },
  58604. enumerable: true,
  58605. configurable: true
  58606. });
  58607. Object.defineProperty(InstancedMesh.prototype, "material", {
  58608. get: function () {
  58609. return this._sourceMesh.material;
  58610. },
  58611. enumerable: true,
  58612. configurable: true
  58613. });
  58614. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  58615. get: function () {
  58616. return this._sourceMesh.visibility;
  58617. },
  58618. enumerable: true,
  58619. configurable: true
  58620. });
  58621. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  58622. get: function () {
  58623. return this._sourceMesh.skeleton;
  58624. },
  58625. enumerable: true,
  58626. configurable: true
  58627. });
  58628. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  58629. get: function () {
  58630. return this._sourceMesh.renderingGroupId;
  58631. },
  58632. set: function (value) {
  58633. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  58634. return;
  58635. }
  58636. //no-op with warning
  58637. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  58638. },
  58639. enumerable: true,
  58640. configurable: true
  58641. });
  58642. /**
  58643. * Returns the total number of vertices (integer).
  58644. */
  58645. InstancedMesh.prototype.getTotalVertices = function () {
  58646. return this._sourceMesh.getTotalVertices();
  58647. };
  58648. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  58649. get: function () {
  58650. return this._sourceMesh;
  58651. },
  58652. enumerable: true,
  58653. configurable: true
  58654. });
  58655. /**
  58656. * Is this node ready to be used/rendered
  58657. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  58658. * @return {boolean} is it ready
  58659. */
  58660. InstancedMesh.prototype.isReady = function (completeCheck) {
  58661. if (completeCheck === void 0) { completeCheck = false; }
  58662. return this._sourceMesh.isReady(completeCheck, true);
  58663. };
  58664. /**
  58665. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  58666. */
  58667. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  58668. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  58669. };
  58670. /**
  58671. * Sets the vertex data of the mesh geometry for the requested `kind`.
  58672. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  58673. * The `data` are either a numeric array either a Float32Array.
  58674. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  58675. * 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).
  58676. * Note that a new underlying VertexBuffer object is created each call.
  58677. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58678. *
  58679. * Possible `kind` values :
  58680. * - BABYLON.VertexBuffer.PositionKind
  58681. * - BABYLON.VertexBuffer.UVKind
  58682. * - BABYLON.VertexBuffer.UV2Kind
  58683. * - BABYLON.VertexBuffer.UV3Kind
  58684. * - BABYLON.VertexBuffer.UV4Kind
  58685. * - BABYLON.VertexBuffer.UV5Kind
  58686. * - BABYLON.VertexBuffer.UV6Kind
  58687. * - BABYLON.VertexBuffer.ColorKind
  58688. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58689. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58690. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58691. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58692. *
  58693. * Returns the Mesh.
  58694. */
  58695. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58696. if (this.sourceMesh) {
  58697. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58698. }
  58699. return this.sourceMesh;
  58700. };
  58701. /**
  58702. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58703. * If the mesh has no geometry, it is simply returned as it is.
  58704. * The `data` are either a numeric array either a Float32Array.
  58705. * No new underlying VertexBuffer object is created.
  58706. * 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.
  58707. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58708. *
  58709. * Possible `kind` values :
  58710. * - BABYLON.VertexBuffer.PositionKind
  58711. * - BABYLON.VertexBuffer.UVKind
  58712. * - BABYLON.VertexBuffer.UV2Kind
  58713. * - BABYLON.VertexBuffer.UV3Kind
  58714. * - BABYLON.VertexBuffer.UV4Kind
  58715. * - BABYLON.VertexBuffer.UV5Kind
  58716. * - BABYLON.VertexBuffer.UV6Kind
  58717. * - BABYLON.VertexBuffer.ColorKind
  58718. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58719. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58720. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58721. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58722. *
  58723. * Returns the Mesh.
  58724. */
  58725. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58726. if (this.sourceMesh) {
  58727. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58728. }
  58729. return this.sourceMesh;
  58730. };
  58731. /**
  58732. * Sets the mesh indices.
  58733. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58734. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58735. * This method creates a new index buffer each call.
  58736. * Returns the Mesh.
  58737. */
  58738. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58739. if (totalVertices === void 0) { totalVertices = null; }
  58740. if (this.sourceMesh) {
  58741. this.sourceMesh.setIndices(indices, totalVertices);
  58742. }
  58743. return this.sourceMesh;
  58744. };
  58745. /**
  58746. * Boolean : True if the mesh owns the requested kind of data.
  58747. */
  58748. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58749. return this._sourceMesh.isVerticesDataPresent(kind);
  58750. };
  58751. /**
  58752. * Returns an array of indices (IndicesArray).
  58753. */
  58754. InstancedMesh.prototype.getIndices = function () {
  58755. return this._sourceMesh.getIndices();
  58756. };
  58757. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58758. get: function () {
  58759. return this._sourceMesh._positions;
  58760. },
  58761. enumerable: true,
  58762. configurable: true
  58763. });
  58764. /**
  58765. * Sets a new updated BoundingInfo to the mesh.
  58766. * Returns the mesh.
  58767. */
  58768. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58769. var meshBB = this._sourceMesh.getBoundingInfo();
  58770. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58771. this._updateBoundingInfo();
  58772. return this;
  58773. };
  58774. InstancedMesh.prototype._preActivate = function () {
  58775. if (this._currentLOD) {
  58776. this._currentLOD._preActivate();
  58777. }
  58778. return this;
  58779. };
  58780. InstancedMesh.prototype._activate = function (renderId) {
  58781. if (this._currentLOD) {
  58782. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58783. }
  58784. return this;
  58785. };
  58786. /**
  58787. * Returns the current associated LOD AbstractMesh.
  58788. */
  58789. InstancedMesh.prototype.getLOD = function (camera) {
  58790. if (!camera) {
  58791. return this;
  58792. }
  58793. var boundingInfo = this.getBoundingInfo();
  58794. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58795. if (this._currentLOD === this.sourceMesh) {
  58796. return this;
  58797. }
  58798. return this._currentLOD;
  58799. };
  58800. InstancedMesh.prototype._syncSubMeshes = function () {
  58801. this.releaseSubMeshes();
  58802. if (this._sourceMesh.subMeshes) {
  58803. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58804. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58805. }
  58806. }
  58807. return this;
  58808. };
  58809. InstancedMesh.prototype._generatePointsArray = function () {
  58810. return this._sourceMesh._generatePointsArray();
  58811. };
  58812. /**
  58813. * Creates a new InstancedMesh from the current mesh.
  58814. * - name (string) : the cloned mesh name
  58815. * - newParent (optional Node) : the optional Node to parent the clone to.
  58816. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58817. *
  58818. * Returns the clone.
  58819. */
  58820. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58821. var result = this._sourceMesh.createInstance(name);
  58822. // Deep copy
  58823. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58824. // Bounding info
  58825. this.refreshBoundingInfo();
  58826. // Parent
  58827. if (newParent) {
  58828. result.parent = newParent;
  58829. }
  58830. if (!doNotCloneChildren) {
  58831. // Children
  58832. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58833. var mesh = this.getScene().meshes[index];
  58834. if (mesh.parent === this) {
  58835. mesh.clone(mesh.name, result);
  58836. }
  58837. }
  58838. }
  58839. result.computeWorldMatrix(true);
  58840. return result;
  58841. };
  58842. /**
  58843. * Disposes the InstancedMesh.
  58844. * Returns nothing.
  58845. */
  58846. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58847. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58848. // Remove from mesh
  58849. var index = this._sourceMesh.instances.indexOf(this);
  58850. this._sourceMesh.instances.splice(index, 1);
  58851. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58852. };
  58853. return InstancedMesh;
  58854. }(BABYLON.AbstractMesh));
  58855. BABYLON.InstancedMesh = InstancedMesh;
  58856. })(BABYLON || (BABYLON = {}));
  58857. //# sourceMappingURL=babylon.instancedMesh.js.map
  58858. "use strict";
  58859. var BABYLON;
  58860. (function (BABYLON) {
  58861. var LinesMesh = /** @class */ (function (_super) {
  58862. __extends(LinesMesh, _super);
  58863. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58864. if (scene === void 0) { scene = null; }
  58865. if (parent === void 0) { parent = null; }
  58866. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58867. _this.useVertexColor = useVertexColor;
  58868. _this.useVertexAlpha = useVertexAlpha;
  58869. _this.color = new BABYLON.Color3(1, 1, 1);
  58870. _this.alpha = 1;
  58871. if (source) {
  58872. _this.color = source.color.clone();
  58873. _this.alpha = source.alpha;
  58874. _this.useVertexColor = source.useVertexColor;
  58875. _this.useVertexAlpha = source.useVertexAlpha;
  58876. }
  58877. _this._intersectionThreshold = 0.1;
  58878. var defines = [];
  58879. var options = {
  58880. attributes: [BABYLON.VertexBuffer.PositionKind],
  58881. uniforms: ["world", "viewProjection"],
  58882. needAlphaBlending: true,
  58883. defines: defines
  58884. };
  58885. if (useVertexAlpha === false) {
  58886. options.needAlphaBlending = false;
  58887. }
  58888. if (!useVertexColor) {
  58889. options.uniforms.push("color");
  58890. }
  58891. else {
  58892. options.defines.push("#define VERTEXCOLOR");
  58893. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58894. }
  58895. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58896. return _this;
  58897. }
  58898. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58899. /**
  58900. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58901. * This margin is expressed in world space coordinates, so its value may vary.
  58902. * Default value is 0.1
  58903. * @returns the intersection Threshold value.
  58904. */
  58905. get: function () {
  58906. return this._intersectionThreshold;
  58907. },
  58908. /**
  58909. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58910. * This margin is expressed in world space coordinates, so its value may vary.
  58911. * @param value the new threshold to apply
  58912. */
  58913. set: function (value) {
  58914. if (this._intersectionThreshold === value) {
  58915. return;
  58916. }
  58917. this._intersectionThreshold = value;
  58918. if (this.geometry) {
  58919. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58920. }
  58921. },
  58922. enumerable: true,
  58923. configurable: true
  58924. });
  58925. /**
  58926. * Returns the string "LineMesh"
  58927. */
  58928. LinesMesh.prototype.getClassName = function () {
  58929. return "LinesMesh";
  58930. };
  58931. Object.defineProperty(LinesMesh.prototype, "material", {
  58932. get: function () {
  58933. return this._colorShader;
  58934. },
  58935. set: function (value) {
  58936. // Do nothing
  58937. },
  58938. enumerable: true,
  58939. configurable: true
  58940. });
  58941. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58942. get: function () {
  58943. return false;
  58944. },
  58945. enumerable: true,
  58946. configurable: true
  58947. });
  58948. LinesMesh.prototype.createInstance = function (name) {
  58949. throw new Error("LinesMeshes do not support createInstance.");
  58950. };
  58951. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58952. if (!this._geometry) {
  58953. return this;
  58954. }
  58955. // VBOs
  58956. this._geometry._bind(this._colorShader.getEffect());
  58957. // Color
  58958. if (!this.useVertexColor) {
  58959. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58960. }
  58961. return this;
  58962. };
  58963. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58964. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58965. return this;
  58966. }
  58967. var engine = this.getScene().getEngine();
  58968. // Draw order
  58969. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58970. return this;
  58971. };
  58972. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58973. this._colorShader.dispose();
  58974. _super.prototype.dispose.call(this, doNotRecurse);
  58975. };
  58976. /**
  58977. * Returns a new LineMesh object cloned from the current one.
  58978. */
  58979. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58980. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58981. };
  58982. return LinesMesh;
  58983. }(BABYLON.Mesh));
  58984. BABYLON.LinesMesh = LinesMesh;
  58985. })(BABYLON || (BABYLON = {}));
  58986. //# sourceMappingURL=babylon.linesMesh.js.map
  58987. "use strict";
  58988. var BABYLON;
  58989. (function (BABYLON) {
  58990. /**
  58991. * Class containing static functions to help procedurally build meshes
  58992. */
  58993. var MeshBuilder = /** @class */ (function () {
  58994. function MeshBuilder() {
  58995. }
  58996. MeshBuilder.updateSideOrientation = function (orientation) {
  58997. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  58998. return BABYLON.Mesh.DOUBLESIDE;
  58999. }
  59000. if (orientation === undefined || orientation === null) {
  59001. return BABYLON.Mesh.FRONTSIDE;
  59002. }
  59003. return orientation;
  59004. };
  59005. /**
  59006. * Creates a box mesh
  59007. * * The parameter `size` sets the size (float) of each box side (default 1)
  59008. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59009. * * 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)
  59010. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59011. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59012. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59013. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59014. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59015. * @param name defines the name of the mesh
  59016. * @param options defines the options used to create the mesh
  59017. * @param scene defines the hosting scene
  59018. * @returns the box mesh
  59019. */
  59020. MeshBuilder.CreateBox = function (name, options, scene) {
  59021. if (scene === void 0) { scene = null; }
  59022. var box = new BABYLON.Mesh(name, scene);
  59023. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59024. box._originalBuilderSideOrientation = options.sideOrientation;
  59025. var vertexData = BABYLON.VertexData.CreateBox(options);
  59026. vertexData.applyToMesh(box, options.updatable);
  59027. return box;
  59028. };
  59029. /**
  59030. * Creates a sphere mesh
  59031. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59032. * * 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`)
  59033. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59034. * * 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
  59035. * * 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)
  59036. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59037. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59038. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59039. * @param name defines the name of the mesh
  59040. * @param options defines the options used to create the mesh
  59041. * @param scene defines the hosting scene
  59042. * @returns the sphere mesh
  59043. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59044. */
  59045. MeshBuilder.CreateSphere = function (name, options, scene) {
  59046. var sphere = new BABYLON.Mesh(name, scene);
  59047. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59048. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59049. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59050. vertexData.applyToMesh(sphere, options.updatable);
  59051. return sphere;
  59052. };
  59053. /**
  59054. * Creates a plane polygonal mesh. By default, this is a disc
  59055. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59056. * * 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
  59057. * * 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
  59058. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59059. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59060. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59061. * @param name defines the name of the mesh
  59062. * @param options defines the options used to create the mesh
  59063. * @param scene defines the hosting scene
  59064. * @returns the plane polygonal mesh
  59065. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  59066. */
  59067. MeshBuilder.CreateDisc = function (name, options, scene) {
  59068. if (scene === void 0) { scene = null; }
  59069. var disc = new BABYLON.Mesh(name, scene);
  59070. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59071. disc._originalBuilderSideOrientation = options.sideOrientation;
  59072. var vertexData = BABYLON.VertexData.CreateDisc(options);
  59073. vertexData.applyToMesh(disc, options.updatable);
  59074. return disc;
  59075. };
  59076. /**
  59077. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  59078. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  59079. * * 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`)
  59080. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  59081. * * 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
  59082. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59083. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59084. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59085. * @param name defines the name of the mesh
  59086. * @param options defines the options used to create the mesh
  59087. * @param scene defines the hosting scene
  59088. * @returns the icosahedron mesh
  59089. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  59090. */
  59091. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  59092. var sphere = new BABYLON.Mesh(name, scene);
  59093. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59094. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59095. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  59096. vertexData.applyToMesh(sphere, options.updatable);
  59097. return sphere;
  59098. };
  59099. ;
  59100. /**
  59101. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59102. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  59103. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  59104. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  59105. * * 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
  59106. * * 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
  59107. * * 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
  59108. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59109. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59110. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59111. * * 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
  59112. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  59113. * * 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
  59114. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  59115. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59116. * @param name defines the name of the mesh
  59117. * @param options defines the options used to create the mesh
  59118. * @param scene defines the hosting scene
  59119. * @returns the ribbon mesh
  59120. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  59121. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59122. */
  59123. MeshBuilder.CreateRibbon = function (name, options, scene) {
  59124. if (scene === void 0) { scene = null; }
  59125. var pathArray = options.pathArray;
  59126. var closeArray = options.closeArray;
  59127. var closePath = options.closePath;
  59128. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59129. var instance = options.instance;
  59130. var updatable = options.updatable;
  59131. if (instance) {
  59132. // positionFunction : ribbon case
  59133. // only pathArray and sideOrientation parameters are taken into account for positions update
  59134. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  59135. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  59136. var positionFunction = function (positions) {
  59137. var minlg = pathArray[0].length;
  59138. var i = 0;
  59139. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  59140. for (var si = 1; si <= ns; si++) {
  59141. for (var p = 0; p < pathArray.length; p++) {
  59142. var path = pathArray[p];
  59143. var l = path.length;
  59144. minlg = (minlg < l) ? minlg : l;
  59145. var j = 0;
  59146. while (j < minlg) {
  59147. positions[i] = path[j].x;
  59148. positions[i + 1] = path[j].y;
  59149. positions[i + 2] = path[j].z;
  59150. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  59151. BABYLON.Tmp.Vector3[0].x = path[j].x;
  59152. }
  59153. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  59154. BABYLON.Tmp.Vector3[1].x = path[j].x;
  59155. }
  59156. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  59157. BABYLON.Tmp.Vector3[0].y = path[j].y;
  59158. }
  59159. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  59160. BABYLON.Tmp.Vector3[1].y = path[j].y;
  59161. }
  59162. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  59163. BABYLON.Tmp.Vector3[0].z = path[j].z;
  59164. }
  59165. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  59166. BABYLON.Tmp.Vector3[1].z = path[j].z;
  59167. }
  59168. j++;
  59169. i += 3;
  59170. }
  59171. if (instance._closePath) {
  59172. positions[i] = path[0].x;
  59173. positions[i + 1] = path[0].y;
  59174. positions[i + 2] = path[0].z;
  59175. i += 3;
  59176. }
  59177. }
  59178. }
  59179. };
  59180. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59181. positionFunction(positions);
  59182. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  59183. instance._boundingInfo.update(instance._worldMatrix);
  59184. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59185. if (options.colors) {
  59186. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59187. for (var c = 0; c < options.colors.length; c++) {
  59188. colors[c * 4] = options.colors[c].r;
  59189. colors[c * 4 + 1] = options.colors[c].g;
  59190. colors[c * 4 + 2] = options.colors[c].b;
  59191. colors[c * 4 + 3] = options.colors[c].a;
  59192. }
  59193. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  59194. }
  59195. if (options.uvs) {
  59196. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59197. for (var i = 0; i < options.uvs.length; i++) {
  59198. uvs[i * 2] = options.uvs[i].x;
  59199. uvs[i * 2 + 1] = options.uvs[i].y;
  59200. }
  59201. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  59202. }
  59203. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  59204. var indices = instance.getIndices();
  59205. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59206. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  59207. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  59208. if (instance._closePath) {
  59209. var indexFirst = 0;
  59210. var indexLast = 0;
  59211. for (var p = 0; p < pathArray.length; p++) {
  59212. indexFirst = instance._idx[p] * 3;
  59213. if (p + 1 < pathArray.length) {
  59214. indexLast = (instance._idx[p + 1] - 1) * 3;
  59215. }
  59216. else {
  59217. indexLast = normals.length - 3;
  59218. }
  59219. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  59220. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  59221. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  59222. normals[indexLast] = normals[indexFirst];
  59223. normals[indexLast + 1] = normals[indexFirst + 1];
  59224. normals[indexLast + 2] = normals[indexFirst + 2];
  59225. }
  59226. }
  59227. if (!(instance.areNormalsFrozen)) {
  59228. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  59229. }
  59230. }
  59231. return instance;
  59232. }
  59233. else {
  59234. var ribbon = new BABYLON.Mesh(name, scene);
  59235. ribbon._originalBuilderSideOrientation = sideOrientation;
  59236. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  59237. if (closePath) {
  59238. ribbon._idx = vertexData._idx;
  59239. }
  59240. ribbon._closePath = closePath;
  59241. ribbon._closeArray = closeArray;
  59242. vertexData.applyToMesh(ribbon, updatable);
  59243. return ribbon;
  59244. }
  59245. };
  59246. /**
  59247. * Creates a cylinder or a cone mesh
  59248. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  59249. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  59250. * * 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.
  59251. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  59252. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  59253. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  59254. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  59255. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  59256. * * 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).
  59257. * * 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
  59258. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  59259. * * 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
  59260. * * 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.
  59261. * * If `enclose` is false, a ring surface is one element.
  59262. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  59263. * * 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
  59264. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59265. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59266. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59267. * @param name defines the name of the mesh
  59268. * @param options defines the options used to create the mesh
  59269. * @param scene defines the hosting scene
  59270. * @returns the cylinder mesh
  59271. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  59272. */
  59273. MeshBuilder.CreateCylinder = function (name, options, scene) {
  59274. var cylinder = new BABYLON.Mesh(name, scene);
  59275. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59276. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  59277. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  59278. vertexData.applyToMesh(cylinder, options.updatable);
  59279. return cylinder;
  59280. };
  59281. /**
  59282. * Creates a torus mesh
  59283. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  59284. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  59285. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  59286. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59287. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59288. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59289. * @param name defines the name of the mesh
  59290. * @param options defines the options used to create the mesh
  59291. * @param scene defines the hosting scene
  59292. * @returns the torus mesh
  59293. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  59294. */
  59295. MeshBuilder.CreateTorus = function (name, options, scene) {
  59296. var torus = new BABYLON.Mesh(name, scene);
  59297. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59298. torus._originalBuilderSideOrientation = options.sideOrientation;
  59299. var vertexData = BABYLON.VertexData.CreateTorus(options);
  59300. vertexData.applyToMesh(torus, options.updatable);
  59301. return torus;
  59302. };
  59303. /**
  59304. * Creates a torus knot mesh
  59305. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  59306. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  59307. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  59308. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  59309. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59310. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59311. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59312. * @param name defines the name of the mesh
  59313. * @param options defines the options used to create the mesh
  59314. * @param scene defines the hosting scene
  59315. * @returns the torus knot mesh
  59316. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  59317. */
  59318. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  59319. var torusKnot = new BABYLON.Mesh(name, scene);
  59320. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59321. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  59322. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  59323. vertexData.applyToMesh(torusKnot, options.updatable);
  59324. return torusKnot;
  59325. };
  59326. /**
  59327. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  59328. * * 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
  59329. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  59330. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  59331. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  59332. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  59333. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  59334. * * 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
  59335. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  59336. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59337. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  59338. * @param name defines the name of the new line system
  59339. * @param options defines the options used to create the line system
  59340. * @param scene defines the hosting scene
  59341. * @returns a new line system mesh
  59342. */
  59343. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  59344. var instance = options.instance;
  59345. var lines = options.lines;
  59346. var colors = options.colors;
  59347. if (instance) {
  59348. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59349. var vertexColor;
  59350. var lineColors;
  59351. if (colors) {
  59352. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59353. }
  59354. var i = 0;
  59355. var c = 0;
  59356. for (var l = 0; l < lines.length; l++) {
  59357. var points = lines[l];
  59358. for (var p = 0; p < points.length; p++) {
  59359. positions[i] = points[p].x;
  59360. positions[i + 1] = points[p].y;
  59361. positions[i + 2] = points[p].z;
  59362. if (colors && vertexColor) {
  59363. lineColors = colors[l];
  59364. vertexColor[c] = lineColors[p].r;
  59365. vertexColor[c + 1] = lineColors[p].g;
  59366. vertexColor[c + 2] = lineColors[p].b;
  59367. vertexColor[c + 3] = lineColors[p].a;
  59368. c += 4;
  59369. }
  59370. i += 3;
  59371. }
  59372. }
  59373. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  59374. if (colors && vertexColor) {
  59375. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  59376. }
  59377. return instance;
  59378. }
  59379. // line system creation
  59380. var useVertexColor = (colors) ? true : false;
  59381. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  59382. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  59383. vertexData.applyToMesh(lineSystem, options.updatable);
  59384. return lineSystem;
  59385. };
  59386. /**
  59387. * Creates a line mesh
  59388. * 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
  59389. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59390. * * The parameter `points` is an array successive Vector3
  59391. * * 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
  59392. * * The optional parameter `colors` is an array of successive Color4, one per line point
  59393. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  59394. * * When updating an instance, remember that only point positions can change, not the number of points
  59395. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59396. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  59397. * @param name defines the name of the new line system
  59398. * @param options defines the options used to create the line system
  59399. * @param scene defines the hosting scene
  59400. * @returns a new line mesh
  59401. */
  59402. MeshBuilder.CreateLines = function (name, options, scene) {
  59403. if (scene === void 0) { scene = null; }
  59404. var colors = (options.colors) ? [options.colors] : null;
  59405. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  59406. return lines;
  59407. };
  59408. /**
  59409. * Creates a dashed line mesh
  59410. * * 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
  59411. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  59412. * * The parameter `points` is an array successive Vector3
  59413. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  59414. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  59415. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  59416. * * 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
  59417. * * When updating an instance, remember that only point positions can change, not the number of points
  59418. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59419. * @param name defines the name of the mesh
  59420. * @param options defines the options used to create the mesh
  59421. * @param scene defines the hosting scene
  59422. * @returns the dashed line mesh
  59423. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  59424. */
  59425. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  59426. if (scene === void 0) { scene = null; }
  59427. var points = options.points;
  59428. var instance = options.instance;
  59429. var gapSize = options.gapSize || 1;
  59430. var dashSize = options.dashSize || 3;
  59431. if (instance) {
  59432. var positionFunction = function (positions) {
  59433. var curvect = BABYLON.Vector3.Zero();
  59434. var nbSeg = positions.length / 6;
  59435. var lg = 0;
  59436. var nb = 0;
  59437. var shft = 0;
  59438. var dashshft = 0;
  59439. var curshft = 0;
  59440. var p = 0;
  59441. var i = 0;
  59442. var j = 0;
  59443. for (i = 0; i < points.length - 1; i++) {
  59444. points[i + 1].subtractToRef(points[i], curvect);
  59445. lg += curvect.length();
  59446. }
  59447. shft = lg / nbSeg;
  59448. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  59449. for (i = 0; i < points.length - 1; i++) {
  59450. points[i + 1].subtractToRef(points[i], curvect);
  59451. nb = Math.floor(curvect.length() / shft);
  59452. curvect.normalize();
  59453. j = 0;
  59454. while (j < nb && p < positions.length) {
  59455. curshft = shft * j;
  59456. positions[p] = points[i].x + curshft * curvect.x;
  59457. positions[p + 1] = points[i].y + curshft * curvect.y;
  59458. positions[p + 2] = points[i].z + curshft * curvect.z;
  59459. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  59460. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  59461. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  59462. p += 6;
  59463. j++;
  59464. }
  59465. }
  59466. while (p < positions.length) {
  59467. positions[p] = points[i].x;
  59468. positions[p + 1] = points[i].y;
  59469. positions[p + 2] = points[i].z;
  59470. p += 3;
  59471. }
  59472. };
  59473. instance.updateMeshPositions(positionFunction, false);
  59474. return instance;
  59475. }
  59476. // dashed lines creation
  59477. var dashedLines = new BABYLON.LinesMesh(name, scene);
  59478. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  59479. vertexData.applyToMesh(dashedLines, options.updatable);
  59480. dashedLines.dashSize = dashSize;
  59481. dashedLines.gapSize = gapSize;
  59482. return dashedLines;
  59483. };
  59484. /**
  59485. * 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.
  59486. * * 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.
  59487. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59488. * * 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.
  59489. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  59490. * * 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
  59491. * * 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
  59492. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  59493. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59494. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59495. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  59496. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59497. * @param name defines the name of the mesh
  59498. * @param options defines the options used to create the mesh
  59499. * @param scene defines the hosting scene
  59500. * @returns the extruded shape mesh
  59501. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59502. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59503. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  59504. */
  59505. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  59506. if (scene === void 0) { scene = null; }
  59507. var path = options.path;
  59508. var shape = options.shape;
  59509. var scale = options.scale || 1;
  59510. var rotation = options.rotation || 0;
  59511. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59512. var updatable = options.updatable;
  59513. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59514. var instance = options.instance || null;
  59515. var invertUV = options.invertUV || false;
  59516. 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);
  59517. };
  59518. /**
  59519. * Creates an custom extruded shape mesh.
  59520. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  59521. * * 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.
  59522. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  59523. * * 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
  59524. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  59525. * * 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
  59526. * * It must returns a float value that will be the scale value applied to the shape on each path point
  59527. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  59528. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  59529. * * 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
  59530. * * 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
  59531. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  59532. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59533. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59534. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59535. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59536. * @param name defines the name of the mesh
  59537. * @param options defines the options used to create the mesh
  59538. * @param scene defines the hosting scene
  59539. * @returns the custom extruded shape mesh
  59540. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  59541. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59542. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  59543. */
  59544. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  59545. var path = options.path;
  59546. var shape = options.shape;
  59547. var scaleFunction = options.scaleFunction || (function () { return 1; });
  59548. var rotationFunction = options.rotationFunction || (function () { return 0; });
  59549. var ribbonCloseArray = options.ribbonCloseArray || false;
  59550. var ribbonClosePath = options.ribbonClosePath || false;
  59551. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  59552. var updatable = options.updatable;
  59553. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59554. var instance = options.instance;
  59555. var invertUV = options.invertUV || false;
  59556. 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);
  59557. };
  59558. /**
  59559. * Creates lathe mesh.
  59560. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  59561. * * 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
  59562. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  59563. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  59564. * * 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
  59565. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  59566. * * 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
  59567. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59568. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59569. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59570. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59571. * @param name defines the name of the mesh
  59572. * @param options defines the options used to create the mesh
  59573. * @param scene defines the hosting scene
  59574. * @returns the lathe mesh
  59575. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  59576. */
  59577. MeshBuilder.CreateLathe = function (name, options, scene) {
  59578. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  59579. var closed = (options.closed === undefined) ? true : options.closed;
  59580. var shape = options.shape;
  59581. var radius = options.radius || 1;
  59582. var tessellation = options.tessellation || 64;
  59583. var updatable = options.updatable;
  59584. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59585. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59586. var pi2 = Math.PI * 2;
  59587. var paths = new Array();
  59588. var invertUV = options.invertUV || false;
  59589. var i = 0;
  59590. var p = 0;
  59591. var step = pi2 / tessellation * arc;
  59592. var rotated;
  59593. var path = new Array();
  59594. ;
  59595. for (i = 0; i <= tessellation; i++) {
  59596. var path = [];
  59597. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  59598. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  59599. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  59600. }
  59601. for (p = 0; p < shape.length; p++) {
  59602. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  59603. path.push(rotated);
  59604. }
  59605. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  59606. 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));
  59607. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  59608. }
  59609. paths.push(path);
  59610. }
  59611. // lathe ribbon
  59612. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59613. return lathe;
  59614. };
  59615. /**
  59616. * Creates a plane mesh
  59617. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  59618. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  59619. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  59620. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59621. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59622. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59623. * @param name defines the name of the mesh
  59624. * @param options defines the options used to create the mesh
  59625. * @param scene defines the hosting scene
  59626. * @returns the plane mesh
  59627. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59628. */
  59629. MeshBuilder.CreatePlane = function (name, options, scene) {
  59630. var plane = new BABYLON.Mesh(name, scene);
  59631. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59632. plane._originalBuilderSideOrientation = options.sideOrientation;
  59633. var vertexData = BABYLON.VertexData.CreatePlane(options);
  59634. vertexData.applyToMesh(plane, options.updatable);
  59635. if (options.sourcePlane) {
  59636. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  59637. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  59638. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  59639. plane.rotate(vectorProduct, product);
  59640. }
  59641. return plane;
  59642. };
  59643. /**
  59644. * Creates a ground mesh
  59645. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  59646. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  59647. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59648. * @param name defines the name of the mesh
  59649. * @param options defines the options used to create the mesh
  59650. * @param scene defines the hosting scene
  59651. * @returns the ground mesh
  59652. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  59653. */
  59654. MeshBuilder.CreateGround = function (name, options, scene) {
  59655. var ground = new BABYLON.GroundMesh(name, scene);
  59656. ground._setReady(false);
  59657. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  59658. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  59659. ground._width = options.width || 1;
  59660. ground._height = options.height || 1;
  59661. ground._maxX = ground._width / 2;
  59662. ground._maxZ = ground._height / 2;
  59663. ground._minX = -ground._maxX;
  59664. ground._minZ = -ground._maxZ;
  59665. var vertexData = BABYLON.VertexData.CreateGround(options);
  59666. vertexData.applyToMesh(ground, options.updatable);
  59667. ground._setReady(true);
  59668. return ground;
  59669. };
  59670. /**
  59671. * Creates a tiled ground mesh
  59672. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  59673. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  59674. * * 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
  59675. * * 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
  59676. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59677. * @param name defines the name of the mesh
  59678. * @param options defines the options used to create the mesh
  59679. * @param scene defines the hosting scene
  59680. * @returns the tiled ground mesh
  59681. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  59682. */
  59683. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  59684. var tiledGround = new BABYLON.Mesh(name, scene);
  59685. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  59686. vertexData.applyToMesh(tiledGround, options.updatable);
  59687. return tiledGround;
  59688. };
  59689. /**
  59690. * Creates a ground mesh from a height map
  59691. * * The parameter `url` sets the URL of the height map image resource.
  59692. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  59693. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  59694. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  59695. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  59696. * * 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.
  59697. * * 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).
  59698. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  59699. * @param name defines the name of the mesh
  59700. * @param url defines the url to the height map
  59701. * @param options defines the options used to create the mesh
  59702. * @param scene defines the hosting scene
  59703. * @returns the ground mesh
  59704. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  59705. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  59706. */
  59707. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  59708. var width = options.width || 10.0;
  59709. var height = options.height || 10.0;
  59710. var subdivisions = options.subdivisions || 1 | 0;
  59711. var minHeight = options.minHeight || 0.0;
  59712. var maxHeight = options.maxHeight || 1.0;
  59713. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  59714. var updatable = options.updatable;
  59715. var onReady = options.onReady;
  59716. var ground = new BABYLON.GroundMesh(name, scene);
  59717. ground._subdivisionsX = subdivisions;
  59718. ground._subdivisionsY = subdivisions;
  59719. ground._width = width;
  59720. ground._height = height;
  59721. ground._maxX = ground._width / 2.0;
  59722. ground._maxZ = ground._height / 2.0;
  59723. ground._minX = -ground._maxX;
  59724. ground._minZ = -ground._maxZ;
  59725. ground._setReady(false);
  59726. var onload = function (img) {
  59727. // Getting height map data
  59728. var canvas = document.createElement("canvas");
  59729. var context = canvas.getContext("2d");
  59730. if (!context) {
  59731. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  59732. }
  59733. if (scene.isDisposed) {
  59734. return;
  59735. }
  59736. var bufferWidth = img.width;
  59737. var bufferHeight = img.height;
  59738. canvas.width = bufferWidth;
  59739. canvas.height = bufferHeight;
  59740. context.drawImage(img, 0, 0);
  59741. // Create VertexData from map data
  59742. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  59743. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  59744. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  59745. width: width, height: height,
  59746. subdivisions: subdivisions,
  59747. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  59748. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  59749. });
  59750. vertexData.applyToMesh(ground, updatable);
  59751. //execute ready callback, if set
  59752. if (onReady) {
  59753. onReady(ground);
  59754. }
  59755. ground._setReady(true);
  59756. };
  59757. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  59758. return ground;
  59759. };
  59760. /**
  59761. * Creates a polygon mesh
  59762. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  59763. * * 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
  59764. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59765. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59766. * * 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)
  59767. * * Remember you can only change the shape positions, not their number when updating a polygon
  59768. * @param name defines the name of the mesh
  59769. * @param options defines the options used to create the mesh
  59770. * @param scene defines the hosting scene
  59771. * @returns the polygon mesh
  59772. */
  59773. MeshBuilder.CreatePolygon = function (name, options, scene) {
  59774. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59775. var shape = options.shape;
  59776. var holes = options.holes || [];
  59777. var depth = options.depth || 0;
  59778. var contours = [];
  59779. var hole = [];
  59780. for (var i = 0; i < shape.length; i++) {
  59781. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  59782. }
  59783. var epsilon = 0.00000001;
  59784. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  59785. contours.pop();
  59786. }
  59787. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  59788. for (var hNb = 0; hNb < holes.length; hNb++) {
  59789. hole = [];
  59790. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  59791. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  59792. }
  59793. polygonTriangulation.addHole(hole);
  59794. }
  59795. var polygon = polygonTriangulation.build(options.updatable, depth);
  59796. polygon._originalBuilderSideOrientation = options.sideOrientation;
  59797. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  59798. vertexData.applyToMesh(polygon, options.updatable);
  59799. return polygon;
  59800. };
  59801. ;
  59802. /**
  59803. * Creates an extruded polygon mesh, with depth in the Y direction.
  59804. * * 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)
  59805. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59806. * @param name defines the name of the mesh
  59807. * @param options defines the options used to create the mesh
  59808. * @param scene defines the hosting scene
  59809. * @returns the polygon mesh
  59810. */
  59811. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  59812. return MeshBuilder.CreatePolygon(name, options, scene);
  59813. };
  59814. ;
  59815. /**
  59816. * Creates a tube mesh.
  59817. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  59818. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  59819. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  59820. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  59821. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  59822. * * 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)
  59823. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  59824. * * 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
  59825. * * 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
  59826. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59827. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59828. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  59829. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59830. * @param name defines the name of the mesh
  59831. * @param options defines the options used to create the mesh
  59832. * @param scene defines the hosting scene
  59833. * @returns the tube mesh
  59834. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  59835. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  59836. */
  59837. MeshBuilder.CreateTube = function (name, options, scene) {
  59838. var path = options.path;
  59839. var instance = options.instance;
  59840. var radius = 1.0;
  59841. if (instance) {
  59842. radius = instance.radius;
  59843. }
  59844. if (options.radius !== undefined) {
  59845. radius = options.radius;
  59846. }
  59847. ;
  59848. var tessellation = options.tessellation || 64 | 0;
  59849. var radiusFunction = options.radiusFunction || null;
  59850. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  59851. var invertUV = options.invertUV || false;
  59852. var updatable = options.updatable;
  59853. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59854. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  59855. // tube geometry
  59856. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  59857. var tangents = path3D.getTangents();
  59858. var normals = path3D.getNormals();
  59859. var distances = path3D.getDistances();
  59860. var pi2 = Math.PI * 2;
  59861. var step = pi2 / tessellation * arc;
  59862. var returnRadius = function () { return radius; };
  59863. var radiusFunctionFinal = radiusFunction || returnRadius;
  59864. var circlePath;
  59865. var rad;
  59866. var normal;
  59867. var rotated;
  59868. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  59869. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  59870. for (var i = 0; i < path.length; i++) {
  59871. rad = radiusFunctionFinal(i, distances[i]); // current radius
  59872. circlePath = Array(); // current circle array
  59873. normal = normals[i]; // current normal
  59874. for (var t = 0; t < tessellation; t++) {
  59875. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  59876. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  59877. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  59878. rotated.scaleInPlace(rad).addInPlace(path[i]);
  59879. circlePath[t] = rotated;
  59880. }
  59881. circlePaths[index] = circlePath;
  59882. index++;
  59883. }
  59884. // cap
  59885. var capPath = function (nbPoints, pathIndex) {
  59886. var pointCap = Array();
  59887. for (var i = 0; i < nbPoints; i++) {
  59888. pointCap.push(path[pathIndex]);
  59889. }
  59890. return pointCap;
  59891. };
  59892. switch (cap) {
  59893. case BABYLON.Mesh.NO_CAP:
  59894. break;
  59895. case BABYLON.Mesh.CAP_START:
  59896. circlePaths[0] = capPath(tessellation, 0);
  59897. circlePaths[1] = circlePaths[2].slice(0);
  59898. break;
  59899. case BABYLON.Mesh.CAP_END:
  59900. circlePaths[index] = circlePaths[index - 1].slice(0);
  59901. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  59902. break;
  59903. case BABYLON.Mesh.CAP_ALL:
  59904. circlePaths[0] = capPath(tessellation, 0);
  59905. circlePaths[1] = circlePaths[2].slice(0);
  59906. circlePaths[index] = circlePaths[index - 1].slice(0);
  59907. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  59908. break;
  59909. default:
  59910. break;
  59911. }
  59912. return circlePaths;
  59913. };
  59914. var path3D;
  59915. var pathArray;
  59916. if (instance) {
  59917. var arc = options.arc || instance.arc;
  59918. path3D = (instance.path3D).update(path);
  59919. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  59920. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  59921. instance.path3D = path3D;
  59922. instance.pathArray = pathArray;
  59923. instance.arc = arc;
  59924. instance.radius = radius;
  59925. return instance;
  59926. }
  59927. // tube creation
  59928. path3D = new BABYLON.Path3D(path);
  59929. var newPathArray = new Array();
  59930. cap = (cap < 0 || cap > 3) ? 0 : cap;
  59931. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  59932. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  59933. tube.pathArray = pathArray;
  59934. tube.path3D = path3D;
  59935. tube.tessellation = tessellation;
  59936. tube.cap = cap;
  59937. tube.arc = options.arc;
  59938. tube.radius = radius;
  59939. return tube;
  59940. };
  59941. /**
  59942. * Creates a polyhedron mesh
  59943. * * 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
  59944. * * The parameter `size` (positive float, default 1) sets the polygon size
  59945. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  59946. * * 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`
  59947. * * 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
  59948. * * 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)`)
  59949. * * 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
  59950. * * 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
  59951. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59952. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  59953. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59954. * @param name defines the name of the mesh
  59955. * @param options defines the options used to create the mesh
  59956. * @param scene defines the hosting scene
  59957. * @returns the polyhedron mesh
  59958. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  59959. */
  59960. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  59961. var polyhedron = new BABYLON.Mesh(name, scene);
  59962. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59963. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  59964. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  59965. vertexData.applyToMesh(polyhedron, options.updatable);
  59966. return polyhedron;
  59967. };
  59968. /**
  59969. * Creates a decal mesh.
  59970. * 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
  59971. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  59972. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  59973. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  59974. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  59975. * @param name defines the name of the mesh
  59976. * @param sourceMesh defines the mesh where the decal must be applied
  59977. * @param options defines the options used to create the mesh
  59978. * @param scene defines the hosting scene
  59979. * @returns the decal mesh
  59980. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  59981. */
  59982. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  59983. var indices = sourceMesh.getIndices();
  59984. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59985. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59986. var position = options.position || BABYLON.Vector3.Zero();
  59987. var normal = options.normal || BABYLON.Vector3.Up();
  59988. var size = options.size || BABYLON.Vector3.One();
  59989. var angle = options.angle || 0;
  59990. // Getting correct rotation
  59991. if (!normal) {
  59992. var target = new BABYLON.Vector3(0, 0, 1);
  59993. var camera = sourceMesh.getScene().activeCamera;
  59994. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  59995. normal = camera.globalPosition.subtract(cameraWorldTarget);
  59996. }
  59997. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  59998. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  59999. var pitch = Math.atan2(normal.y, len);
  60000. // Matrix
  60001. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60002. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60003. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60004. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60005. var vertexData = new BABYLON.VertexData();
  60006. vertexData.indices = [];
  60007. vertexData.positions = [];
  60008. vertexData.normals = [];
  60009. vertexData.uvs = [];
  60010. var currentVertexDataIndex = 0;
  60011. var extractDecalVector3 = function (indexId) {
  60012. var result = new BABYLON.PositionNormalVertex();
  60013. if (!indices || !positions || !normals) {
  60014. return result;
  60015. }
  60016. var vertexId = indices[indexId];
  60017. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60018. // Send vector to decal local world
  60019. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60020. // Get normal
  60021. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60022. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60023. return result;
  60024. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60025. var clip = function (vertices, axis) {
  60026. if (vertices.length === 0) {
  60027. return vertices;
  60028. }
  60029. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60030. var clipVertices = function (v0, v1) {
  60031. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60032. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60033. };
  60034. var result = new Array();
  60035. for (var index = 0; index < vertices.length; index += 3) {
  60036. var v1Out;
  60037. var v2Out;
  60038. var v3Out;
  60039. var total = 0;
  60040. var nV1 = null;
  60041. var nV2 = null;
  60042. var nV3 = null;
  60043. var nV4 = null;
  60044. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60045. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60046. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60047. v1Out = d1 > 0;
  60048. v2Out = d2 > 0;
  60049. v3Out = d3 > 0;
  60050. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60051. switch (total) {
  60052. case 0:
  60053. result.push(vertices[index]);
  60054. result.push(vertices[index + 1]);
  60055. result.push(vertices[index + 2]);
  60056. break;
  60057. case 1:
  60058. if (v1Out) {
  60059. nV1 = vertices[index + 1];
  60060. nV2 = vertices[index + 2];
  60061. nV3 = clipVertices(vertices[index], nV1);
  60062. nV4 = clipVertices(vertices[index], nV2);
  60063. }
  60064. if (v2Out) {
  60065. nV1 = vertices[index];
  60066. nV2 = vertices[index + 2];
  60067. nV3 = clipVertices(vertices[index + 1], nV1);
  60068. nV4 = clipVertices(vertices[index + 1], nV2);
  60069. result.push(nV3);
  60070. result.push(nV2.clone());
  60071. result.push(nV1.clone());
  60072. result.push(nV2.clone());
  60073. result.push(nV3.clone());
  60074. result.push(nV4);
  60075. break;
  60076. }
  60077. if (v3Out) {
  60078. nV1 = vertices[index];
  60079. nV2 = vertices[index + 1];
  60080. nV3 = clipVertices(vertices[index + 2], nV1);
  60081. nV4 = clipVertices(vertices[index + 2], nV2);
  60082. }
  60083. if (nV1 && nV2 && nV3 && nV4) {
  60084. result.push(nV1.clone());
  60085. result.push(nV2.clone());
  60086. result.push(nV3);
  60087. result.push(nV4);
  60088. result.push(nV3.clone());
  60089. result.push(nV2.clone());
  60090. }
  60091. break;
  60092. case 2:
  60093. if (!v1Out) {
  60094. nV1 = vertices[index].clone();
  60095. nV2 = clipVertices(nV1, vertices[index + 1]);
  60096. nV3 = clipVertices(nV1, vertices[index + 2]);
  60097. result.push(nV1);
  60098. result.push(nV2);
  60099. result.push(nV3);
  60100. }
  60101. if (!v2Out) {
  60102. nV1 = vertices[index + 1].clone();
  60103. nV2 = clipVertices(nV1, vertices[index + 2]);
  60104. nV3 = clipVertices(nV1, vertices[index]);
  60105. result.push(nV1);
  60106. result.push(nV2);
  60107. result.push(nV3);
  60108. }
  60109. if (!v3Out) {
  60110. nV1 = vertices[index + 2].clone();
  60111. nV2 = clipVertices(nV1, vertices[index]);
  60112. nV3 = clipVertices(nV1, vertices[index + 1]);
  60113. result.push(nV1);
  60114. result.push(nV2);
  60115. result.push(nV3);
  60116. }
  60117. break;
  60118. case 3:
  60119. break;
  60120. }
  60121. }
  60122. return result;
  60123. };
  60124. for (var index = 0; index < indices.length; index += 3) {
  60125. var faceVertices = new Array();
  60126. faceVertices.push(extractDecalVector3(index));
  60127. faceVertices.push(extractDecalVector3(index + 1));
  60128. faceVertices.push(extractDecalVector3(index + 2));
  60129. // Clip
  60130. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  60131. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  60132. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  60133. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  60134. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  60135. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  60136. if (faceVertices.length === 0) {
  60137. continue;
  60138. }
  60139. // Add UVs and get back to world
  60140. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  60141. var vertex = faceVertices[vIndex];
  60142. //TODO check for Int32Array | Uint32Array | Uint16Array
  60143. vertexData.indices.push(currentVertexDataIndex);
  60144. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  60145. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  60146. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  60147. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  60148. currentVertexDataIndex++;
  60149. }
  60150. }
  60151. // Return mesh
  60152. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  60153. vertexData.applyToMesh(decal);
  60154. decal.position = position.clone();
  60155. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  60156. return decal;
  60157. };
  60158. // Privates
  60159. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  60160. // extrusion geometry
  60161. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  60162. var tangents = path3D.getTangents();
  60163. var normals = path3D.getNormals();
  60164. var binormals = path3D.getBinormals();
  60165. var distances = path3D.getDistances();
  60166. var angle = 0;
  60167. var returnScale = function () { return scale !== null ? scale : 1; };
  60168. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  60169. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  60170. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  60171. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60172. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60173. for (var i = 0; i < curve.length; i++) {
  60174. var shapePath = new Array();
  60175. var angleStep = rotate(i, distances[i]);
  60176. var scaleRatio = scl(i, distances[i]);
  60177. for (var p = 0; p < shape.length; p++) {
  60178. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  60179. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  60180. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  60181. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  60182. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  60183. shapePath[p] = rotated;
  60184. }
  60185. shapePaths[index] = shapePath;
  60186. angle += angleStep;
  60187. index++;
  60188. }
  60189. // cap
  60190. var capPath = function (shapePath) {
  60191. var pointCap = Array();
  60192. var barycenter = BABYLON.Vector3.Zero();
  60193. var i;
  60194. for (i = 0; i < shapePath.length; i++) {
  60195. barycenter.addInPlace(shapePath[i]);
  60196. }
  60197. barycenter.scaleInPlace(1.0 / shapePath.length);
  60198. for (i = 0; i < shapePath.length; i++) {
  60199. pointCap.push(barycenter);
  60200. }
  60201. return pointCap;
  60202. };
  60203. switch (cap) {
  60204. case BABYLON.Mesh.NO_CAP:
  60205. break;
  60206. case BABYLON.Mesh.CAP_START:
  60207. shapePaths[0] = capPath(shapePaths[2]);
  60208. shapePaths[1] = shapePaths[2];
  60209. break;
  60210. case BABYLON.Mesh.CAP_END:
  60211. shapePaths[index] = shapePaths[index - 1];
  60212. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60213. break;
  60214. case BABYLON.Mesh.CAP_ALL:
  60215. shapePaths[0] = capPath(shapePaths[2]);
  60216. shapePaths[1] = shapePaths[2];
  60217. shapePaths[index] = shapePaths[index - 1];
  60218. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  60219. break;
  60220. default:
  60221. break;
  60222. }
  60223. return shapePaths;
  60224. };
  60225. var path3D;
  60226. var pathArray;
  60227. if (instance) {
  60228. path3D = (instance.path3D).update(curve);
  60229. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  60230. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  60231. return instance;
  60232. }
  60233. // extruded shape creation
  60234. path3D = new BABYLON.Path3D(curve);
  60235. var newShapePaths = new Array();
  60236. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60237. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  60238. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  60239. extrudedGeneric.pathArray = pathArray;
  60240. extrudedGeneric.path3D = path3D;
  60241. extrudedGeneric.cap = cap;
  60242. return extrudedGeneric;
  60243. };
  60244. return MeshBuilder;
  60245. }());
  60246. BABYLON.MeshBuilder = MeshBuilder;
  60247. })(BABYLON || (BABYLON = {}));
  60248. //# sourceMappingURL=babylon.meshBuilder.js.map
  60249. "use strict";
  60250. var BABYLON;
  60251. (function (BABYLON) {
  60252. /**
  60253. * Draco compression (https://google.github.io/draco/)
  60254. */
  60255. var DracoCompression = /** @class */ (function () {
  60256. /**
  60257. * Constructor
  60258. * @param numWorkers The number of workers for async operations
  60259. */
  60260. function DracoCompression(numWorkers) {
  60261. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  60262. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  60263. if (!workerBlobUrl || !Worker) {
  60264. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  60265. return;
  60266. }
  60267. var workers = new Array(numWorkers);
  60268. for (var i = 0; i < workers.length; i++) {
  60269. var worker = new Worker(workerBlobUrl);
  60270. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  60271. workers[i] = worker;
  60272. }
  60273. this._workerPool = new BABYLON.WorkerPool(workers);
  60274. }
  60275. /**
  60276. * Stop all async operations and release resources.
  60277. */
  60278. DracoCompression.prototype.dispose = function () {
  60279. this._workerPool.dispose();
  60280. delete this._workerPool;
  60281. };
  60282. /**
  60283. * Decode Draco compressed mesh data to vertex data.
  60284. * @param data The array buffer view for the Draco compression data
  60285. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  60286. * @returns A promise that resolves with the decoded vertex data
  60287. */
  60288. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  60289. var _this = this;
  60290. return new Promise(function (resolve, reject) {
  60291. _this._workerPool.push(function (worker, onComplete) {
  60292. var vertexData = new BABYLON.VertexData();
  60293. var onError = function (error) {
  60294. worker.removeEventListener("error", onError);
  60295. worker.removeEventListener("message", onMessage);
  60296. reject(error);
  60297. onComplete();
  60298. };
  60299. var onMessage = function (message) {
  60300. if (message.data === "done") {
  60301. worker.removeEventListener("error", onError);
  60302. worker.removeEventListener("message", onMessage);
  60303. resolve(vertexData);
  60304. onComplete();
  60305. }
  60306. else if (message.data.id === "indices") {
  60307. vertexData.indices = message.data.value;
  60308. }
  60309. else {
  60310. vertexData.set(message.data.value, message.data.id);
  60311. }
  60312. };
  60313. worker.addEventListener("error", onError);
  60314. worker.addEventListener("message", onMessage);
  60315. var dataCopy = new Uint8Array(data.byteLength);
  60316. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  60317. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  60318. });
  60319. });
  60320. };
  60321. /**
  60322. * The worker function that gets converted to a blob url to pass into a worker.
  60323. */
  60324. DracoCompression._Worker = function () {
  60325. // self is actually a DedicatedWorkerGlobalScope
  60326. var _self = self;
  60327. var decodeMesh = function (data, attributes) {
  60328. var dracoModule = new DracoDecoderModule();
  60329. var buffer = new dracoModule.DecoderBuffer();
  60330. buffer.Init(data, data.byteLength);
  60331. var decoder = new dracoModule.Decoder();
  60332. var geometry;
  60333. var status;
  60334. try {
  60335. var type = decoder.GetEncodedGeometryType(buffer);
  60336. switch (type) {
  60337. case dracoModule.TRIANGULAR_MESH:
  60338. geometry = new dracoModule.Mesh();
  60339. status = decoder.DecodeBufferToMesh(buffer, geometry);
  60340. break;
  60341. case dracoModule.POINT_CLOUD:
  60342. geometry = new dracoModule.PointCloud();
  60343. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  60344. break;
  60345. default:
  60346. throw new Error("Invalid geometry type " + type);
  60347. }
  60348. if (!status.ok() || !geometry.ptr) {
  60349. throw new Error(status.error_msg());
  60350. }
  60351. var numPoints = geometry.num_points();
  60352. if (type === dracoModule.TRIANGULAR_MESH) {
  60353. var numFaces = geometry.num_faces();
  60354. var faceIndices = new dracoModule.DracoInt32Array();
  60355. try {
  60356. var indices = new Uint32Array(numFaces * 3);
  60357. for (var i = 0; i < numFaces; i++) {
  60358. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  60359. var offset = i * 3;
  60360. indices[offset + 0] = faceIndices.GetValue(0);
  60361. indices[offset + 1] = faceIndices.GetValue(1);
  60362. indices[offset + 2] = faceIndices.GetValue(2);
  60363. }
  60364. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  60365. }
  60366. finally {
  60367. dracoModule.destroy(faceIndices);
  60368. }
  60369. }
  60370. for (var kind in attributes) {
  60371. var uniqueId = attributes[kind];
  60372. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  60373. var dracoData = new dracoModule.DracoFloat32Array();
  60374. try {
  60375. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  60376. var babylonData = new Float32Array(numPoints * attribute.num_components());
  60377. for (var i = 0; i < babylonData.length; i++) {
  60378. babylonData[i] = dracoData.GetValue(i);
  60379. }
  60380. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  60381. }
  60382. finally {
  60383. dracoModule.destroy(dracoData);
  60384. }
  60385. }
  60386. }
  60387. finally {
  60388. if (geometry) {
  60389. dracoModule.destroy(geometry);
  60390. }
  60391. dracoModule.destroy(decoder);
  60392. dracoModule.destroy(buffer);
  60393. }
  60394. _self.postMessage("done");
  60395. };
  60396. _self.onmessage = function (event) {
  60397. switch (event.data.id) {
  60398. case "initDecoder": {
  60399. importScripts(event.data.url);
  60400. break;
  60401. }
  60402. case "decodeMesh": {
  60403. decodeMesh(event.data.data, event.data.attributes);
  60404. break;
  60405. }
  60406. }
  60407. };
  60408. };
  60409. DracoCompression._GetDefaultDecoderUrl = function () {
  60410. if (!BABYLON.Tools.IsWindowObjectExist()) {
  60411. return null;
  60412. }
  60413. for (var i = 0; i < document.scripts.length; i++) {
  60414. if (document.scripts[i].type === "text/x-draco-decoder") {
  60415. return document.scripts[i].src;
  60416. }
  60417. }
  60418. return null;
  60419. };
  60420. /**
  60421. * Gets the url to the draco decoder if available.
  60422. */
  60423. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  60424. return DracoCompression;
  60425. }());
  60426. BABYLON.DracoCompression = DracoCompression;
  60427. })(BABYLON || (BABYLON = {}));
  60428. //# sourceMappingURL=babylon.dracoCompression.js.map
  60429. "use strict";
  60430. var BABYLON;
  60431. (function (BABYLON) {
  60432. var AudioEngine = /** @class */ (function () {
  60433. function AudioEngine() {
  60434. this._audioContext = null;
  60435. this._audioContextInitialized = false;
  60436. this.canUseWebAudio = false;
  60437. this.WarnedWebAudioUnsupported = false;
  60438. this.unlocked = false;
  60439. this.isMP3supported = false;
  60440. this.isOGGsupported = false;
  60441. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  60442. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  60443. this.canUseWebAudio = true;
  60444. }
  60445. var audioElem = document.createElement('audio');
  60446. try {
  60447. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  60448. this.isMP3supported = true;
  60449. }
  60450. }
  60451. catch (e) {
  60452. // protect error during capability check.
  60453. }
  60454. try {
  60455. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  60456. this.isOGGsupported = true;
  60457. }
  60458. }
  60459. catch (e) {
  60460. // protect error during capability check.
  60461. }
  60462. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  60463. this._unlockiOSaudio();
  60464. }
  60465. else {
  60466. this.unlocked = true;
  60467. }
  60468. }
  60469. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  60470. get: function () {
  60471. if (!this._audioContextInitialized) {
  60472. this._initializeAudioContext();
  60473. }
  60474. return this._audioContext;
  60475. },
  60476. enumerable: true,
  60477. configurable: true
  60478. });
  60479. AudioEngine.prototype._unlockiOSaudio = function () {
  60480. var _this = this;
  60481. var unlockaudio = function () {
  60482. if (!_this.audioContext) {
  60483. return;
  60484. }
  60485. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  60486. var source = _this.audioContext.createBufferSource();
  60487. source.buffer = buffer;
  60488. source.connect(_this.audioContext.destination);
  60489. source.start(0);
  60490. setTimeout(function () {
  60491. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  60492. _this.unlocked = true;
  60493. window.removeEventListener('touchend', unlockaudio, false);
  60494. if (_this.onAudioUnlocked) {
  60495. _this.onAudioUnlocked();
  60496. }
  60497. }
  60498. }, 0);
  60499. };
  60500. window.addEventListener('touchend', unlockaudio, false);
  60501. };
  60502. AudioEngine.prototype._initializeAudioContext = function () {
  60503. try {
  60504. if (this.canUseWebAudio) {
  60505. this._audioContext = new AudioContext();
  60506. // create a global volume gain node
  60507. this.masterGain = this._audioContext.createGain();
  60508. this.masterGain.gain.value = 1;
  60509. this.masterGain.connect(this._audioContext.destination);
  60510. this._audioContextInitialized = true;
  60511. }
  60512. }
  60513. catch (e) {
  60514. this.canUseWebAudio = false;
  60515. BABYLON.Tools.Error("Web Audio: " + e.message);
  60516. }
  60517. };
  60518. AudioEngine.prototype.dispose = function () {
  60519. if (this.canUseWebAudio && this._audioContextInitialized) {
  60520. if (this._connectedAnalyser && this._audioContext) {
  60521. this._connectedAnalyser.stopDebugCanvas();
  60522. this._connectedAnalyser.dispose();
  60523. this.masterGain.disconnect();
  60524. this.masterGain.connect(this._audioContext.destination);
  60525. this._connectedAnalyser = null;
  60526. }
  60527. this.masterGain.gain.value = 1;
  60528. }
  60529. this.WarnedWebAudioUnsupported = false;
  60530. };
  60531. AudioEngine.prototype.getGlobalVolume = function () {
  60532. if (this.canUseWebAudio && this._audioContextInitialized) {
  60533. return this.masterGain.gain.value;
  60534. }
  60535. else {
  60536. return -1;
  60537. }
  60538. };
  60539. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  60540. if (this.canUseWebAudio && this._audioContextInitialized) {
  60541. this.masterGain.gain.value = newVolume;
  60542. }
  60543. };
  60544. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  60545. if (this._connectedAnalyser) {
  60546. this._connectedAnalyser.stopDebugCanvas();
  60547. }
  60548. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  60549. this._connectedAnalyser = analyser;
  60550. this.masterGain.disconnect();
  60551. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  60552. }
  60553. };
  60554. return AudioEngine;
  60555. }());
  60556. BABYLON.AudioEngine = AudioEngine;
  60557. })(BABYLON || (BABYLON = {}));
  60558. //# sourceMappingURL=babylon.audioEngine.js.map
  60559. "use strict";
  60560. var BABYLON;
  60561. (function (BABYLON) {
  60562. var Sound = /** @class */ (function () {
  60563. /**
  60564. * Create a sound and attach it to a scene
  60565. * @param name Name of your sound
  60566. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  60567. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  60568. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  60569. */
  60570. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  60571. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  60572. var _this = this;
  60573. this.autoplay = false;
  60574. this.loop = false;
  60575. this.useCustomAttenuation = false;
  60576. this.spatialSound = false;
  60577. this.refDistance = 1;
  60578. this.rolloffFactor = 1;
  60579. this.maxDistance = 100;
  60580. this.distanceModel = "linear";
  60581. this._panningModel = "equalpower";
  60582. this._playbackRate = 1;
  60583. this._streaming = false;
  60584. this._startTime = 0;
  60585. this._startOffset = 0;
  60586. this._position = BABYLON.Vector3.Zero();
  60587. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  60588. this._volume = 1;
  60589. this._isReadyToPlay = false;
  60590. this.isPlaying = false;
  60591. this.isPaused = false;
  60592. this._isDirectional = false;
  60593. // Used if you'd like to create a directional sound.
  60594. // If not set, the sound will be omnidirectional
  60595. this._coneInnerAngle = 360;
  60596. this._coneOuterAngle = 360;
  60597. this._coneOuterGain = 0;
  60598. this._isOutputConnected = false;
  60599. this._urlType = "Unknown";
  60600. this.name = name;
  60601. this._scene = scene;
  60602. this._readyToPlayCallback = readyToPlayCallback;
  60603. // Default custom attenuation function is a linear attenuation
  60604. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  60605. if (currentDistance < maxDistance) {
  60606. return currentVolume * (1 - currentDistance / maxDistance);
  60607. }
  60608. else {
  60609. return 0;
  60610. }
  60611. };
  60612. if (options) {
  60613. this.autoplay = options.autoplay || false;
  60614. this.loop = options.loop || false;
  60615. // if volume === 0, we need another way to check this option
  60616. if (options.volume !== undefined) {
  60617. this._volume = options.volume;
  60618. }
  60619. this.spatialSound = options.spatialSound || false;
  60620. this.maxDistance = options.maxDistance || 100;
  60621. this.useCustomAttenuation = options.useCustomAttenuation || false;
  60622. this.rolloffFactor = options.rolloffFactor || 1;
  60623. this.refDistance = options.refDistance || 1;
  60624. this.distanceModel = options.distanceModel || "linear";
  60625. this._playbackRate = options.playbackRate || 1;
  60626. this._streaming = options.streaming || false;
  60627. }
  60628. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60629. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  60630. this._soundGain.gain.value = this._volume;
  60631. this._inputAudioNode = this._soundGain;
  60632. this._ouputAudioNode = this._soundGain;
  60633. if (this.spatialSound) {
  60634. this._createSpatialParameters();
  60635. }
  60636. this._scene.mainSoundTrack.AddSound(this);
  60637. var validParameter = true;
  60638. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  60639. if (urlOrArrayBuffer) {
  60640. try {
  60641. if (typeof (urlOrArrayBuffer) === "string")
  60642. this._urlType = "String";
  60643. if (Array.isArray(urlOrArrayBuffer))
  60644. this._urlType = "Array";
  60645. if (urlOrArrayBuffer instanceof ArrayBuffer)
  60646. this._urlType = "ArrayBuffer";
  60647. var urls = [];
  60648. var codecSupportedFound = false;
  60649. switch (this._urlType) {
  60650. case "ArrayBuffer":
  60651. if (urlOrArrayBuffer.byteLength > 0) {
  60652. codecSupportedFound = true;
  60653. this._soundLoaded(urlOrArrayBuffer);
  60654. }
  60655. break;
  60656. case "String":
  60657. urls.push(urlOrArrayBuffer);
  60658. case "Array":
  60659. if (urls.length === 0)
  60660. urls = urlOrArrayBuffer;
  60661. // If we found a supported format, we load it immediately and stop the loop
  60662. for (var i = 0; i < urls.length; i++) {
  60663. var url = urls[i];
  60664. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  60665. codecSupportedFound = true;
  60666. }
  60667. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  60668. codecSupportedFound = true;
  60669. }
  60670. if (url.indexOf(".wav", url.length - 4) !== -1) {
  60671. codecSupportedFound = true;
  60672. }
  60673. if (url.indexOf("blob:") !== -1) {
  60674. codecSupportedFound = true;
  60675. }
  60676. if (codecSupportedFound) {
  60677. // Loading sound using XHR2
  60678. if (!this._streaming) {
  60679. this._scene._loadFile(url, function (data) {
  60680. _this._soundLoaded(data);
  60681. }, undefined, true, true, function (exception) {
  60682. if (exception) {
  60683. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  60684. }
  60685. BABYLON.Tools.Error("Sound creation aborted.");
  60686. _this._scene.mainSoundTrack.RemoveSound(_this);
  60687. });
  60688. }
  60689. else {
  60690. this._htmlAudioElement = new Audio(url);
  60691. this._htmlAudioElement.controls = false;
  60692. this._htmlAudioElement.loop = this.loop;
  60693. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  60694. this._htmlAudioElement.preload = "auto";
  60695. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  60696. _this._isReadyToPlay = true;
  60697. if (_this.autoplay) {
  60698. _this.play();
  60699. }
  60700. if (_this._readyToPlayCallback) {
  60701. _this._readyToPlayCallback();
  60702. }
  60703. });
  60704. document.body.appendChild(this._htmlAudioElement);
  60705. }
  60706. break;
  60707. }
  60708. }
  60709. break;
  60710. default:
  60711. validParameter = false;
  60712. break;
  60713. }
  60714. if (!validParameter) {
  60715. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  60716. }
  60717. else {
  60718. if (!codecSupportedFound) {
  60719. this._isReadyToPlay = true;
  60720. // Simulating a ready to play event to avoid breaking code path
  60721. if (this._readyToPlayCallback) {
  60722. window.setTimeout(function () {
  60723. if (_this._readyToPlayCallback) {
  60724. _this._readyToPlayCallback();
  60725. }
  60726. }, 1000);
  60727. }
  60728. }
  60729. }
  60730. }
  60731. catch (ex) {
  60732. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  60733. this._scene.mainSoundTrack.RemoveSound(this);
  60734. }
  60735. }
  60736. }
  60737. else {
  60738. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  60739. this._scene.mainSoundTrack.AddSound(this);
  60740. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  60741. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  60742. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  60743. }
  60744. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  60745. if (this._readyToPlayCallback) {
  60746. window.setTimeout(function () {
  60747. if (_this._readyToPlayCallback) {
  60748. _this._readyToPlayCallback();
  60749. }
  60750. }, 1000);
  60751. }
  60752. }
  60753. }
  60754. Sound.prototype.dispose = function () {
  60755. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60756. if (this.isPlaying) {
  60757. this.stop();
  60758. }
  60759. this._isReadyToPlay = false;
  60760. if (this.soundTrackId === -1) {
  60761. this._scene.mainSoundTrack.RemoveSound(this);
  60762. }
  60763. else {
  60764. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  60765. }
  60766. if (this._soundGain) {
  60767. this._soundGain.disconnect();
  60768. this._soundGain = null;
  60769. }
  60770. if (this._soundPanner) {
  60771. this._soundPanner.disconnect();
  60772. this._soundPanner = null;
  60773. }
  60774. if (this._soundSource) {
  60775. this._soundSource.disconnect();
  60776. this._soundSource = null;
  60777. }
  60778. this._audioBuffer = null;
  60779. if (this._htmlAudioElement) {
  60780. this._htmlAudioElement.pause();
  60781. this._htmlAudioElement.src = "";
  60782. document.body.removeChild(this._htmlAudioElement);
  60783. }
  60784. if (this._connectedMesh && this._registerFunc) {
  60785. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  60786. this._connectedMesh = null;
  60787. }
  60788. }
  60789. };
  60790. Sound.prototype.isReady = function () {
  60791. return this._isReadyToPlay;
  60792. };
  60793. Sound.prototype._soundLoaded = function (audioData) {
  60794. var _this = this;
  60795. if (!BABYLON.Engine.audioEngine.audioContext) {
  60796. return;
  60797. }
  60798. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  60799. _this._audioBuffer = buffer;
  60800. _this._isReadyToPlay = true;
  60801. if (_this.autoplay) {
  60802. _this.play();
  60803. }
  60804. if (_this._readyToPlayCallback) {
  60805. _this._readyToPlayCallback();
  60806. }
  60807. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  60808. };
  60809. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  60810. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60811. this._audioBuffer = audioBuffer;
  60812. this._isReadyToPlay = true;
  60813. }
  60814. };
  60815. Sound.prototype.updateOptions = function (options) {
  60816. if (options) {
  60817. this.loop = options.loop || this.loop;
  60818. this.maxDistance = options.maxDistance || this.maxDistance;
  60819. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  60820. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  60821. this.refDistance = options.refDistance || this.refDistance;
  60822. this.distanceModel = options.distanceModel || this.distanceModel;
  60823. this._playbackRate = options.playbackRate || this._playbackRate;
  60824. this._updateSpatialParameters();
  60825. if (this.isPlaying) {
  60826. if (this._streaming) {
  60827. this._htmlAudioElement.playbackRate = this._playbackRate;
  60828. }
  60829. else {
  60830. if (this._soundSource) {
  60831. this._soundSource.playbackRate.value = this._playbackRate;
  60832. }
  60833. }
  60834. }
  60835. }
  60836. };
  60837. Sound.prototype._createSpatialParameters = function () {
  60838. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  60839. if (this._scene.headphone) {
  60840. this._panningModel = "HRTF";
  60841. }
  60842. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  60843. this._updateSpatialParameters();
  60844. this._soundPanner.connect(this._ouputAudioNode);
  60845. this._inputAudioNode = this._soundPanner;
  60846. }
  60847. };
  60848. Sound.prototype._updateSpatialParameters = function () {
  60849. if (this.spatialSound && this._soundPanner) {
  60850. if (this.useCustomAttenuation) {
  60851. // Tricks to disable in a way embedded Web Audio attenuation
  60852. this._soundPanner.distanceModel = "linear";
  60853. this._soundPanner.maxDistance = Number.MAX_VALUE;
  60854. this._soundPanner.refDistance = 1;
  60855. this._soundPanner.rolloffFactor = 1;
  60856. this._soundPanner.panningModel = this._panningModel;
  60857. }
  60858. else {
  60859. this._soundPanner.distanceModel = this.distanceModel;
  60860. this._soundPanner.maxDistance = this.maxDistance;
  60861. this._soundPanner.refDistance = this.refDistance;
  60862. this._soundPanner.rolloffFactor = this.rolloffFactor;
  60863. this._soundPanner.panningModel = this._panningModel;
  60864. }
  60865. }
  60866. };
  60867. Sound.prototype.switchPanningModelToHRTF = function () {
  60868. this._panningModel = "HRTF";
  60869. this._switchPanningModel();
  60870. };
  60871. Sound.prototype.switchPanningModelToEqualPower = function () {
  60872. this._panningModel = "equalpower";
  60873. this._switchPanningModel();
  60874. };
  60875. Sound.prototype._switchPanningModel = function () {
  60876. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  60877. this._soundPanner.panningModel = this._panningModel;
  60878. }
  60879. };
  60880. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  60881. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60882. if (this._isOutputConnected) {
  60883. this._ouputAudioNode.disconnect();
  60884. }
  60885. this._ouputAudioNode.connect(soundTrackAudioNode);
  60886. this._isOutputConnected = true;
  60887. }
  60888. };
  60889. /**
  60890. * Transform this sound into a directional source
  60891. * @param coneInnerAngle Size of the inner cone in degree
  60892. * @param coneOuterAngle Size of the outer cone in degree
  60893. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  60894. */
  60895. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  60896. if (coneOuterAngle < coneInnerAngle) {
  60897. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  60898. return;
  60899. }
  60900. this._coneInnerAngle = coneInnerAngle;
  60901. this._coneOuterAngle = coneOuterAngle;
  60902. this._coneOuterGain = coneOuterGain;
  60903. this._isDirectional = true;
  60904. if (this.isPlaying && this.loop) {
  60905. this.stop();
  60906. this.play();
  60907. }
  60908. };
  60909. Sound.prototype.setPosition = function (newPosition) {
  60910. this._position = newPosition;
  60911. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  60912. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  60913. }
  60914. };
  60915. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  60916. this._localDirection = newLocalDirection;
  60917. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  60918. this._updateDirection();
  60919. }
  60920. };
  60921. Sound.prototype._updateDirection = function () {
  60922. if (!this._connectedMesh || !this._soundPanner) {
  60923. return;
  60924. }
  60925. var mat = this._connectedMesh.getWorldMatrix();
  60926. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  60927. direction.normalize();
  60928. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  60929. };
  60930. Sound.prototype.updateDistanceFromListener = function () {
  60931. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  60932. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  60933. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  60934. }
  60935. };
  60936. Sound.prototype.setAttenuationFunction = function (callback) {
  60937. this._customAttenuationFunction = callback;
  60938. };
  60939. /**
  60940. * Play the sound
  60941. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  60942. * @param offset (optional) Start the sound setting it at a specific time
  60943. */
  60944. Sound.prototype.play = function (time, offset) {
  60945. var _this = this;
  60946. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  60947. try {
  60948. if (this._startOffset < 0) {
  60949. time = -this._startOffset;
  60950. this._startOffset = 0;
  60951. }
  60952. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  60953. if (!this._soundSource || !this._streamingSource) {
  60954. if (this.spatialSound && this._soundPanner) {
  60955. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  60956. if (this._isDirectional) {
  60957. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  60958. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  60959. this._soundPanner.coneOuterGain = this._coneOuterGain;
  60960. if (this._connectedMesh) {
  60961. this._updateDirection();
  60962. }
  60963. else {
  60964. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  60965. }
  60966. }
  60967. }
  60968. }
  60969. if (this._streaming) {
  60970. if (!this._streamingSource) {
  60971. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  60972. this._htmlAudioElement.onended = function () { _this._onended(); };
  60973. this._htmlAudioElement.playbackRate = this._playbackRate;
  60974. }
  60975. this._streamingSource.disconnect();
  60976. this._streamingSource.connect(this._inputAudioNode);
  60977. this._htmlAudioElement.play();
  60978. }
  60979. else {
  60980. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  60981. this._soundSource.buffer = this._audioBuffer;
  60982. this._soundSource.connect(this._inputAudioNode);
  60983. this._soundSource.loop = this.loop;
  60984. this._soundSource.playbackRate.value = this._playbackRate;
  60985. this._soundSource.onended = function () { _this._onended(); };
  60986. if (this._soundSource.buffer) {
  60987. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  60988. }
  60989. }
  60990. this._startTime = startTime;
  60991. this.isPlaying = true;
  60992. this.isPaused = false;
  60993. }
  60994. catch (ex) {
  60995. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  60996. }
  60997. }
  60998. };
  60999. Sound.prototype._onended = function () {
  61000. this.isPlaying = false;
  61001. if (this.onended) {
  61002. this.onended();
  61003. }
  61004. };
  61005. /**
  61006. * Stop the sound
  61007. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61008. */
  61009. Sound.prototype.stop = function (time) {
  61010. if (this.isPlaying) {
  61011. if (this._streaming) {
  61012. this._htmlAudioElement.pause();
  61013. // Test needed for Firefox or it will generate an Invalid State Error
  61014. if (this._htmlAudioElement.currentTime > 0) {
  61015. this._htmlAudioElement.currentTime = 0;
  61016. }
  61017. }
  61018. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61019. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61020. this._soundSource.stop(stopTime);
  61021. this._soundSource.onended = function () { };
  61022. if (!this.isPaused) {
  61023. this._startOffset = 0;
  61024. }
  61025. }
  61026. this.isPlaying = false;
  61027. }
  61028. };
  61029. Sound.prototype.pause = function () {
  61030. if (this.isPlaying) {
  61031. this.isPaused = true;
  61032. if (this._streaming) {
  61033. this._htmlAudioElement.pause();
  61034. }
  61035. else if (BABYLON.Engine.audioEngine.audioContext) {
  61036. this.stop(0);
  61037. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61038. }
  61039. }
  61040. };
  61041. Sound.prototype.setVolume = function (newVolume, time) {
  61042. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61043. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61044. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61045. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61046. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61047. }
  61048. else {
  61049. this._soundGain.gain.value = newVolume;
  61050. }
  61051. }
  61052. this._volume = newVolume;
  61053. };
  61054. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  61055. this._playbackRate = newPlaybackRate;
  61056. if (this.isPlaying) {
  61057. if (this._streaming) {
  61058. this._htmlAudioElement.playbackRate = this._playbackRate;
  61059. }
  61060. else if (this._soundSource) {
  61061. this._soundSource.playbackRate.value = this._playbackRate;
  61062. }
  61063. }
  61064. };
  61065. Sound.prototype.getVolume = function () {
  61066. return this._volume;
  61067. };
  61068. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  61069. var _this = this;
  61070. if (this._connectedMesh && this._registerFunc) {
  61071. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61072. this._registerFunc = null;
  61073. }
  61074. this._connectedMesh = meshToConnectTo;
  61075. if (!this.spatialSound) {
  61076. this.spatialSound = true;
  61077. this._createSpatialParameters();
  61078. if (this.isPlaying && this.loop) {
  61079. this.stop();
  61080. this.play();
  61081. }
  61082. }
  61083. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  61084. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  61085. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  61086. };
  61087. Sound.prototype.detachFromMesh = function () {
  61088. if (this._connectedMesh && this._registerFunc) {
  61089. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61090. this._registerFunc = null;
  61091. this._connectedMesh = null;
  61092. }
  61093. };
  61094. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  61095. if (!node.getBoundingInfo) {
  61096. return;
  61097. }
  61098. var mesh = node;
  61099. var boundingInfo = mesh.getBoundingInfo();
  61100. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  61101. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  61102. this._updateDirection();
  61103. }
  61104. };
  61105. Sound.prototype.clone = function () {
  61106. var _this = this;
  61107. if (!this._streaming) {
  61108. var setBufferAndRun = function () {
  61109. if (_this._isReadyToPlay) {
  61110. clonedSound._audioBuffer = _this.getAudioBuffer();
  61111. clonedSound._isReadyToPlay = true;
  61112. if (clonedSound.autoplay) {
  61113. clonedSound.play();
  61114. }
  61115. }
  61116. else {
  61117. window.setTimeout(setBufferAndRun, 300);
  61118. }
  61119. };
  61120. var currentOptions = {
  61121. autoplay: this.autoplay, loop: this.loop,
  61122. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  61123. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  61124. refDistance: this.refDistance, distanceModel: this.distanceModel
  61125. };
  61126. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  61127. if (this.useCustomAttenuation) {
  61128. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  61129. }
  61130. clonedSound.setPosition(this._position);
  61131. clonedSound.setPlaybackRate(this._playbackRate);
  61132. setBufferAndRun();
  61133. return clonedSound;
  61134. }
  61135. else {
  61136. return null;
  61137. }
  61138. };
  61139. Sound.prototype.getAudioBuffer = function () {
  61140. return this._audioBuffer;
  61141. };
  61142. Sound.prototype.serialize = function () {
  61143. var serializationObject = {
  61144. name: this.name,
  61145. url: this.name,
  61146. autoplay: this.autoplay,
  61147. loop: this.loop,
  61148. volume: this._volume,
  61149. spatialSound: this.spatialSound,
  61150. maxDistance: this.maxDistance,
  61151. rolloffFactor: this.rolloffFactor,
  61152. refDistance: this.refDistance,
  61153. distanceModel: this.distanceModel,
  61154. playbackRate: this._playbackRate,
  61155. panningModel: this._panningModel,
  61156. soundTrackId: this.soundTrackId
  61157. };
  61158. if (this.spatialSound) {
  61159. if (this._connectedMesh)
  61160. serializationObject.connectedMeshId = this._connectedMesh.id;
  61161. serializationObject.position = this._position.asArray();
  61162. serializationObject.refDistance = this.refDistance;
  61163. serializationObject.distanceModel = this.distanceModel;
  61164. serializationObject.isDirectional = this._isDirectional;
  61165. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  61166. serializationObject.coneInnerAngle = this._coneInnerAngle;
  61167. serializationObject.coneOuterAngle = this._coneOuterAngle;
  61168. serializationObject.coneOuterGain = this._coneOuterGain;
  61169. }
  61170. return serializationObject;
  61171. };
  61172. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  61173. var soundName = parsedSound.name;
  61174. var soundUrl;
  61175. if (parsedSound.url) {
  61176. soundUrl = rootUrl + parsedSound.url;
  61177. }
  61178. else {
  61179. soundUrl = rootUrl + soundName;
  61180. }
  61181. var options = {
  61182. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  61183. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  61184. rolloffFactor: parsedSound.rolloffFactor,
  61185. refDistance: parsedSound.refDistance,
  61186. distanceModel: parsedSound.distanceModel,
  61187. playbackRate: parsedSound.playbackRate
  61188. };
  61189. var newSound;
  61190. if (!sourceSound) {
  61191. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  61192. scene._addPendingData(newSound);
  61193. }
  61194. else {
  61195. var setBufferAndRun = function () {
  61196. if (sourceSound._isReadyToPlay) {
  61197. newSound._audioBuffer = sourceSound.getAudioBuffer();
  61198. newSound._isReadyToPlay = true;
  61199. if (newSound.autoplay) {
  61200. newSound.play();
  61201. }
  61202. }
  61203. else {
  61204. window.setTimeout(setBufferAndRun, 300);
  61205. }
  61206. };
  61207. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  61208. setBufferAndRun();
  61209. }
  61210. if (parsedSound.position) {
  61211. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  61212. newSound.setPosition(soundPosition);
  61213. }
  61214. if (parsedSound.isDirectional) {
  61215. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  61216. if (parsedSound.localDirectionToMesh) {
  61217. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  61218. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  61219. }
  61220. }
  61221. if (parsedSound.connectedMeshId) {
  61222. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  61223. if (connectedMesh) {
  61224. newSound.attachToMesh(connectedMesh);
  61225. }
  61226. }
  61227. return newSound;
  61228. };
  61229. return Sound;
  61230. }());
  61231. BABYLON.Sound = Sound;
  61232. })(BABYLON || (BABYLON = {}));
  61233. //# sourceMappingURL=babylon.sound.js.map
  61234. "use strict";
  61235. var BABYLON;
  61236. (function (BABYLON) {
  61237. var SoundTrack = /** @class */ (function () {
  61238. function SoundTrack(scene, options) {
  61239. this.id = -1;
  61240. this._isMainTrack = false;
  61241. this._isInitialized = false;
  61242. this._scene = scene;
  61243. this.soundCollection = new Array();
  61244. this._options = options;
  61245. if (!this._isMainTrack) {
  61246. this._scene.soundTracks.push(this);
  61247. this.id = this._scene.soundTracks.length - 1;
  61248. }
  61249. }
  61250. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  61251. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61252. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  61253. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  61254. if (this._options) {
  61255. if (this._options.volume) {
  61256. this._outputAudioNode.gain.value = this._options.volume;
  61257. }
  61258. if (this._options.mainTrack) {
  61259. this._isMainTrack = this._options.mainTrack;
  61260. }
  61261. }
  61262. this._isInitialized = true;
  61263. }
  61264. };
  61265. SoundTrack.prototype.dispose = function () {
  61266. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  61267. if (this._connectedAnalyser) {
  61268. this._connectedAnalyser.stopDebugCanvas();
  61269. }
  61270. while (this.soundCollection.length) {
  61271. this.soundCollection[0].dispose();
  61272. }
  61273. if (this._outputAudioNode) {
  61274. this._outputAudioNode.disconnect();
  61275. }
  61276. this._outputAudioNode = null;
  61277. }
  61278. };
  61279. SoundTrack.prototype.AddSound = function (sound) {
  61280. if (!this._isInitialized) {
  61281. this._initializeSoundTrackAudioGraph();
  61282. }
  61283. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61284. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  61285. }
  61286. if (sound.soundTrackId) {
  61287. if (sound.soundTrackId === -1) {
  61288. this._scene.mainSoundTrack.RemoveSound(sound);
  61289. }
  61290. else {
  61291. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  61292. }
  61293. }
  61294. this.soundCollection.push(sound);
  61295. sound.soundTrackId = this.id;
  61296. };
  61297. SoundTrack.prototype.RemoveSound = function (sound) {
  61298. var index = this.soundCollection.indexOf(sound);
  61299. if (index !== -1) {
  61300. this.soundCollection.splice(index, 1);
  61301. }
  61302. };
  61303. SoundTrack.prototype.setVolume = function (newVolume) {
  61304. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61305. this._outputAudioNode.gain.value = newVolume;
  61306. }
  61307. };
  61308. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  61309. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61310. for (var i = 0; i < this.soundCollection.length; i++) {
  61311. this.soundCollection[i].switchPanningModelToHRTF();
  61312. }
  61313. }
  61314. };
  61315. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  61316. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61317. for (var i = 0; i < this.soundCollection.length; i++) {
  61318. this.soundCollection[i].switchPanningModelToEqualPower();
  61319. }
  61320. }
  61321. };
  61322. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  61323. if (this._connectedAnalyser) {
  61324. this._connectedAnalyser.stopDebugCanvas();
  61325. }
  61326. this._connectedAnalyser = analyser;
  61327. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  61328. this._outputAudioNode.disconnect();
  61329. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  61330. }
  61331. };
  61332. return SoundTrack;
  61333. }());
  61334. BABYLON.SoundTrack = SoundTrack;
  61335. })(BABYLON || (BABYLON = {}));
  61336. //# sourceMappingURL=babylon.soundtrack.js.map
  61337. "use strict";
  61338. var BABYLON;
  61339. (function (BABYLON) {
  61340. var Analyser = /** @class */ (function () {
  61341. function Analyser(scene) {
  61342. this.SMOOTHING = 0.75;
  61343. this.FFT_SIZE = 512;
  61344. this.BARGRAPHAMPLITUDE = 256;
  61345. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  61346. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  61347. this._scene = scene;
  61348. this._audioEngine = BABYLON.Engine.audioEngine;
  61349. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  61350. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  61351. this._webAudioAnalyser.minDecibels = -140;
  61352. this._webAudioAnalyser.maxDecibels = 0;
  61353. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61354. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  61355. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  61356. }
  61357. }
  61358. Analyser.prototype.getFrequencyBinCount = function () {
  61359. if (this._audioEngine.canUseWebAudio) {
  61360. return this._webAudioAnalyser.frequencyBinCount;
  61361. }
  61362. else {
  61363. return 0;
  61364. }
  61365. };
  61366. Analyser.prototype.getByteFrequencyData = function () {
  61367. if (this._audioEngine.canUseWebAudio) {
  61368. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61369. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61370. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  61371. }
  61372. return this._byteFreqs;
  61373. };
  61374. Analyser.prototype.getByteTimeDomainData = function () {
  61375. if (this._audioEngine.canUseWebAudio) {
  61376. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61377. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61378. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  61379. }
  61380. return this._byteTime;
  61381. };
  61382. Analyser.prototype.getFloatFrequencyData = function () {
  61383. if (this._audioEngine.canUseWebAudio) {
  61384. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  61385. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  61386. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  61387. }
  61388. return this._floatFreqs;
  61389. };
  61390. Analyser.prototype.drawDebugCanvas = function () {
  61391. var _this = this;
  61392. if (this._audioEngine.canUseWebAudio) {
  61393. if (!this._debugCanvas) {
  61394. this._debugCanvas = document.createElement("canvas");
  61395. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  61396. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  61397. this._debugCanvas.style.position = "absolute";
  61398. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  61399. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  61400. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  61401. document.body.appendChild(this._debugCanvas);
  61402. this._registerFunc = function () {
  61403. _this.drawDebugCanvas();
  61404. };
  61405. this._scene.registerBeforeRender(this._registerFunc);
  61406. }
  61407. if (this._registerFunc && this._debugCanvasContext) {
  61408. var workingArray = this.getByteFrequencyData();
  61409. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  61410. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  61411. // Draw the frequency domain chart.
  61412. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  61413. var value = workingArray[i];
  61414. var percent = value / this.BARGRAPHAMPLITUDE;
  61415. var height = this.DEBUGCANVASSIZE.height * percent;
  61416. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  61417. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  61418. var hue = i / this.getFrequencyBinCount() * 360;
  61419. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  61420. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  61421. }
  61422. }
  61423. }
  61424. };
  61425. Analyser.prototype.stopDebugCanvas = function () {
  61426. if (this._debugCanvas) {
  61427. if (this._registerFunc) {
  61428. this._scene.unregisterBeforeRender(this._registerFunc);
  61429. this._registerFunc = null;
  61430. }
  61431. document.body.removeChild(this._debugCanvas);
  61432. this._debugCanvas = null;
  61433. this._debugCanvasContext = null;
  61434. }
  61435. };
  61436. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  61437. if (this._audioEngine.canUseWebAudio) {
  61438. inputAudioNode.connect(this._webAudioAnalyser);
  61439. this._webAudioAnalyser.connect(outputAudioNode);
  61440. }
  61441. };
  61442. Analyser.prototype.dispose = function () {
  61443. if (this._audioEngine.canUseWebAudio) {
  61444. this._webAudioAnalyser.disconnect();
  61445. }
  61446. };
  61447. return Analyser;
  61448. }());
  61449. BABYLON.Analyser = Analyser;
  61450. })(BABYLON || (BABYLON = {}));
  61451. //# sourceMappingURL=babylon.analyser.js.map
  61452. "use strict";
  61453. var BABYLON;
  61454. (function (BABYLON) {
  61455. var CubeTexture = /** @class */ (function (_super) {
  61456. __extends(CubeTexture, _super);
  61457. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  61458. if (extensions === void 0) { extensions = null; }
  61459. if (noMipmap === void 0) { noMipmap = false; }
  61460. if (files === void 0) { files = null; }
  61461. if (onLoad === void 0) { onLoad = null; }
  61462. if (onError === void 0) { onError = null; }
  61463. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  61464. if (prefiltered === void 0) { prefiltered = false; }
  61465. if (forcedExtension === void 0) { forcedExtension = null; }
  61466. var _this = _super.call(this, scene) || this;
  61467. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  61468. /**
  61469. * Gets or sets the center of the bounding box associated with the cube texture
  61470. * It must define where the camera used to render the texture was set
  61471. */
  61472. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61473. _this._rotationY = 0;
  61474. _this.name = rootUrl;
  61475. _this.url = rootUrl;
  61476. _this._noMipmap = noMipmap;
  61477. _this.hasAlpha = false;
  61478. _this._format = format;
  61479. _this._prefiltered = prefiltered;
  61480. _this.isCube = true;
  61481. _this._textureMatrix = BABYLON.Matrix.Identity();
  61482. if (prefiltered) {
  61483. _this.gammaSpace = false;
  61484. }
  61485. if (!rootUrl && !files) {
  61486. return _this;
  61487. }
  61488. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  61489. var lastDot = rootUrl.lastIndexOf(".");
  61490. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  61491. var isDDS = (extension === ".dds");
  61492. if (!files) {
  61493. if (!isDDS && !extensions) {
  61494. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  61495. }
  61496. files = [];
  61497. if (extensions) {
  61498. for (var index = 0; index < extensions.length; index++) {
  61499. files.push(rootUrl + extensions[index]);
  61500. }
  61501. }
  61502. }
  61503. _this._files = files;
  61504. if (!_this._texture) {
  61505. if (!scene.useDelayedTextureLoading) {
  61506. if (prefiltered) {
  61507. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  61508. }
  61509. else {
  61510. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  61511. }
  61512. }
  61513. else {
  61514. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  61515. }
  61516. }
  61517. else if (onLoad) {
  61518. if (_this._texture.isReady) {
  61519. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  61520. }
  61521. else {
  61522. _this._texture.onLoadedObservable.add(onLoad);
  61523. }
  61524. }
  61525. return _this;
  61526. }
  61527. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  61528. get: function () {
  61529. return this._boundingBoxSize;
  61530. },
  61531. /**
  61532. * Gets or sets the size of the bounding box associated with the cube texture
  61533. * When defined, the cubemap will switch to local mode
  61534. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61535. * @example https://www.babylonjs-playground.com/#RNASML
  61536. */
  61537. set: function (value) {
  61538. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61539. return;
  61540. }
  61541. this._boundingBoxSize = value;
  61542. var scene = this.getScene();
  61543. if (scene) {
  61544. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61545. }
  61546. },
  61547. enumerable: true,
  61548. configurable: true
  61549. });
  61550. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  61551. /**
  61552. * Gets texture matrix rotation angle around Y axis radians.
  61553. */
  61554. get: function () {
  61555. return this._rotationY;
  61556. },
  61557. /**
  61558. * Sets texture matrix rotation angle around Y axis in radians.
  61559. */
  61560. set: function (value) {
  61561. this._rotationY = value;
  61562. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  61563. },
  61564. enumerable: true,
  61565. configurable: true
  61566. });
  61567. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  61568. var rootUrlKey = "";
  61569. files.forEach(function (url) { return rootUrlKey += url; });
  61570. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  61571. };
  61572. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  61573. if (forcedExtension === void 0) { forcedExtension = null; }
  61574. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  61575. };
  61576. // Methods
  61577. CubeTexture.prototype.delayLoad = function () {
  61578. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  61579. return;
  61580. }
  61581. var scene = this.getScene();
  61582. if (!scene) {
  61583. return;
  61584. }
  61585. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  61586. this._texture = this._getFromCache(this.url, this._noMipmap);
  61587. if (!this._texture) {
  61588. if (this._prefiltered) {
  61589. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  61590. }
  61591. else {
  61592. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  61593. }
  61594. }
  61595. };
  61596. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  61597. return this._textureMatrix;
  61598. };
  61599. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  61600. this._textureMatrix = value;
  61601. };
  61602. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  61603. var texture = BABYLON.SerializationHelper.Parse(function () {
  61604. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  61605. }, parsedTexture, scene);
  61606. // Local Cubemaps
  61607. if (parsedTexture.boundingBoxPosition) {
  61608. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  61609. }
  61610. if (parsedTexture.boundingBoxSize) {
  61611. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  61612. }
  61613. // Animations
  61614. if (parsedTexture.animations) {
  61615. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  61616. var parsedAnimation = parsedTexture.animations[animationIndex];
  61617. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  61618. }
  61619. }
  61620. return texture;
  61621. };
  61622. CubeTexture.prototype.clone = function () {
  61623. var _this = this;
  61624. return BABYLON.SerializationHelper.Clone(function () {
  61625. var scene = _this.getScene();
  61626. if (!scene) {
  61627. return _this;
  61628. }
  61629. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  61630. }, this);
  61631. };
  61632. __decorate([
  61633. BABYLON.serialize("rotationY")
  61634. ], CubeTexture.prototype, "_rotationY", void 0);
  61635. return CubeTexture;
  61636. }(BABYLON.BaseTexture));
  61637. BABYLON.CubeTexture = CubeTexture;
  61638. })(BABYLON || (BABYLON = {}));
  61639. //# sourceMappingURL=babylon.cubeTexture.js.map
  61640. "use strict";
  61641. var BABYLON;
  61642. (function (BABYLON) {
  61643. var RenderTargetTexture = /** @class */ (function (_super) {
  61644. __extends(RenderTargetTexture, _super);
  61645. /**
  61646. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  61647. * or used a shadow, depth texture...
  61648. * @param name The friendly name of the texture
  61649. * @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)
  61650. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  61651. * @param generateMipMaps True if mip maps need to be generated after render.
  61652. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  61653. * @param type The type of the buffer in the RTT (int, half float, float...)
  61654. * @param isCube True if a cube texture needs to be created
  61655. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  61656. * @param generateDepthBuffer True to generate a depth buffer
  61657. * @param generateStencilBuffer True to generate a stencil buffer
  61658. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  61659. */
  61660. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  61661. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  61662. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61663. if (isCube === void 0) { isCube = false; }
  61664. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61665. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  61666. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  61667. if (isMulti === void 0) { isMulti = false; }
  61668. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  61669. _this.isCube = isCube;
  61670. /**
  61671. * Use this list to define the list of mesh you want to render.
  61672. */
  61673. _this.renderList = new Array();
  61674. _this.renderParticles = true;
  61675. _this.renderSprites = false;
  61676. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  61677. _this.ignoreCameraViewport = false;
  61678. // Events
  61679. /**
  61680. * An event triggered when the texture is unbind.
  61681. */
  61682. _this.onBeforeBindObservable = new BABYLON.Observable();
  61683. /**
  61684. * An event triggered when the texture is unbind.
  61685. */
  61686. _this.onAfterUnbindObservable = new BABYLON.Observable();
  61687. /**
  61688. * An event triggered before rendering the texture
  61689. */
  61690. _this.onBeforeRenderObservable = new BABYLON.Observable();
  61691. /**
  61692. * An event triggered after rendering the texture
  61693. */
  61694. _this.onAfterRenderObservable = new BABYLON.Observable();
  61695. /**
  61696. * An event triggered after the texture clear
  61697. */
  61698. _this.onClearObservable = new BABYLON.Observable();
  61699. _this._currentRefreshId = -1;
  61700. _this._refreshRate = 1;
  61701. _this._samples = 1;
  61702. /**
  61703. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  61704. * It must define where the camera used to render the texture is set
  61705. */
  61706. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  61707. scene = _this.getScene();
  61708. if (!scene) {
  61709. return _this;
  61710. }
  61711. _this._engine = scene.getEngine();
  61712. _this.name = name;
  61713. _this.isRenderTarget = true;
  61714. _this._initialSizeParameter = size;
  61715. _this._processSizeParameter(size);
  61716. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  61717. });
  61718. _this._generateMipMaps = generateMipMaps ? true : false;
  61719. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  61720. // Rendering groups
  61721. _this._renderingManager = new BABYLON.RenderingManager(scene);
  61722. if (isMulti) {
  61723. return _this;
  61724. }
  61725. _this._renderTargetOptions = {
  61726. generateMipMaps: generateMipMaps,
  61727. type: type,
  61728. samplingMode: samplingMode,
  61729. generateDepthBuffer: generateDepthBuffer,
  61730. generateStencilBuffer: generateStencilBuffer
  61731. };
  61732. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  61733. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61734. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61735. }
  61736. if (isCube) {
  61737. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  61738. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  61739. _this._textureMatrix = BABYLON.Matrix.Identity();
  61740. }
  61741. else {
  61742. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  61743. }
  61744. return _this;
  61745. }
  61746. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  61747. get: function () {
  61748. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  61749. },
  61750. enumerable: true,
  61751. configurable: true
  61752. });
  61753. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  61754. get: function () {
  61755. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  61756. },
  61757. enumerable: true,
  61758. configurable: true
  61759. });
  61760. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  61761. get: function () {
  61762. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  61763. },
  61764. enumerable: true,
  61765. configurable: true
  61766. });
  61767. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  61768. set: function (callback) {
  61769. if (this._onAfterUnbindObserver) {
  61770. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  61771. }
  61772. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  61773. },
  61774. enumerable: true,
  61775. configurable: true
  61776. });
  61777. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  61778. set: function (callback) {
  61779. if (this._onBeforeRenderObserver) {
  61780. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  61781. }
  61782. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  61783. },
  61784. enumerable: true,
  61785. configurable: true
  61786. });
  61787. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  61788. set: function (callback) {
  61789. if (this._onAfterRenderObserver) {
  61790. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  61791. }
  61792. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  61793. },
  61794. enumerable: true,
  61795. configurable: true
  61796. });
  61797. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  61798. set: function (callback) {
  61799. if (this._onClearObserver) {
  61800. this.onClearObservable.remove(this._onClearObserver);
  61801. }
  61802. this._onClearObserver = this.onClearObservable.add(callback);
  61803. },
  61804. enumerable: true,
  61805. configurable: true
  61806. });
  61807. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  61808. get: function () {
  61809. return this._renderTargetOptions;
  61810. },
  61811. enumerable: true,
  61812. configurable: true
  61813. });
  61814. RenderTargetTexture.prototype._onRatioRescale = function () {
  61815. if (this._sizeRatio) {
  61816. this.resize(this._initialSizeParameter);
  61817. }
  61818. };
  61819. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  61820. get: function () {
  61821. return this._boundingBoxSize;
  61822. },
  61823. /**
  61824. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  61825. * When defined, the cubemap will switch to local mode
  61826. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  61827. * @example https://www.babylonjs-playground.com/#RNASML
  61828. */
  61829. set: function (value) {
  61830. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  61831. return;
  61832. }
  61833. this._boundingBoxSize = value;
  61834. var scene = this.getScene();
  61835. if (scene) {
  61836. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  61837. }
  61838. },
  61839. enumerable: true,
  61840. configurable: true
  61841. });
  61842. /**
  61843. * Creates a depth stencil texture.
  61844. * This is only available in WebGL 2 or with the depth texture extension available.
  61845. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  61846. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  61847. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  61848. */
  61849. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  61850. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  61851. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  61852. if (generateStencil === void 0) { generateStencil = false; }
  61853. if (!this.getScene()) {
  61854. return;
  61855. }
  61856. var engine = this.getScene().getEngine();
  61857. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  61858. bilinearFiltering: bilinearFiltering,
  61859. comparisonFunction: comparisonFunction,
  61860. generateStencil: generateStencil,
  61861. isCube: this.isCube
  61862. });
  61863. engine.setFrameBufferDepthStencilTexture(this);
  61864. };
  61865. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  61866. if (size.ratio) {
  61867. this._sizeRatio = size.ratio;
  61868. this._size = {
  61869. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  61870. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  61871. };
  61872. }
  61873. else {
  61874. this._size = size;
  61875. }
  61876. };
  61877. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  61878. get: function () {
  61879. return this._samples;
  61880. },
  61881. set: function (value) {
  61882. if (this._samples === value) {
  61883. return;
  61884. }
  61885. var scene = this.getScene();
  61886. if (!scene) {
  61887. return;
  61888. }
  61889. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  61890. },
  61891. enumerable: true,
  61892. configurable: true
  61893. });
  61894. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  61895. this._currentRefreshId = -1;
  61896. };
  61897. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  61898. get: function () {
  61899. return this._refreshRate;
  61900. },
  61901. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  61902. set: function (value) {
  61903. this._refreshRate = value;
  61904. this.resetRefreshCounter();
  61905. },
  61906. enumerable: true,
  61907. configurable: true
  61908. });
  61909. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  61910. if (!this._postProcessManager) {
  61911. var scene = this.getScene();
  61912. if (!scene) {
  61913. return;
  61914. }
  61915. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  61916. this._postProcesses = new Array();
  61917. }
  61918. this._postProcesses.push(postProcess);
  61919. this._postProcesses[0].autoClear = false;
  61920. };
  61921. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  61922. if (!this._postProcesses) {
  61923. return;
  61924. }
  61925. if (dispose) {
  61926. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  61927. var postProcess = _a[_i];
  61928. postProcess.dispose();
  61929. }
  61930. }
  61931. this._postProcesses = [];
  61932. };
  61933. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  61934. if (!this._postProcesses) {
  61935. return;
  61936. }
  61937. var index = this._postProcesses.indexOf(postProcess);
  61938. if (index === -1) {
  61939. return;
  61940. }
  61941. this._postProcesses.splice(index, 1);
  61942. if (this._postProcesses.length > 0) {
  61943. this._postProcesses[0].autoClear = false;
  61944. }
  61945. };
  61946. RenderTargetTexture.prototype._shouldRender = function () {
  61947. if (this._currentRefreshId === -1) {
  61948. this._currentRefreshId = 1;
  61949. return true;
  61950. }
  61951. if (this.refreshRate === this._currentRefreshId) {
  61952. this._currentRefreshId = 1;
  61953. return true;
  61954. }
  61955. this._currentRefreshId++;
  61956. return false;
  61957. };
  61958. RenderTargetTexture.prototype.getRenderSize = function () {
  61959. if (this._size.width) {
  61960. return this._size.width;
  61961. }
  61962. return this._size;
  61963. };
  61964. RenderTargetTexture.prototype.getRenderWidth = function () {
  61965. if (this._size.width) {
  61966. return this._size.width;
  61967. }
  61968. return this._size;
  61969. };
  61970. RenderTargetTexture.prototype.getRenderHeight = function () {
  61971. if (this._size.width) {
  61972. return this._size.height;
  61973. }
  61974. return this._size;
  61975. };
  61976. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  61977. get: function () {
  61978. return true;
  61979. },
  61980. enumerable: true,
  61981. configurable: true
  61982. });
  61983. RenderTargetTexture.prototype.scale = function (ratio) {
  61984. var newSize = this.getRenderSize() * ratio;
  61985. this.resize(newSize);
  61986. };
  61987. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  61988. if (this.isCube) {
  61989. return this._textureMatrix;
  61990. }
  61991. return _super.prototype.getReflectionTextureMatrix.call(this);
  61992. };
  61993. RenderTargetTexture.prototype.resize = function (size) {
  61994. this.releaseInternalTexture();
  61995. var scene = this.getScene();
  61996. if (!scene) {
  61997. return;
  61998. }
  61999. this._processSizeParameter(size);
  62000. if (this.isCube) {
  62001. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62002. }
  62003. else {
  62004. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62005. }
  62006. };
  62007. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62008. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62009. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62010. var scene = this.getScene();
  62011. if (!scene) {
  62012. return;
  62013. }
  62014. var engine = scene.getEngine();
  62015. if (this.useCameraPostProcesses !== undefined) {
  62016. useCameraPostProcess = this.useCameraPostProcesses;
  62017. }
  62018. if (this._waitingRenderList) {
  62019. this.renderList = [];
  62020. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62021. var id = this._waitingRenderList[index];
  62022. var mesh_1 = scene.getMeshByID(id);
  62023. if (mesh_1) {
  62024. this.renderList.push(mesh_1);
  62025. }
  62026. }
  62027. delete this._waitingRenderList;
  62028. }
  62029. // Is predicate defined?
  62030. if (this.renderListPredicate) {
  62031. if (this.renderList) {
  62032. this.renderList.splice(0); // Clear previous renderList
  62033. }
  62034. else {
  62035. this.renderList = [];
  62036. }
  62037. var scene = this.getScene();
  62038. if (!scene) {
  62039. return;
  62040. }
  62041. var sceneMeshes = scene.meshes;
  62042. for (var index = 0; index < sceneMeshes.length; index++) {
  62043. var mesh = sceneMeshes[index];
  62044. if (this.renderListPredicate(mesh)) {
  62045. this.renderList.push(mesh);
  62046. }
  62047. }
  62048. }
  62049. this.onBeforeBindObservable.notifyObservers(this);
  62050. // Set custom projection.
  62051. // Needs to be before binding to prevent changing the aspect ratio.
  62052. var camera;
  62053. if (this.activeCamera) {
  62054. camera = this.activeCamera;
  62055. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62056. if (this.activeCamera !== scene.activeCamera) {
  62057. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  62058. }
  62059. }
  62060. else {
  62061. camera = scene.activeCamera;
  62062. if (camera) {
  62063. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  62064. }
  62065. }
  62066. // Prepare renderingManager
  62067. this._renderingManager.reset();
  62068. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  62069. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  62070. var sceneRenderId = scene.getRenderId();
  62071. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  62072. var mesh = currentRenderList[meshIndex];
  62073. if (mesh) {
  62074. if (!mesh.isReady(this.refreshRate === 0)) {
  62075. this.resetRefreshCounter();
  62076. continue;
  62077. }
  62078. mesh._preActivateForIntermediateRendering(sceneRenderId);
  62079. var isMasked = void 0;
  62080. if (!this.renderList && camera) {
  62081. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  62082. }
  62083. else {
  62084. isMasked = false;
  62085. }
  62086. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  62087. mesh._activate(sceneRenderId);
  62088. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  62089. var subMesh = mesh.subMeshes[subIndex];
  62090. scene._activeIndices.addCount(subMesh.indexCount, false);
  62091. this._renderingManager.dispatch(subMesh, mesh);
  62092. }
  62093. }
  62094. }
  62095. }
  62096. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  62097. var particleSystem = scene.particleSystems[particleIndex];
  62098. var emitter = particleSystem.emitter;
  62099. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  62100. continue;
  62101. }
  62102. if (currentRenderList.indexOf(emitter) >= 0) {
  62103. this._renderingManager.dispatchParticles(particleSystem);
  62104. }
  62105. }
  62106. if (this.isCube) {
  62107. for (var face = 0; face < 6; face++) {
  62108. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62109. scene.incrementRenderId();
  62110. scene.resetCachedMaterial();
  62111. }
  62112. }
  62113. else {
  62114. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  62115. }
  62116. this.onAfterUnbindObservable.notifyObservers(this);
  62117. if (scene.activeCamera) {
  62118. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  62119. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  62120. }
  62121. engine.setViewport(scene.activeCamera.viewport);
  62122. }
  62123. scene.resetCachedMaterial();
  62124. };
  62125. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  62126. var minimum = 128;
  62127. var x = renderDimension * scale;
  62128. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  62129. // Ensure we don't exceed the render dimension (while staying POT)
  62130. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  62131. };
  62132. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62133. var _this = this;
  62134. if (!this._texture) {
  62135. return;
  62136. }
  62137. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  62138. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62139. });
  62140. };
  62141. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  62142. var scene = this.getScene();
  62143. if (!scene) {
  62144. return;
  62145. }
  62146. var engine = scene.getEngine();
  62147. if (!this._texture) {
  62148. return;
  62149. }
  62150. // Bind
  62151. if (this._postProcessManager) {
  62152. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  62153. }
  62154. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  62155. if (this._texture) {
  62156. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  62157. }
  62158. }
  62159. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  62160. // Clear
  62161. if (this.onClearObservable.hasObservers()) {
  62162. this.onClearObservable.notifyObservers(engine);
  62163. }
  62164. else {
  62165. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  62166. }
  62167. if (!this._doNotChangeAspectRatio) {
  62168. scene.updateTransformMatrix(true);
  62169. }
  62170. // Render
  62171. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  62172. if (this._postProcessManager) {
  62173. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  62174. }
  62175. else if (useCameraPostProcess) {
  62176. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  62177. }
  62178. if (!this._doNotChangeAspectRatio) {
  62179. scene.updateTransformMatrix(true);
  62180. }
  62181. // Dump ?
  62182. if (dumpForDebug) {
  62183. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  62184. }
  62185. // Unbind
  62186. if (!this.isCube || faceIndex === 5) {
  62187. if (this.isCube) {
  62188. if (faceIndex === 5) {
  62189. engine.generateMipMapsForCubemap(this._texture);
  62190. }
  62191. }
  62192. this.unbindFrameBuffer(engine, faceIndex);
  62193. }
  62194. else {
  62195. this.onAfterRenderObservable.notifyObservers(faceIndex);
  62196. }
  62197. };
  62198. /**
  62199. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  62200. * This allowed control for front to back rendering or reversly depending of the special needs.
  62201. *
  62202. * @param renderingGroupId The rendering group id corresponding to its index
  62203. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  62204. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  62205. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  62206. */
  62207. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  62208. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  62209. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  62210. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  62211. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  62212. };
  62213. /**
  62214. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  62215. *
  62216. * @param renderingGroupId The rendering group id corresponding to its index
  62217. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  62218. */
  62219. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  62220. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  62221. };
  62222. RenderTargetTexture.prototype.clone = function () {
  62223. var textureSize = this.getSize();
  62224. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  62225. // Base texture
  62226. newTexture.hasAlpha = this.hasAlpha;
  62227. newTexture.level = this.level;
  62228. // RenderTarget Texture
  62229. newTexture.coordinatesMode = this.coordinatesMode;
  62230. if (this.renderList) {
  62231. newTexture.renderList = this.renderList.slice(0);
  62232. }
  62233. return newTexture;
  62234. };
  62235. RenderTargetTexture.prototype.serialize = function () {
  62236. if (!this.name) {
  62237. return null;
  62238. }
  62239. var serializationObject = _super.prototype.serialize.call(this);
  62240. serializationObject.renderTargetSize = this.getRenderSize();
  62241. serializationObject.renderList = [];
  62242. if (this.renderList) {
  62243. for (var index = 0; index < this.renderList.length; index++) {
  62244. serializationObject.renderList.push(this.renderList[index].id);
  62245. }
  62246. }
  62247. return serializationObject;
  62248. };
  62249. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  62250. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  62251. var objBuffer = this.getInternalTexture();
  62252. var scene = this.getScene();
  62253. if (objBuffer && scene) {
  62254. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  62255. }
  62256. };
  62257. RenderTargetTexture.prototype.dispose = function () {
  62258. if (this._postProcessManager) {
  62259. this._postProcessManager.dispose();
  62260. this._postProcessManager = null;
  62261. }
  62262. this.clearPostProcesses(true);
  62263. if (this._resizeObserver) {
  62264. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  62265. this._resizeObserver = null;
  62266. }
  62267. this.renderList = null;
  62268. // Remove from custom render targets
  62269. var scene = this.getScene();
  62270. if (!scene) {
  62271. return;
  62272. }
  62273. var index = scene.customRenderTargets.indexOf(this);
  62274. if (index >= 0) {
  62275. scene.customRenderTargets.splice(index, 1);
  62276. }
  62277. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  62278. var camera = _a[_i];
  62279. index = camera.customRenderTargets.indexOf(this);
  62280. if (index >= 0) {
  62281. camera.customRenderTargets.splice(index, 1);
  62282. }
  62283. }
  62284. _super.prototype.dispose.call(this);
  62285. };
  62286. RenderTargetTexture.prototype._rebuild = function () {
  62287. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62288. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62289. }
  62290. if (this._postProcessManager) {
  62291. this._postProcessManager._rebuild();
  62292. }
  62293. };
  62294. /**
  62295. * Clear the info related to rendering groups preventing retention point in material dispose.
  62296. */
  62297. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  62298. if (this._renderingManager) {
  62299. this._renderingManager.freeRenderingGroups();
  62300. }
  62301. };
  62302. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  62303. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  62304. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  62305. return RenderTargetTexture;
  62306. }(BABYLON.Texture));
  62307. BABYLON.RenderTargetTexture = RenderTargetTexture;
  62308. })(BABYLON || (BABYLON = {}));
  62309. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  62310. "use strict";
  62311. var BABYLON;
  62312. (function (BABYLON) {
  62313. ;
  62314. var MultiRenderTarget = /** @class */ (function (_super) {
  62315. __extends(MultiRenderTarget, _super);
  62316. function MultiRenderTarget(name, size, count, scene, options) {
  62317. var _this = this;
  62318. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  62319. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  62320. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  62321. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  62322. _this._engine = scene.getEngine();
  62323. if (!_this.isSupported) {
  62324. _this.dispose();
  62325. return;
  62326. }
  62327. var types = [];
  62328. var samplingModes = [];
  62329. for (var i = 0; i < count; i++) {
  62330. if (options && options.types && options.types[i] !== undefined) {
  62331. types.push(options.types[i]);
  62332. }
  62333. else {
  62334. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62335. }
  62336. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  62337. samplingModes.push(options.samplingModes[i]);
  62338. }
  62339. else {
  62340. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62341. }
  62342. }
  62343. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  62344. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  62345. _this._size = size;
  62346. _this._multiRenderTargetOptions = {
  62347. samplingModes: samplingModes,
  62348. generateMipMaps: generateMipMaps,
  62349. generateDepthBuffer: generateDepthBuffer,
  62350. generateStencilBuffer: generateStencilBuffer,
  62351. generateDepthTexture: generateDepthTexture,
  62352. types: types,
  62353. textureCount: count
  62354. };
  62355. _this._createInternalTextures();
  62356. _this._createTextures();
  62357. return _this;
  62358. }
  62359. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  62360. get: function () {
  62361. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  62362. },
  62363. enumerable: true,
  62364. configurable: true
  62365. });
  62366. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  62367. get: function () {
  62368. return this._textures;
  62369. },
  62370. enumerable: true,
  62371. configurable: true
  62372. });
  62373. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  62374. get: function () {
  62375. return this._textures[this._textures.length - 1];
  62376. },
  62377. enumerable: true,
  62378. configurable: true
  62379. });
  62380. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  62381. set: function (wrap) {
  62382. if (this._textures) {
  62383. for (var i = 0; i < this._textures.length; i++) {
  62384. this._textures[i].wrapU = wrap;
  62385. }
  62386. }
  62387. },
  62388. enumerable: true,
  62389. configurable: true
  62390. });
  62391. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  62392. set: function (wrap) {
  62393. if (this._textures) {
  62394. for (var i = 0; i < this._textures.length; i++) {
  62395. this._textures[i].wrapV = wrap;
  62396. }
  62397. }
  62398. },
  62399. enumerable: true,
  62400. configurable: true
  62401. });
  62402. MultiRenderTarget.prototype._rebuild = function () {
  62403. this.releaseInternalTextures();
  62404. this._createInternalTextures();
  62405. for (var i = 0; i < this._internalTextures.length; i++) {
  62406. var texture = this._textures[i];
  62407. texture._texture = this._internalTextures[i];
  62408. }
  62409. // Keeps references to frame buffer and stencil/depth buffer
  62410. this._texture = this._internalTextures[0];
  62411. };
  62412. MultiRenderTarget.prototype._createInternalTextures = function () {
  62413. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  62414. };
  62415. MultiRenderTarget.prototype._createTextures = function () {
  62416. this._textures = [];
  62417. for (var i = 0; i < this._internalTextures.length; i++) {
  62418. var texture = new BABYLON.Texture(null, this.getScene());
  62419. texture._texture = this._internalTextures[i];
  62420. this._textures.push(texture);
  62421. }
  62422. // Keeps references to frame buffer and stencil/depth buffer
  62423. this._texture = this._internalTextures[0];
  62424. };
  62425. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  62426. get: function () {
  62427. return this._samples;
  62428. },
  62429. set: function (value) {
  62430. if (this._samples === value) {
  62431. return;
  62432. }
  62433. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  62434. },
  62435. enumerable: true,
  62436. configurable: true
  62437. });
  62438. MultiRenderTarget.prototype.resize = function (size) {
  62439. this.releaseInternalTextures();
  62440. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  62441. this._createInternalTextures();
  62442. };
  62443. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  62444. var _this = this;
  62445. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  62446. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  62447. });
  62448. };
  62449. MultiRenderTarget.prototype.dispose = function () {
  62450. this.releaseInternalTextures();
  62451. _super.prototype.dispose.call(this);
  62452. };
  62453. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  62454. if (!this._internalTextures) {
  62455. return;
  62456. }
  62457. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  62458. if (this._internalTextures[i] !== undefined) {
  62459. this._internalTextures[i].dispose();
  62460. this._internalTextures.splice(i, 1);
  62461. }
  62462. }
  62463. };
  62464. return MultiRenderTarget;
  62465. }(BABYLON.RenderTargetTexture));
  62466. BABYLON.MultiRenderTarget = MultiRenderTarget;
  62467. })(BABYLON || (BABYLON = {}));
  62468. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  62469. "use strict";
  62470. var BABYLON;
  62471. (function (BABYLON) {
  62472. var MirrorTexture = /** @class */ (function (_super) {
  62473. __extends(MirrorTexture, _super);
  62474. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  62475. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62476. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62477. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62478. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  62479. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  62480. _this._transformMatrix = BABYLON.Matrix.Zero();
  62481. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  62482. _this._adaptiveBlurKernel = 0;
  62483. _this._blurKernelX = 0;
  62484. _this._blurKernelY = 0;
  62485. _this._blurRatio = 1.0;
  62486. _this.ignoreCameraViewport = true;
  62487. _this.onBeforeRenderObservable.add(function () {
  62488. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  62489. _this._savedViewMatrix = scene.getViewMatrix();
  62490. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  62491. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  62492. scene.clipPlane = _this.mirrorPlane;
  62493. scene.getEngine().cullBackFaces = false;
  62494. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  62495. });
  62496. _this.onAfterRenderObservable.add(function () {
  62497. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  62498. scene.getEngine().cullBackFaces = true;
  62499. scene._mirroredCameraPosition = null;
  62500. delete scene.clipPlane;
  62501. });
  62502. return _this;
  62503. }
  62504. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  62505. get: function () {
  62506. return this._blurRatio;
  62507. },
  62508. set: function (value) {
  62509. if (this._blurRatio === value) {
  62510. return;
  62511. }
  62512. this._blurRatio = value;
  62513. this._preparePostProcesses();
  62514. },
  62515. enumerable: true,
  62516. configurable: true
  62517. });
  62518. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  62519. set: function (value) {
  62520. this._adaptiveBlurKernel = value;
  62521. this._autoComputeBlurKernel();
  62522. },
  62523. enumerable: true,
  62524. configurable: true
  62525. });
  62526. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  62527. set: function (value) {
  62528. this.blurKernelX = value;
  62529. this.blurKernelY = value;
  62530. },
  62531. enumerable: true,
  62532. configurable: true
  62533. });
  62534. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  62535. get: function () {
  62536. return this._blurKernelX;
  62537. },
  62538. set: function (value) {
  62539. if (this._blurKernelX === value) {
  62540. return;
  62541. }
  62542. this._blurKernelX = value;
  62543. this._preparePostProcesses();
  62544. },
  62545. enumerable: true,
  62546. configurable: true
  62547. });
  62548. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  62549. get: function () {
  62550. return this._blurKernelY;
  62551. },
  62552. set: function (value) {
  62553. if (this._blurKernelY === value) {
  62554. return;
  62555. }
  62556. this._blurKernelY = value;
  62557. this._preparePostProcesses();
  62558. },
  62559. enumerable: true,
  62560. configurable: true
  62561. });
  62562. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  62563. var engine = this.getScene().getEngine();
  62564. var dw = this.getRenderWidth() / engine.getRenderWidth();
  62565. var dh = this.getRenderHeight() / engine.getRenderHeight();
  62566. this.blurKernelX = this._adaptiveBlurKernel * dw;
  62567. this.blurKernelY = this._adaptiveBlurKernel * dh;
  62568. };
  62569. MirrorTexture.prototype._onRatioRescale = function () {
  62570. if (this._sizeRatio) {
  62571. this.resize(this._initialSizeParameter);
  62572. if (!this._adaptiveBlurKernel) {
  62573. this._preparePostProcesses();
  62574. }
  62575. }
  62576. if (this._adaptiveBlurKernel) {
  62577. this._autoComputeBlurKernel();
  62578. }
  62579. };
  62580. MirrorTexture.prototype._preparePostProcesses = function () {
  62581. this.clearPostProcesses(true);
  62582. if (this._blurKernelX && this._blurKernelY) {
  62583. var engine = this.getScene().getEngine();
  62584. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62585. 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);
  62586. this._blurX.autoClear = false;
  62587. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  62588. this._blurX.inputTexture = this._texture;
  62589. }
  62590. else {
  62591. this._blurX.alwaysForcePOT = true;
  62592. }
  62593. 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);
  62594. this._blurY.autoClear = false;
  62595. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  62596. this.addPostProcess(this._blurX);
  62597. this.addPostProcess(this._blurY);
  62598. }
  62599. else {
  62600. if (this._blurY) {
  62601. this.removePostProcess(this._blurY);
  62602. this._blurY.dispose();
  62603. this._blurY = null;
  62604. }
  62605. if (this._blurX) {
  62606. this.removePostProcess(this._blurX);
  62607. this._blurX.dispose();
  62608. this._blurX = null;
  62609. }
  62610. }
  62611. };
  62612. MirrorTexture.prototype.clone = function () {
  62613. var scene = this.getScene();
  62614. if (!scene) {
  62615. return this;
  62616. }
  62617. var textureSize = this.getSize();
  62618. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  62619. // Base texture
  62620. newTexture.hasAlpha = this.hasAlpha;
  62621. newTexture.level = this.level;
  62622. // Mirror Texture
  62623. newTexture.mirrorPlane = this.mirrorPlane.clone();
  62624. if (this.renderList) {
  62625. newTexture.renderList = this.renderList.slice(0);
  62626. }
  62627. return newTexture;
  62628. };
  62629. MirrorTexture.prototype.serialize = function () {
  62630. if (!this.name) {
  62631. return null;
  62632. }
  62633. var serializationObject = _super.prototype.serialize.call(this);
  62634. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  62635. return serializationObject;
  62636. };
  62637. return MirrorTexture;
  62638. }(BABYLON.RenderTargetTexture));
  62639. BABYLON.MirrorTexture = MirrorTexture;
  62640. })(BABYLON || (BABYLON = {}));
  62641. //# sourceMappingURL=babylon.mirrorTexture.js.map
  62642. "use strict";
  62643. var BABYLON;
  62644. (function (BABYLON) {
  62645. /**
  62646. * Creates a refraction texture used by refraction channel of the standard material.
  62647. * @param name the texture name
  62648. * @param size size of the underlying texture
  62649. * @param scene root scene
  62650. */
  62651. var RefractionTexture = /** @class */ (function (_super) {
  62652. __extends(RefractionTexture, _super);
  62653. function RefractionTexture(name, size, scene, generateMipMaps) {
  62654. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  62655. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  62656. _this.depth = 2.0;
  62657. _this.onBeforeRenderObservable.add(function () {
  62658. scene.clipPlane = _this.refractionPlane;
  62659. });
  62660. _this.onAfterRenderObservable.add(function () {
  62661. delete scene.clipPlane;
  62662. });
  62663. return _this;
  62664. }
  62665. RefractionTexture.prototype.clone = function () {
  62666. var scene = this.getScene();
  62667. if (!scene) {
  62668. return this;
  62669. }
  62670. var textureSize = this.getSize();
  62671. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  62672. // Base texture
  62673. newTexture.hasAlpha = this.hasAlpha;
  62674. newTexture.level = this.level;
  62675. // Refraction Texture
  62676. newTexture.refractionPlane = this.refractionPlane.clone();
  62677. if (this.renderList) {
  62678. newTexture.renderList = this.renderList.slice(0);
  62679. }
  62680. newTexture.depth = this.depth;
  62681. return newTexture;
  62682. };
  62683. RefractionTexture.prototype.serialize = function () {
  62684. if (!this.name) {
  62685. return null;
  62686. }
  62687. var serializationObject = _super.prototype.serialize.call(this);
  62688. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  62689. serializationObject.depth = this.depth;
  62690. return serializationObject;
  62691. };
  62692. return RefractionTexture;
  62693. }(BABYLON.RenderTargetTexture));
  62694. BABYLON.RefractionTexture = RefractionTexture;
  62695. })(BABYLON || (BABYLON = {}));
  62696. //# sourceMappingURL=babylon.refractionTexture.js.map
  62697. "use strict";
  62698. var BABYLON;
  62699. (function (BABYLON) {
  62700. /**
  62701. * A class extending {BABYLON.Texture} allowing drawing on a texture
  62702. * @see http://doc.babylonjs.com/how_to/dynamictexture
  62703. */
  62704. var DynamicTexture = /** @class */ (function (_super) {
  62705. __extends(DynamicTexture, _super);
  62706. /**
  62707. * Creates a {BABYLON.DynamicTexture}
  62708. * @param name defines the name of the texture
  62709. * @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
  62710. * @param scene defines the scene where you want the texture
  62711. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  62712. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  62713. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  62714. */
  62715. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  62716. if (scene === void 0) { scene = null; }
  62717. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62718. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62719. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  62720. _this.name = name;
  62721. _this._engine = _this.getScene().getEngine();
  62722. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62723. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62724. _this._generateMipMaps = generateMipMaps;
  62725. if (options.getContext) {
  62726. _this._canvas = options;
  62727. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62728. }
  62729. else {
  62730. _this._canvas = document.createElement("canvas");
  62731. if (options.width) {
  62732. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  62733. }
  62734. else {
  62735. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  62736. }
  62737. }
  62738. var textureSize = _this.getSize();
  62739. _this._canvas.width = textureSize.width;
  62740. _this._canvas.height = textureSize.height;
  62741. _this._context = _this._canvas.getContext("2d");
  62742. return _this;
  62743. }
  62744. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  62745. /**
  62746. * Gets the current state of canRescale
  62747. */
  62748. get: function () {
  62749. return true;
  62750. },
  62751. enumerable: true,
  62752. configurable: true
  62753. });
  62754. DynamicTexture.prototype._recreate = function (textureSize) {
  62755. this._canvas.width = textureSize.width;
  62756. this._canvas.height = textureSize.height;
  62757. this.releaseInternalTexture();
  62758. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  62759. };
  62760. /**
  62761. * Scales the texture
  62762. * @param ratio the scale factor to apply to both width and height
  62763. */
  62764. DynamicTexture.prototype.scale = function (ratio) {
  62765. var textureSize = this.getSize();
  62766. textureSize.width *= ratio;
  62767. textureSize.height *= ratio;
  62768. this._recreate(textureSize);
  62769. };
  62770. /**
  62771. * Resizes the texture
  62772. * @param width the new width
  62773. * @param height the new height
  62774. */
  62775. DynamicTexture.prototype.scaleTo = function (width, height) {
  62776. var textureSize = this.getSize();
  62777. textureSize.width = width;
  62778. textureSize.height = height;
  62779. this._recreate(textureSize);
  62780. };
  62781. /**
  62782. * Gets the context of the canvas used by the texture
  62783. * @returns the canvas context of the dynamic texture
  62784. */
  62785. DynamicTexture.prototype.getContext = function () {
  62786. return this._context;
  62787. };
  62788. /**
  62789. * Clears the texture
  62790. */
  62791. DynamicTexture.prototype.clear = function () {
  62792. var size = this.getSize();
  62793. this._context.fillRect(0, 0, size.width, size.height);
  62794. };
  62795. /**
  62796. * Updates the texture
  62797. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  62798. */
  62799. DynamicTexture.prototype.update = function (invertY) {
  62800. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  62801. };
  62802. /**
  62803. * Draws text onto the texture
  62804. * @param text defines the text to be drawn
  62805. * @param x defines the placement of the text from the left
  62806. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  62807. * @param font defines the font to be used with font-style, font-size, font-name
  62808. * @param color defines the color used for the text
  62809. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  62810. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  62811. * @param update defines whether texture is immediately update (default is true)
  62812. */
  62813. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  62814. if (update === void 0) { update = true; }
  62815. var size = this.getSize();
  62816. if (clearColor) {
  62817. this._context.fillStyle = clearColor;
  62818. this._context.fillRect(0, 0, size.width, size.height);
  62819. }
  62820. this._context.font = font;
  62821. if (x === null || x === undefined) {
  62822. var textSize = this._context.measureText(text);
  62823. x = (size.width - textSize.width) / 2;
  62824. }
  62825. if (y === null || y === undefined) {
  62826. var fontSize = parseInt((font.replace(/\D/g, '')));
  62827. ;
  62828. y = (size.height / 2) + (fontSize / 3.65);
  62829. }
  62830. this._context.fillStyle = color;
  62831. this._context.fillText(text, x, y);
  62832. if (update) {
  62833. this.update(invertY);
  62834. }
  62835. };
  62836. /**
  62837. * Clones the texture
  62838. * @returns the clone of the texture.
  62839. */
  62840. DynamicTexture.prototype.clone = function () {
  62841. var scene = this.getScene();
  62842. if (!scene) {
  62843. return this;
  62844. }
  62845. var textureSize = this.getSize();
  62846. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  62847. // Base texture
  62848. newTexture.hasAlpha = this.hasAlpha;
  62849. newTexture.level = this.level;
  62850. // Dynamic Texture
  62851. newTexture.wrapU = this.wrapU;
  62852. newTexture.wrapV = this.wrapV;
  62853. return newTexture;
  62854. };
  62855. /** @ignore */
  62856. DynamicTexture.prototype._rebuild = function () {
  62857. this.update();
  62858. };
  62859. return DynamicTexture;
  62860. }(BABYLON.Texture));
  62861. BABYLON.DynamicTexture = DynamicTexture;
  62862. })(BABYLON || (BABYLON = {}));
  62863. //# sourceMappingURL=babylon.dynamicTexture.js.map
  62864. "use strict";
  62865. var BABYLON;
  62866. (function (BABYLON) {
  62867. var VideoTexture = /** @class */ (function (_super) {
  62868. __extends(VideoTexture, _super);
  62869. /**
  62870. * Creates a video texture.
  62871. * Sample : https://doc.babylonjs.com/how_to/video_texture
  62872. * @param {string | null} name optional name, will detect from video source, if not defined
  62873. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  62874. * @param {BABYLON.Scene} scene is obviously the current scene.
  62875. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  62876. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  62877. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  62878. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  62879. */
  62880. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  62881. if (generateMipMaps === void 0) { generateMipMaps = false; }
  62882. if (invertY === void 0) { invertY = false; }
  62883. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62884. if (settings === void 0) { settings = {
  62885. autoPlay: true,
  62886. loop: true,
  62887. autoUpdateTexture: true,
  62888. }; }
  62889. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  62890. _this._createInternalTexture = function () {
  62891. if (_this._texture != null) {
  62892. return;
  62893. }
  62894. if (!_this._engine.needPOTTextures ||
  62895. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  62896. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62897. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62898. }
  62899. else {
  62900. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62901. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62902. _this._generateMipMaps = false;
  62903. }
  62904. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  62905. _this._texture.isReady = true;
  62906. _this._updateInternalTexture();
  62907. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  62908. _this.onLoadObservable.notifyObservers(_this);
  62909. }
  62910. };
  62911. _this.reset = function () {
  62912. if (_this._texture == null) {
  62913. return;
  62914. }
  62915. _this._texture.dispose();
  62916. _this._texture = null;
  62917. };
  62918. _this._updateInternalTexture = function (e) {
  62919. if (_this._texture == null || !_this._texture.isReady) {
  62920. return;
  62921. }
  62922. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  62923. return;
  62924. }
  62925. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  62926. };
  62927. _this._engine = _this.getScene().getEngine();
  62928. _this._generateMipMaps = generateMipMaps;
  62929. _this._samplingMode = samplingMode;
  62930. _this.autoUpdateTexture = settings.autoUpdateTexture;
  62931. _this.name = name || _this._getName(src);
  62932. _this.video = _this._getVideo(src);
  62933. if (settings.autoPlay !== undefined) {
  62934. _this.video.autoplay = settings.autoPlay;
  62935. }
  62936. if (settings.loop !== undefined) {
  62937. _this.video.loop = settings.loop;
  62938. }
  62939. _this.video.addEventListener("canplay", _this._createInternalTexture);
  62940. _this.video.addEventListener("paused", _this._updateInternalTexture);
  62941. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  62942. _this.video.addEventListener("emptied", _this.reset);
  62943. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  62944. _this._createInternalTexture();
  62945. }
  62946. return _this;
  62947. }
  62948. VideoTexture.prototype._getName = function (src) {
  62949. if (src instanceof HTMLVideoElement) {
  62950. return src.currentSrc;
  62951. }
  62952. if (typeof src === "object") {
  62953. return src.toString();
  62954. }
  62955. return src;
  62956. };
  62957. ;
  62958. VideoTexture.prototype._getVideo = function (src) {
  62959. if (src instanceof HTMLVideoElement) {
  62960. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  62961. return src;
  62962. }
  62963. var video = document.createElement("video");
  62964. if (typeof src === "string") {
  62965. BABYLON.Tools.SetCorsBehavior(src, video);
  62966. video.src = src;
  62967. }
  62968. else {
  62969. BABYLON.Tools.SetCorsBehavior(src[0], video);
  62970. src.forEach(function (url) {
  62971. var source = document.createElement("source");
  62972. source.src = url;
  62973. video.appendChild(source);
  62974. });
  62975. }
  62976. return video;
  62977. };
  62978. ;
  62979. /**
  62980. * Internal method to initiate `update`.
  62981. */
  62982. VideoTexture.prototype._rebuild = function () {
  62983. this.update();
  62984. };
  62985. /**
  62986. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  62987. */
  62988. VideoTexture.prototype.update = function () {
  62989. if (!this.autoUpdateTexture) {
  62990. // Expecting user to call `updateTexture` manually
  62991. return;
  62992. }
  62993. this.updateTexture(true);
  62994. };
  62995. /**
  62996. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  62997. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  62998. */
  62999. VideoTexture.prototype.updateTexture = function (isVisible) {
  63000. if (!isVisible) {
  63001. return;
  63002. }
  63003. if (this.video.paused) {
  63004. return;
  63005. }
  63006. this._updateInternalTexture();
  63007. };
  63008. /**
  63009. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63010. * @param url New url.
  63011. */
  63012. VideoTexture.prototype.updateURL = function (url) {
  63013. this.video.src = url;
  63014. };
  63015. VideoTexture.prototype.dispose = function () {
  63016. _super.prototype.dispose.call(this);
  63017. this.video.removeEventListener("canplay", this._createInternalTexture);
  63018. this.video.removeEventListener("paused", this._updateInternalTexture);
  63019. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63020. this.video.removeEventListener("emptied", this.reset);
  63021. this.video.pause();
  63022. };
  63023. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63024. var video = document.createElement("video");
  63025. var constraintsDeviceId;
  63026. if (constraints && constraints.deviceId) {
  63027. constraintsDeviceId = {
  63028. exact: constraints.deviceId,
  63029. };
  63030. }
  63031. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63032. if (navigator.mediaDevices) {
  63033. navigator.mediaDevices.getUserMedia({ video: constraints })
  63034. .then(function (stream) {
  63035. if (video.mozSrcObject !== undefined) {
  63036. // hack for Firefox < 19
  63037. video.mozSrcObject = stream;
  63038. }
  63039. else {
  63040. video.srcObject = stream;
  63041. }
  63042. var onPlaying = function () {
  63043. if (onReady) {
  63044. onReady(new VideoTexture("video", video, scene, true, true));
  63045. }
  63046. video.removeEventListener("playing", onPlaying);
  63047. };
  63048. video.addEventListener("playing", onPlaying);
  63049. video.play();
  63050. })
  63051. .catch(function (err) {
  63052. BABYLON.Tools.Error(err.name);
  63053. });
  63054. }
  63055. else {
  63056. navigator.getUserMedia =
  63057. navigator.getUserMedia ||
  63058. navigator.webkitGetUserMedia ||
  63059. navigator.mozGetUserMedia ||
  63060. navigator.msGetUserMedia;
  63061. if (navigator.getUserMedia) {
  63062. navigator.getUserMedia({
  63063. video: {
  63064. deviceId: constraintsDeviceId,
  63065. width: {
  63066. min: (constraints && constraints.minWidth) || 256,
  63067. max: (constraints && constraints.maxWidth) || 640,
  63068. },
  63069. height: {
  63070. min: (constraints && constraints.minHeight) || 256,
  63071. max: (constraints && constraints.maxHeight) || 480,
  63072. },
  63073. },
  63074. }, function (stream) {
  63075. if (video.mozSrcObject !== undefined) {
  63076. // hack for Firefox < 19
  63077. video.mozSrcObject = stream;
  63078. }
  63079. else {
  63080. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  63081. }
  63082. video.play();
  63083. if (onReady) {
  63084. onReady(new VideoTexture("video", video, scene, true, true));
  63085. }
  63086. }, function (e) {
  63087. BABYLON.Tools.Error(e.name);
  63088. });
  63089. }
  63090. }
  63091. };
  63092. return VideoTexture;
  63093. }(BABYLON.Texture));
  63094. BABYLON.VideoTexture = VideoTexture;
  63095. })(BABYLON || (BABYLON = {}));
  63096. //# sourceMappingURL=babylon.videoTexture.js.map
  63097. "use strict";
  63098. var BABYLON;
  63099. (function (BABYLON) {
  63100. var RawTexture = /** @class */ (function (_super) {
  63101. __extends(RawTexture, _super);
  63102. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  63103. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63104. if (invertY === void 0) { invertY = false; }
  63105. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63106. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63107. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63108. _this.format = format;
  63109. _this._engine = scene.getEngine();
  63110. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  63111. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63112. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63113. return _this;
  63114. }
  63115. RawTexture.prototype.update = function (data) {
  63116. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  63117. };
  63118. // Statics
  63119. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63120. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63121. if (invertY === void 0) { invertY = false; }
  63122. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63123. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  63124. };
  63125. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63126. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63127. if (invertY === void 0) { invertY = false; }
  63128. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63129. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63130. };
  63131. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  63132. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63133. if (invertY === void 0) { invertY = false; }
  63134. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63135. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  63136. };
  63137. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63138. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63139. if (invertY === void 0) { invertY = false; }
  63140. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63141. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63142. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  63143. };
  63144. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  63145. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63146. if (invertY === void 0) { invertY = false; }
  63147. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63148. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63149. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  63150. };
  63151. return RawTexture;
  63152. }(BABYLON.Texture));
  63153. BABYLON.RawTexture = RawTexture;
  63154. })(BABYLON || (BABYLON = {}));
  63155. //# sourceMappingURL=babylon.rawTexture.js.map
  63156. "use strict";
  63157. var BABYLON;
  63158. (function (BABYLON) {
  63159. /**
  63160. * Class used to store 3D textures containing user data
  63161. */
  63162. var RawTexture3D = /** @class */ (function (_super) {
  63163. __extends(RawTexture3D, _super);
  63164. /**
  63165. * Create a new RawTexture3D
  63166. * @param data defines the data of the texture
  63167. * @param width defines the width of the texture
  63168. * @param height defines the height of the texture
  63169. * @param depth defines the depth of the texture
  63170. * @param format defines the texture format to use
  63171. * @param scene defines the hosting scene
  63172. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  63173. * @param invertY defines if texture must be stored with Y axis inverted
  63174. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  63175. */
  63176. function RawTexture3D(data, width, height, depth,
  63177. /** Gets or sets the texture format to use*/
  63178. format, scene, generateMipMaps, invertY, samplingMode) {
  63179. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63180. if (invertY === void 0) { invertY = false; }
  63181. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63182. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63183. _this.format = format;
  63184. _this._engine = scene.getEngine();
  63185. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  63186. _this.is3D = true;
  63187. return _this;
  63188. }
  63189. /**
  63190. * Update the texture with new data
  63191. * @param data defines the data to store in the texture
  63192. */
  63193. RawTexture3D.prototype.update = function (data) {
  63194. if (!this._texture) {
  63195. return;
  63196. }
  63197. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  63198. };
  63199. return RawTexture3D;
  63200. }(BABYLON.Texture));
  63201. BABYLON.RawTexture3D = RawTexture3D;
  63202. })(BABYLON || (BABYLON = {}));
  63203. //# sourceMappingURL=babylon.rawTexture3D.js.map
  63204. "use strict";
  63205. var BABYLON;
  63206. (function (BABYLON) {
  63207. /**
  63208. * PostProcess can be used to apply a shader to a texture after it has been rendered
  63209. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  63210. */
  63211. var PostProcess = /** @class */ (function () {
  63212. /**
  63213. * Creates a new instance PostProcess
  63214. * @param name The name of the PostProcess.
  63215. * @param fragmentUrl The url of the fragment shader to be used.
  63216. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  63217. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  63218. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  63219. * @param camera The camera to apply the render pass to.
  63220. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  63221. * @param engine The engine which the post process will be applied. (default: current engine)
  63222. * @param reusable If the post process can be reused on the same frame. (default: false)
  63223. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  63224. * @param textureType Type of textures used when performing the post process. (default: 0)
  63225. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  63226. * @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
  63227. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  63228. */
  63229. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  63230. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  63231. if (defines === void 0) { defines = null; }
  63232. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63233. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  63234. if (blockCompilation === void 0) { blockCompilation = false; }
  63235. this.name = name;
  63236. /**
  63237. * Width of the texture to apply the post process on
  63238. */
  63239. this.width = -1;
  63240. /**
  63241. * Height of the texture to apply the post process on
  63242. */
  63243. this.height = -1;
  63244. /**
  63245. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  63246. */
  63247. this._outputTexture = null;
  63248. /**
  63249. * If the buffer needs to be cleared before applying the post process. (default: true)
  63250. * Should be set to false if shader will overwrite all previous pixels.
  63251. */
  63252. this.autoClear = true;
  63253. /**
  63254. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  63255. */
  63256. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  63257. /**
  63258. * Animations to be used for the post processing
  63259. */
  63260. this.animations = new Array();
  63261. /**
  63262. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  63263. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  63264. */
  63265. this.enablePixelPerfectMode = false;
  63266. /**
  63267. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  63268. */
  63269. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  63270. /**
  63271. * Force textures to be a power of two (default: false)
  63272. */
  63273. this.alwaysForcePOT = false;
  63274. /**
  63275. * Number of sample textures (default: 1)
  63276. */
  63277. this.samples = 1;
  63278. /**
  63279. * Modify the scale of the post process to be the same as the viewport (default: false)
  63280. */
  63281. this.adaptScaleToCurrentViewport = false;
  63282. this._reusable = false;
  63283. /**
  63284. * Smart array of input and output textures for the post process.
  63285. */
  63286. this._textures = new BABYLON.SmartArray(2);
  63287. /**
  63288. * The index in _textures that corresponds to the output texture.
  63289. */
  63290. this._currentRenderTextureInd = 0;
  63291. this._scaleRatio = new BABYLON.Vector2(1, 1);
  63292. this._texelSize = BABYLON.Vector2.Zero();
  63293. // Events
  63294. /**
  63295. * An event triggered when the postprocess is activated.
  63296. */
  63297. this.onActivateObservable = new BABYLON.Observable();
  63298. /**
  63299. * An event triggered when the postprocess changes its size.
  63300. */
  63301. this.onSizeChangedObservable = new BABYLON.Observable();
  63302. /**
  63303. * An event triggered when the postprocess applies its effect.
  63304. */
  63305. this.onApplyObservable = new BABYLON.Observable();
  63306. /**
  63307. * An event triggered before rendering the postprocess
  63308. */
  63309. this.onBeforeRenderObservable = new BABYLON.Observable();
  63310. /**
  63311. * An event triggered after rendering the postprocess
  63312. */
  63313. this.onAfterRenderObservable = new BABYLON.Observable();
  63314. if (camera != null) {
  63315. this._camera = camera;
  63316. this._scene = camera.getScene();
  63317. camera.attachPostProcess(this);
  63318. this._engine = this._scene.getEngine();
  63319. this._scene.postProcesses.push(this);
  63320. }
  63321. else if (engine) {
  63322. this._engine = engine;
  63323. this._engine.postProcesses.push(this);
  63324. }
  63325. this._options = options;
  63326. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  63327. this._reusable = reusable || false;
  63328. this._textureType = textureType;
  63329. this._samplers = samplers || [];
  63330. this._samplers.push("textureSampler");
  63331. this._fragmentUrl = fragmentUrl;
  63332. this._vertexUrl = vertexUrl;
  63333. this._parameters = parameters || [];
  63334. this._parameters.push("scale");
  63335. this._indexParameters = indexParameters;
  63336. if (!blockCompilation) {
  63337. this.updateEffect(defines);
  63338. }
  63339. }
  63340. Object.defineProperty(PostProcess.prototype, "onActivate", {
  63341. /**
  63342. * A function that is added to the onActivateObservable
  63343. */
  63344. set: function (callback) {
  63345. if (this._onActivateObserver) {
  63346. this.onActivateObservable.remove(this._onActivateObserver);
  63347. }
  63348. if (callback) {
  63349. this._onActivateObserver = this.onActivateObservable.add(callback);
  63350. }
  63351. },
  63352. enumerable: true,
  63353. configurable: true
  63354. });
  63355. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  63356. /**
  63357. * A function that is added to the onSizeChangedObservable
  63358. */
  63359. set: function (callback) {
  63360. if (this._onSizeChangedObserver) {
  63361. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  63362. }
  63363. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  63364. },
  63365. enumerable: true,
  63366. configurable: true
  63367. });
  63368. Object.defineProperty(PostProcess.prototype, "onApply", {
  63369. /**
  63370. * A function that is added to the onApplyObservable
  63371. */
  63372. set: function (callback) {
  63373. if (this._onApplyObserver) {
  63374. this.onApplyObservable.remove(this._onApplyObserver);
  63375. }
  63376. this._onApplyObserver = this.onApplyObservable.add(callback);
  63377. },
  63378. enumerable: true,
  63379. configurable: true
  63380. });
  63381. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  63382. /**
  63383. * A function that is added to the onBeforeRenderObservable
  63384. */
  63385. set: function (callback) {
  63386. if (this._onBeforeRenderObserver) {
  63387. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63388. }
  63389. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63390. },
  63391. enumerable: true,
  63392. configurable: true
  63393. });
  63394. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  63395. /**
  63396. * A function that is added to the onAfterRenderObservable
  63397. */
  63398. set: function (callback) {
  63399. if (this._onAfterRenderObserver) {
  63400. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63401. }
  63402. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63403. },
  63404. enumerable: true,
  63405. configurable: true
  63406. });
  63407. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  63408. /**
  63409. * 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
  63410. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  63411. */
  63412. get: function () {
  63413. return this._textures.data[this._currentRenderTextureInd];
  63414. },
  63415. set: function (value) {
  63416. this._forcedOutputTexture = value;
  63417. },
  63418. enumerable: true,
  63419. configurable: true
  63420. });
  63421. /**
  63422. * Gets the camera which post process is applied to.
  63423. * @returns The camera the post process is applied to.
  63424. */
  63425. PostProcess.prototype.getCamera = function () {
  63426. return this._camera;
  63427. };
  63428. Object.defineProperty(PostProcess.prototype, "texelSize", {
  63429. /**
  63430. * Gets the texel size of the postprocess.
  63431. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  63432. */
  63433. get: function () {
  63434. if (this._shareOutputWithPostProcess) {
  63435. return this._shareOutputWithPostProcess.texelSize;
  63436. }
  63437. if (this._forcedOutputTexture) {
  63438. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  63439. }
  63440. return this._texelSize;
  63441. },
  63442. enumerable: true,
  63443. configurable: true
  63444. });
  63445. /**
  63446. * Gets the engine which this post process belongs to.
  63447. * @returns The engine the post process was enabled with.
  63448. */
  63449. PostProcess.prototype.getEngine = function () {
  63450. return this._engine;
  63451. };
  63452. /**
  63453. * The effect that is created when initializing the post process.
  63454. * @returns The created effect corrisponding the the postprocess.
  63455. */
  63456. PostProcess.prototype.getEffect = function () {
  63457. return this._effect;
  63458. };
  63459. /**
  63460. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  63461. * @param postProcess The post process to share the output with.
  63462. * @returns This post process.
  63463. */
  63464. PostProcess.prototype.shareOutputWith = function (postProcess) {
  63465. this._disposeTextures();
  63466. this._shareOutputWithPostProcess = postProcess;
  63467. return this;
  63468. };
  63469. /**
  63470. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  63471. * This should be called if the post process that shares output with this post process is disabled/disposed.
  63472. */
  63473. PostProcess.prototype.useOwnOutput = function () {
  63474. if (this._textures.length == 0) {
  63475. this._textures = new BABYLON.SmartArray(2);
  63476. }
  63477. this._shareOutputWithPostProcess = null;
  63478. };
  63479. /**
  63480. * Updates the effect with the current post process compile time values and recompiles the shader.
  63481. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  63482. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  63483. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  63484. * @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
  63485. * @param onCompiled Called when the shader has been compiled.
  63486. * @param onError Called if there is an error when compiling a shader.
  63487. */
  63488. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  63489. if (defines === void 0) { defines = null; }
  63490. if (uniforms === void 0) { uniforms = null; }
  63491. if (samplers === void 0) { samplers = null; }
  63492. 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);
  63493. };
  63494. /**
  63495. * The post process is reusable if it can be used multiple times within one frame.
  63496. * @returns If the post process is reusable
  63497. */
  63498. PostProcess.prototype.isReusable = function () {
  63499. return this._reusable;
  63500. };
  63501. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  63502. PostProcess.prototype.markTextureDirty = function () {
  63503. this.width = -1;
  63504. };
  63505. /**
  63506. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  63507. * 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.
  63508. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  63509. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  63510. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  63511. * @returns The target texture that was bound to be written to.
  63512. */
  63513. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  63514. var _this = this;
  63515. if (sourceTexture === void 0) { sourceTexture = null; }
  63516. camera = camera || this._camera;
  63517. var scene = camera.getScene();
  63518. var engine = scene.getEngine();
  63519. var maxSize = engine.getCaps().maxTextureSize;
  63520. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  63521. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  63522. // 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
  63523. var webVRCamera = camera.parent;
  63524. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  63525. requiredWidth /= 2;
  63526. }
  63527. var desiredWidth = (this._options.width || requiredWidth);
  63528. var desiredHeight = this._options.height || requiredHeight;
  63529. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  63530. if (this.adaptScaleToCurrentViewport) {
  63531. var currentViewport = engine.currentViewport;
  63532. if (currentViewport) {
  63533. desiredWidth *= currentViewport.width;
  63534. desiredHeight *= currentViewport.height;
  63535. }
  63536. }
  63537. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  63538. if (!this._options.width) {
  63539. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  63540. }
  63541. if (!this._options.height) {
  63542. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  63543. }
  63544. }
  63545. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  63546. if (this._textures.length > 0) {
  63547. for (var i = 0; i < this._textures.length; i++) {
  63548. this._engine._releaseTexture(this._textures.data[i]);
  63549. }
  63550. this._textures.reset();
  63551. }
  63552. this.width = desiredWidth;
  63553. this.height = desiredHeight;
  63554. var textureSize = { width: this.width, height: this.height };
  63555. var textureOptions = {
  63556. generateMipMaps: false,
  63557. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  63558. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  63559. samplingMode: this.renderTargetSamplingMode,
  63560. type: this._textureType
  63561. };
  63562. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63563. if (this._reusable) {
  63564. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  63565. }
  63566. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  63567. this.onSizeChangedObservable.notifyObservers(this);
  63568. }
  63569. this._textures.forEach(function (texture) {
  63570. if (texture.samples !== _this.samples) {
  63571. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  63572. }
  63573. });
  63574. }
  63575. var target;
  63576. if (this._shareOutputWithPostProcess) {
  63577. target = this._shareOutputWithPostProcess.inputTexture;
  63578. }
  63579. else if (this._forcedOutputTexture) {
  63580. target = this._forcedOutputTexture;
  63581. this.width = this._forcedOutputTexture.width;
  63582. this.height = this._forcedOutputTexture.height;
  63583. }
  63584. else {
  63585. target = this.inputTexture;
  63586. }
  63587. // Bind the input of this post process to be used as the output of the previous post process.
  63588. if (this.enablePixelPerfectMode) {
  63589. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  63590. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  63591. }
  63592. else {
  63593. this._scaleRatio.copyFromFloats(1, 1);
  63594. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  63595. }
  63596. this.onActivateObservable.notifyObservers(camera);
  63597. // Clear
  63598. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  63599. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  63600. }
  63601. if (this._reusable) {
  63602. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  63603. }
  63604. return target;
  63605. };
  63606. Object.defineProperty(PostProcess.prototype, "isSupported", {
  63607. /**
  63608. * If the post process is supported.
  63609. */
  63610. get: function () {
  63611. return this._effect.isSupported;
  63612. },
  63613. enumerable: true,
  63614. configurable: true
  63615. });
  63616. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  63617. /**
  63618. * The aspect ratio of the output texture.
  63619. */
  63620. get: function () {
  63621. if (this._shareOutputWithPostProcess) {
  63622. return this._shareOutputWithPostProcess.aspectRatio;
  63623. }
  63624. if (this._forcedOutputTexture) {
  63625. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  63626. }
  63627. return this.width / this.height;
  63628. },
  63629. enumerable: true,
  63630. configurable: true
  63631. });
  63632. /**
  63633. * Get a value indicating if the post-process is ready to be used
  63634. * @returns true if the post-process is ready (shader is compiled)
  63635. */
  63636. PostProcess.prototype.isReady = function () {
  63637. return this._effect && this._effect.isReady();
  63638. };
  63639. /**
  63640. * Binds all textures and uniforms to the shader, this will be run on every pass.
  63641. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  63642. */
  63643. PostProcess.prototype.apply = function () {
  63644. // Check
  63645. if (!this._effect || !this._effect.isReady())
  63646. return null;
  63647. // States
  63648. this._engine.enableEffect(this._effect);
  63649. this._engine.setState(false);
  63650. this._engine.setDepthBuffer(false);
  63651. this._engine.setDepthWrite(false);
  63652. // Alpha
  63653. this._engine.setAlphaMode(this.alphaMode);
  63654. if (this.alphaConstants) {
  63655. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  63656. }
  63657. // Bind the output texture of the preivous post process as the input to this post process.
  63658. var source;
  63659. if (this._shareOutputWithPostProcess) {
  63660. source = this._shareOutputWithPostProcess.inputTexture;
  63661. }
  63662. else if (this._forcedOutputTexture) {
  63663. source = this._forcedOutputTexture;
  63664. }
  63665. else {
  63666. source = this.inputTexture;
  63667. }
  63668. this._effect._bindTexture("textureSampler", source);
  63669. // Parameters
  63670. this._effect.setVector2("scale", this._scaleRatio);
  63671. this.onApplyObservable.notifyObservers(this._effect);
  63672. return this._effect;
  63673. };
  63674. PostProcess.prototype._disposeTextures = function () {
  63675. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  63676. return;
  63677. }
  63678. if (this._textures.length > 0) {
  63679. for (var i = 0; i < this._textures.length; i++) {
  63680. this._engine._releaseTexture(this._textures.data[i]);
  63681. }
  63682. }
  63683. this._textures.dispose();
  63684. };
  63685. /**
  63686. * Disposes the post process.
  63687. * @param camera The camera to dispose the post process on.
  63688. */
  63689. PostProcess.prototype.dispose = function (camera) {
  63690. camera = camera || this._camera;
  63691. this._disposeTextures();
  63692. if (this._scene) {
  63693. var index_1 = this._scene.postProcesses.indexOf(this);
  63694. if (index_1 !== -1) {
  63695. this._scene.postProcesses.splice(index_1, 1);
  63696. }
  63697. }
  63698. else {
  63699. var index_2 = this._engine.postProcesses.indexOf(this);
  63700. if (index_2 !== -1) {
  63701. this._engine.postProcesses.splice(index_2, 1);
  63702. }
  63703. }
  63704. if (!camera) {
  63705. return;
  63706. }
  63707. camera.detachPostProcess(this);
  63708. var index = camera._postProcesses.indexOf(this);
  63709. if (index === 0 && camera._postProcesses.length > 0) {
  63710. var firstPostProcess = this._camera._getFirstPostProcess();
  63711. if (firstPostProcess) {
  63712. firstPostProcess.markTextureDirty();
  63713. }
  63714. }
  63715. this.onActivateObservable.clear();
  63716. this.onAfterRenderObservable.clear();
  63717. this.onApplyObservable.clear();
  63718. this.onBeforeRenderObservable.clear();
  63719. this.onSizeChangedObservable.clear();
  63720. };
  63721. return PostProcess;
  63722. }());
  63723. BABYLON.PostProcess = PostProcess;
  63724. })(BABYLON || (BABYLON = {}));
  63725. //# sourceMappingURL=babylon.postProcess.js.map
  63726. "use strict";
  63727. var BABYLON;
  63728. (function (BABYLON) {
  63729. var PassPostProcess = /** @class */ (function (_super) {
  63730. __extends(PassPostProcess, _super);
  63731. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  63732. if (camera === void 0) { camera = null; }
  63733. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63734. if (blockCompilation === void 0) { blockCompilation = false; }
  63735. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  63736. }
  63737. return PassPostProcess;
  63738. }(BABYLON.PostProcess));
  63739. BABYLON.PassPostProcess = PassPostProcess;
  63740. })(BABYLON || (BABYLON = {}));
  63741. //# sourceMappingURL=babylon.passPostProcess.js.map
  63742. "use strict";
  63743. var __assign = (this && this.__assign) || Object.assign || function(t) {
  63744. for (var s, i = 1, n = arguments.length; i < n; i++) {
  63745. s = arguments[i];
  63746. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  63747. t[p] = s[p];
  63748. }
  63749. return t;
  63750. };
  63751. var BABYLON;
  63752. (function (BABYLON) {
  63753. /**
  63754. * Default implementation IShadowGenerator.
  63755. * This is the main object responsible of generating shadows in the framework.
  63756. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  63757. */
  63758. var ShadowGenerator = /** @class */ (function () {
  63759. /**
  63760. * Creates a ShadowGenerator object.
  63761. * A ShadowGenerator is the required tool to use the shadows.
  63762. * Each light casting shadows needs to use its own ShadowGenerator.
  63763. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  63764. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  63765. * @param light The light object generating the shadows.
  63766. * @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.
  63767. */
  63768. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  63769. this._bias = 0.00005;
  63770. this._normalBias = 0;
  63771. this._blurBoxOffset = 1;
  63772. this._blurScale = 2;
  63773. this._blurKernel = 1;
  63774. this._useKernelBlur = false;
  63775. this._filter = ShadowGenerator.FILTER_NONE;
  63776. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  63777. this._contactHardeningLightSizeUVRatio = 0.1;
  63778. this._darkness = 0;
  63779. this._transparencyShadow = false;
  63780. /**
  63781. * Controls the extent to which the shadows fade out at the edge of the frustum
  63782. * Used only by directionals and spots
  63783. */
  63784. this.frustumEdgeFalloff = 0;
  63785. /**
  63786. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  63787. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  63788. * It might on the other hand introduce peter panning.
  63789. */
  63790. this.forceBackFacesOnly = false;
  63791. this._lightDirection = BABYLON.Vector3.Zero();
  63792. this._viewMatrix = BABYLON.Matrix.Zero();
  63793. this._projectionMatrix = BABYLON.Matrix.Zero();
  63794. this._transformMatrix = BABYLON.Matrix.Zero();
  63795. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63796. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63797. this._currentFaceIndex = 0;
  63798. this._currentFaceIndexCache = 0;
  63799. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  63800. this._mapSize = mapSize;
  63801. this._light = light;
  63802. this._scene = light.getScene();
  63803. light._shadowGenerator = this;
  63804. // Texture type fallback from float to int if not supported.
  63805. var caps = this._scene.getEngine().getCaps();
  63806. if (!useFullFloatFirst) {
  63807. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  63808. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63809. }
  63810. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  63811. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63812. }
  63813. else {
  63814. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63815. }
  63816. }
  63817. else {
  63818. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  63819. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63820. }
  63821. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  63822. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63823. }
  63824. else {
  63825. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63826. }
  63827. }
  63828. this._initializeGenerator();
  63829. this._applyFilterValues();
  63830. }
  63831. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  63832. /**
  63833. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  63834. */
  63835. get: function () {
  63836. return this._bias;
  63837. },
  63838. /**
  63839. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  63840. */
  63841. set: function (bias) {
  63842. this._bias = bias;
  63843. },
  63844. enumerable: true,
  63845. configurable: true
  63846. });
  63847. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  63848. /**
  63849. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  63850. */
  63851. get: function () {
  63852. return this._normalBias;
  63853. },
  63854. /**
  63855. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  63856. */
  63857. set: function (normalBias) {
  63858. this._normalBias = normalBias;
  63859. },
  63860. enumerable: true,
  63861. configurable: true
  63862. });
  63863. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  63864. /**
  63865. * Gets the blur box offset: offset applied during the blur pass.
  63866. * Only usefull if useKernelBlur = false
  63867. */
  63868. get: function () {
  63869. return this._blurBoxOffset;
  63870. },
  63871. /**
  63872. * Sets the blur box offset: offset applied during the blur pass.
  63873. * Only usefull if useKernelBlur = false
  63874. */
  63875. set: function (value) {
  63876. if (this._blurBoxOffset === value) {
  63877. return;
  63878. }
  63879. this._blurBoxOffset = value;
  63880. this._disposeBlurPostProcesses();
  63881. },
  63882. enumerable: true,
  63883. configurable: true
  63884. });
  63885. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  63886. /**
  63887. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  63888. * 2 means half of the size.
  63889. */
  63890. get: function () {
  63891. return this._blurScale;
  63892. },
  63893. /**
  63894. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  63895. * 2 means half of the size.
  63896. */
  63897. set: function (value) {
  63898. if (this._blurScale === value) {
  63899. return;
  63900. }
  63901. this._blurScale = value;
  63902. this._disposeBlurPostProcesses();
  63903. },
  63904. enumerable: true,
  63905. configurable: true
  63906. });
  63907. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  63908. /**
  63909. * Gets the blur kernel: kernel size of the blur pass.
  63910. * Only usefull if useKernelBlur = true
  63911. */
  63912. get: function () {
  63913. return this._blurKernel;
  63914. },
  63915. /**
  63916. * Sets the blur kernel: kernel size of the blur pass.
  63917. * Only usefull if useKernelBlur = true
  63918. */
  63919. set: function (value) {
  63920. if (this._blurKernel === value) {
  63921. return;
  63922. }
  63923. this._blurKernel = value;
  63924. this._disposeBlurPostProcesses();
  63925. },
  63926. enumerable: true,
  63927. configurable: true
  63928. });
  63929. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  63930. /**
  63931. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  63932. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  63933. */
  63934. get: function () {
  63935. return this._useKernelBlur;
  63936. },
  63937. /**
  63938. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  63939. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  63940. */
  63941. set: function (value) {
  63942. if (this._useKernelBlur === value) {
  63943. return;
  63944. }
  63945. this._useKernelBlur = value;
  63946. this._disposeBlurPostProcesses();
  63947. },
  63948. enumerable: true,
  63949. configurable: true
  63950. });
  63951. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  63952. /**
  63953. * Gets the depth scale used in ESM mode.
  63954. */
  63955. get: function () {
  63956. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  63957. },
  63958. /**
  63959. * Sets the depth scale used in ESM mode.
  63960. * This can override the scale stored on the light.
  63961. */
  63962. set: function (value) {
  63963. this._depthScale = value;
  63964. },
  63965. enumerable: true,
  63966. configurable: true
  63967. });
  63968. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  63969. /**
  63970. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  63971. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  63972. */
  63973. get: function () {
  63974. return this._filter;
  63975. },
  63976. /**
  63977. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  63978. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  63979. */
  63980. set: function (value) {
  63981. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  63982. if (this._light.needCube()) {
  63983. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  63984. this.useExponentialShadowMap = true;
  63985. return;
  63986. }
  63987. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  63988. this.useCloseExponentialShadowMap = true;
  63989. return;
  63990. }
  63991. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  63992. this.usePoissonSampling = true;
  63993. return;
  63994. }
  63995. }
  63996. // Weblg1 fallback for PCF.
  63997. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  63998. if (this._scene.getEngine().webGLVersion === 1) {
  63999. this.usePoissonSampling = true;
  64000. return;
  64001. }
  64002. }
  64003. if (this._filter === value) {
  64004. return;
  64005. }
  64006. this._filter = value;
  64007. this._disposeBlurPostProcesses();
  64008. this._applyFilterValues();
  64009. this._light._markMeshesAsLightDirty();
  64010. },
  64011. enumerable: true,
  64012. configurable: true
  64013. });
  64014. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  64015. /**
  64016. * Gets if the current filter is set to Poisson Sampling.
  64017. */
  64018. get: function () {
  64019. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  64020. },
  64021. /**
  64022. * Sets the current filter to Poisson Sampling.
  64023. */
  64024. set: function (value) {
  64025. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  64026. return;
  64027. }
  64028. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  64029. },
  64030. enumerable: true,
  64031. configurable: true
  64032. });
  64033. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  64034. /**
  64035. * Gets if the current filter is set to VSM.
  64036. * DEPRECATED. Should use useExponentialShadowMap instead.
  64037. */
  64038. get: function () {
  64039. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64040. return this.useExponentialShadowMap;
  64041. },
  64042. /**
  64043. * Sets the current filter is to VSM.
  64044. * DEPRECATED. Should use useExponentialShadowMap instead.
  64045. */
  64046. set: function (value) {
  64047. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64048. this.useExponentialShadowMap = value;
  64049. },
  64050. enumerable: true,
  64051. configurable: true
  64052. });
  64053. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  64054. /**
  64055. * Gets if the current filter is set to blurred VSM.
  64056. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64057. */
  64058. get: function () {
  64059. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64060. return this.useBlurExponentialShadowMap;
  64061. },
  64062. /**
  64063. * Sets the current filter is to blurred VSM.
  64064. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  64065. */
  64066. set: function (value) {
  64067. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  64068. this.useBlurExponentialShadowMap = value;
  64069. },
  64070. enumerable: true,
  64071. configurable: true
  64072. });
  64073. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  64074. /**
  64075. * Gets if the current filter is set to ESM.
  64076. */
  64077. get: function () {
  64078. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  64079. },
  64080. /**
  64081. * Sets the current filter is to ESM.
  64082. */
  64083. set: function (value) {
  64084. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  64085. return;
  64086. }
  64087. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64088. },
  64089. enumerable: true,
  64090. configurable: true
  64091. });
  64092. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  64093. /**
  64094. * Gets if the current filter is set to filtered ESM.
  64095. */
  64096. get: function () {
  64097. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  64098. },
  64099. /**
  64100. * Gets if the current filter is set to filtered ESM.
  64101. */
  64102. set: function (value) {
  64103. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64104. return;
  64105. }
  64106. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64107. },
  64108. enumerable: true,
  64109. configurable: true
  64110. });
  64111. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  64112. /**
  64113. * Gets if the current filter is set to "close ESM" (using the inverse of the
  64114. * exponential to prevent steep falloff artifacts).
  64115. */
  64116. get: function () {
  64117. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  64118. },
  64119. /**
  64120. * Sets the current filter to "close ESM" (using the inverse of the
  64121. * exponential to prevent steep falloff artifacts).
  64122. */
  64123. set: function (value) {
  64124. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  64125. return;
  64126. }
  64127. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64128. },
  64129. enumerable: true,
  64130. configurable: true
  64131. });
  64132. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  64133. /**
  64134. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  64135. * exponential to prevent steep falloff artifacts).
  64136. */
  64137. get: function () {
  64138. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  64139. },
  64140. /**
  64141. * Sets the current filter to filtered "close ESM" (using the inverse of the
  64142. * exponential to prevent steep falloff artifacts).
  64143. */
  64144. set: function (value) {
  64145. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64146. return;
  64147. }
  64148. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  64149. },
  64150. enumerable: true,
  64151. configurable: true
  64152. });
  64153. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  64154. /**
  64155. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  64156. */
  64157. get: function () {
  64158. return this.filter === ShadowGenerator.FILTER_PCF;
  64159. },
  64160. /**
  64161. * Sets the current filter to "PCF" (percentage closer filtering).
  64162. */
  64163. set: function (value) {
  64164. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  64165. return;
  64166. }
  64167. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  64168. },
  64169. enumerable: true,
  64170. configurable: true
  64171. });
  64172. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  64173. /**
  64174. * Gets the PCF or PCSS Quality.
  64175. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64176. */
  64177. get: function () {
  64178. return this._filteringQuality;
  64179. },
  64180. /**
  64181. * Sets the PCF or PCSS Quality.
  64182. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  64183. */
  64184. set: function (filteringQuality) {
  64185. this._filteringQuality = filteringQuality;
  64186. },
  64187. enumerable: true,
  64188. configurable: true
  64189. });
  64190. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  64191. /**
  64192. * Gets if the current filter is set to "PCSS" (contact hardening).
  64193. */
  64194. get: function () {
  64195. return this.filter === ShadowGenerator.FILTER_PCSS;
  64196. },
  64197. /**
  64198. * Sets the current filter to "PCSS" (contact hardening).
  64199. */
  64200. set: function (value) {
  64201. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  64202. return;
  64203. }
  64204. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  64205. },
  64206. enumerable: true,
  64207. configurable: true
  64208. });
  64209. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  64210. /**
  64211. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64212. * Using a ratio helps keeping shape stability independently of the map size.
  64213. *
  64214. * It does not account for the light projection as it was having too much
  64215. * instability during the light setup or during light position changes.
  64216. *
  64217. * Only valid if useContactHardeningShadow is true.
  64218. */
  64219. get: function () {
  64220. return this._contactHardeningLightSizeUVRatio;
  64221. },
  64222. /**
  64223. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  64224. * Using a ratio helps keeping shape stability independently of the map size.
  64225. *
  64226. * It does not account for the light projection as it was having too much
  64227. * instability during the light setup or during light position changes.
  64228. *
  64229. * Only valid if useContactHardeningShadow is true.
  64230. */
  64231. set: function (contactHardeningLightSizeUVRatio) {
  64232. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  64233. },
  64234. enumerable: true,
  64235. configurable: true
  64236. });
  64237. /**
  64238. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  64239. * 0 means strongest and 1 would means no shadow.
  64240. * @returns the darkness.
  64241. */
  64242. ShadowGenerator.prototype.getDarkness = function () {
  64243. return this._darkness;
  64244. };
  64245. /**
  64246. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  64247. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  64248. * @returns the shadow generator allowing fluent coding.
  64249. */
  64250. ShadowGenerator.prototype.setDarkness = function (darkness) {
  64251. if (darkness >= 1.0)
  64252. this._darkness = 1.0;
  64253. else if (darkness <= 0.0)
  64254. this._darkness = 0.0;
  64255. else
  64256. this._darkness = darkness;
  64257. return this;
  64258. };
  64259. /**
  64260. * Sets the ability to have transparent shadow (boolean).
  64261. * @param transparent True if transparent else False
  64262. * @returns the shadow generator allowing fluent coding
  64263. */
  64264. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  64265. this._transparencyShadow = transparent;
  64266. return this;
  64267. };
  64268. /**
  64269. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  64270. * @returns The render target texture if present otherwise, null
  64271. */
  64272. ShadowGenerator.prototype.getShadowMap = function () {
  64273. return this._shadowMap;
  64274. };
  64275. /**
  64276. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  64277. * @returns The render target texture if the shadow map is present otherwise, null
  64278. */
  64279. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  64280. if (this._shadowMap2) {
  64281. return this._shadowMap2;
  64282. }
  64283. return this._shadowMap;
  64284. };
  64285. /**
  64286. * Helper function to add a mesh and its descendants to the list of shadow casters.
  64287. * @param mesh Mesh to add
  64288. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  64289. * @returns the Shadow Generator itself
  64290. */
  64291. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  64292. if (includeDescendants === void 0) { includeDescendants = true; }
  64293. if (!this._shadowMap) {
  64294. return this;
  64295. }
  64296. if (!this._shadowMap.renderList) {
  64297. this._shadowMap.renderList = [];
  64298. }
  64299. this._shadowMap.renderList.push(mesh);
  64300. if (includeDescendants) {
  64301. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  64302. }
  64303. return this;
  64304. var _a;
  64305. };
  64306. /**
  64307. * Helper function to remove a mesh and its descendants from the list of shadow casters
  64308. * @param mesh Mesh to remove
  64309. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  64310. * @returns the Shadow Generator itself
  64311. */
  64312. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  64313. if (includeDescendants === void 0) { includeDescendants = true; }
  64314. if (!this._shadowMap || !this._shadowMap.renderList) {
  64315. return this;
  64316. }
  64317. var index = this._shadowMap.renderList.indexOf(mesh);
  64318. if (index !== -1) {
  64319. this._shadowMap.renderList.splice(index, 1);
  64320. }
  64321. if (includeDescendants) {
  64322. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  64323. var child = _a[_i];
  64324. this.removeShadowCaster(child);
  64325. }
  64326. }
  64327. return this;
  64328. };
  64329. /**
  64330. * Returns the associated light object.
  64331. * @returns the light generating the shadow
  64332. */
  64333. ShadowGenerator.prototype.getLight = function () {
  64334. return this._light;
  64335. };
  64336. ShadowGenerator.prototype._initializeGenerator = function () {
  64337. this._light._markMeshesAsLightDirty();
  64338. this._initializeShadowMap();
  64339. };
  64340. ShadowGenerator.prototype._initializeShadowMap = function () {
  64341. var _this = this;
  64342. // Render target
  64343. var engine = this._scene.getEngine();
  64344. if (engine.webGLVersion > 1) {
  64345. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  64346. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  64347. }
  64348. else {
  64349. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  64350. }
  64351. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64352. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64353. this._shadowMap.anisotropicFilteringLevel = 1;
  64354. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64355. this._shadowMap.renderParticles = false;
  64356. this._shadowMap.ignoreCameraViewport = true;
  64357. // Record Face Index before render.
  64358. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  64359. _this._currentFaceIndex = faceIndex;
  64360. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64361. engine.setColorWrite(false);
  64362. }
  64363. });
  64364. // Custom render function.
  64365. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  64366. // Blur if required afer render.
  64367. this._shadowMap.onAfterUnbindObservable.add(function () {
  64368. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64369. engine.setColorWrite(true);
  64370. }
  64371. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  64372. return;
  64373. }
  64374. var shadowMap = _this.getShadowMapForRendering();
  64375. if (shadowMap) {
  64376. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  64377. }
  64378. });
  64379. // Clear according to the chosen filter.
  64380. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  64381. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  64382. this._shadowMap.onClearObservable.add(function (engine) {
  64383. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  64384. engine.clear(clearOne, false, true, false);
  64385. }
  64386. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  64387. engine.clear(clearZero, true, true, false);
  64388. }
  64389. else {
  64390. engine.clear(clearOne, true, true, false);
  64391. }
  64392. });
  64393. };
  64394. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  64395. var _this = this;
  64396. var engine = this._scene.getEngine();
  64397. var targetSize = this._mapSize / this.blurScale;
  64398. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  64399. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  64400. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64401. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64402. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64403. }
  64404. if (this.useKernelBlur) {
  64405. 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);
  64406. this._kernelBlurXPostprocess.width = targetSize;
  64407. this._kernelBlurXPostprocess.height = targetSize;
  64408. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  64409. effect.setTexture("textureSampler", _this._shadowMap);
  64410. });
  64411. 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);
  64412. this._kernelBlurXPostprocess.autoClear = false;
  64413. this._kernelBlurYPostprocess.autoClear = false;
  64414. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64415. this._kernelBlurXPostprocess.packedFloat = true;
  64416. this._kernelBlurYPostprocess.packedFloat = true;
  64417. }
  64418. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  64419. }
  64420. else {
  64421. 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);
  64422. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  64423. effect.setFloat2("screenSize", targetSize, targetSize);
  64424. effect.setTexture("textureSampler", _this._shadowMap);
  64425. });
  64426. this._boxBlurPostprocess.autoClear = false;
  64427. this._blurPostProcesses = [this._boxBlurPostprocess];
  64428. }
  64429. };
  64430. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64431. var index;
  64432. var engine = this._scene.getEngine();
  64433. if (depthOnlySubMeshes.length) {
  64434. engine.setColorWrite(false);
  64435. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64436. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  64437. }
  64438. engine.setColorWrite(true);
  64439. }
  64440. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64441. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  64442. }
  64443. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64444. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  64445. }
  64446. if (this._transparencyShadow) {
  64447. for (index = 0; index < transparentSubMeshes.length; index++) {
  64448. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  64449. }
  64450. }
  64451. };
  64452. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  64453. var _this = this;
  64454. var mesh = subMesh.getRenderingMesh();
  64455. var scene = this._scene;
  64456. var engine = scene.getEngine();
  64457. var material = subMesh.getMaterial();
  64458. if (!material) {
  64459. return;
  64460. }
  64461. // Culling
  64462. engine.setState(material.backFaceCulling);
  64463. // Managing instances
  64464. var batch = mesh._getInstancesRenderList(subMesh._id);
  64465. if (batch.mustReturn) {
  64466. return;
  64467. }
  64468. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  64469. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  64470. engine.enableEffect(this._effect);
  64471. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  64472. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  64473. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  64474. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64475. this._effect.setVector3("lightData", this._cachedDirection);
  64476. }
  64477. else {
  64478. this._effect.setVector3("lightData", this._cachedPosition);
  64479. }
  64480. if (scene.activeCamera) {
  64481. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  64482. }
  64483. // Alpha test
  64484. if (material && material.needAlphaTesting()) {
  64485. var alphaTexture = material.getAlphaTestTexture();
  64486. if (alphaTexture) {
  64487. this._effect.setTexture("diffuseSampler", alphaTexture);
  64488. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  64489. }
  64490. }
  64491. // Bones
  64492. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64493. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  64494. }
  64495. // Morph targets
  64496. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  64497. if (this.forceBackFacesOnly) {
  64498. engine.setState(true, 0, false, true);
  64499. }
  64500. // Draw
  64501. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64502. if (this.forceBackFacesOnly) {
  64503. engine.setState(true, 0, false, false);
  64504. }
  64505. }
  64506. else {
  64507. // Need to reset refresh rate of the shadowMap
  64508. if (this._shadowMap) {
  64509. this._shadowMap.resetRefreshCounter();
  64510. }
  64511. }
  64512. };
  64513. ShadowGenerator.prototype._applyFilterValues = function () {
  64514. if (!this._shadowMap) {
  64515. return;
  64516. }
  64517. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  64518. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  64519. }
  64520. else {
  64521. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64522. }
  64523. };
  64524. /**
  64525. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64526. * @param onCompiled Callback triggered at the and of the effects compilation
  64527. * @param options Sets of optional options forcing the compilation with different modes
  64528. */
  64529. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  64530. var _this = this;
  64531. var localOptions = __assign({ useInstances: false }, options);
  64532. var shadowMap = this.getShadowMap();
  64533. if (!shadowMap) {
  64534. if (onCompiled) {
  64535. onCompiled(this);
  64536. }
  64537. return;
  64538. }
  64539. var renderList = shadowMap.renderList;
  64540. if (!renderList) {
  64541. if (onCompiled) {
  64542. onCompiled(this);
  64543. }
  64544. return;
  64545. }
  64546. var subMeshes = new Array();
  64547. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  64548. var mesh = renderList_1[_i];
  64549. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  64550. }
  64551. if (subMeshes.length === 0) {
  64552. if (onCompiled) {
  64553. onCompiled(this);
  64554. }
  64555. return;
  64556. }
  64557. var currentIndex = 0;
  64558. var checkReady = function () {
  64559. if (!_this._scene || !_this._scene.getEngine()) {
  64560. return;
  64561. }
  64562. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  64563. currentIndex++;
  64564. if (currentIndex >= subMeshes.length) {
  64565. if (onCompiled) {
  64566. onCompiled(_this);
  64567. }
  64568. return;
  64569. }
  64570. }
  64571. setTimeout(checkReady, 16);
  64572. };
  64573. checkReady();
  64574. };
  64575. /**
  64576. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  64577. * @param options Sets of optional options forcing the compilation with different modes
  64578. * @returns A promise that resolves when the compilation completes
  64579. */
  64580. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  64581. var _this = this;
  64582. return new Promise(function (resolve) {
  64583. _this.forceCompilation(function () {
  64584. resolve();
  64585. }, options);
  64586. });
  64587. };
  64588. /**
  64589. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  64590. * @param subMesh The submesh we want to render in the shadow map
  64591. * @param useInstances Defines wether will draw in the map using instances
  64592. * @returns true if ready otherwise, false
  64593. */
  64594. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  64595. var defines = [];
  64596. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64597. defines.push("#define FLOAT");
  64598. }
  64599. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64600. defines.push("#define ESM");
  64601. }
  64602. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  64603. defines.push("#define DEPTHTEXTURE");
  64604. }
  64605. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64606. var mesh = subMesh.getMesh();
  64607. var material = subMesh.getMaterial();
  64608. // Normal bias.
  64609. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  64610. attribs.push(BABYLON.VertexBuffer.NormalKind);
  64611. defines.push("#define NORMAL");
  64612. if (mesh.nonUniformScaling) {
  64613. defines.push("#define NONUNIFORMSCALING");
  64614. }
  64615. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  64616. defines.push("#define DIRECTIONINLIGHTDATA");
  64617. }
  64618. }
  64619. // Alpha test
  64620. if (material && material.needAlphaTesting()) {
  64621. var alphaTexture = material.getAlphaTestTexture();
  64622. if (alphaTexture) {
  64623. defines.push("#define ALPHATEST");
  64624. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64625. attribs.push(BABYLON.VertexBuffer.UVKind);
  64626. defines.push("#define UV1");
  64627. }
  64628. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64629. if (alphaTexture.coordinatesIndex === 1) {
  64630. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64631. defines.push("#define UV2");
  64632. }
  64633. }
  64634. }
  64635. }
  64636. // Bones
  64637. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64638. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64639. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64640. if (mesh.numBoneInfluencers > 4) {
  64641. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64642. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64643. }
  64644. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64645. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  64646. }
  64647. else {
  64648. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64649. }
  64650. // Morph targets
  64651. var manager = mesh.morphTargetManager;
  64652. var morphInfluencers = 0;
  64653. if (manager) {
  64654. if (manager.numInfluencers > 0) {
  64655. defines.push("#define MORPHTARGETS");
  64656. morphInfluencers = manager.numInfluencers;
  64657. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  64658. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  64659. }
  64660. }
  64661. // Instances
  64662. if (useInstances) {
  64663. defines.push("#define INSTANCES");
  64664. attribs.push("world0");
  64665. attribs.push("world1");
  64666. attribs.push("world2");
  64667. attribs.push("world3");
  64668. }
  64669. // Get correct effect
  64670. var join = defines.join("\n");
  64671. if (this._cachedDefines !== join) {
  64672. this._cachedDefines = join;
  64673. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  64674. }
  64675. if (!this._effect.isReady()) {
  64676. return false;
  64677. }
  64678. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64679. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  64680. this._initializeBlurRTTAndPostProcesses();
  64681. }
  64682. }
  64683. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  64684. return false;
  64685. }
  64686. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  64687. return false;
  64688. }
  64689. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  64690. return false;
  64691. }
  64692. return true;
  64693. };
  64694. /**
  64695. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  64696. * @param defines Defines of the material we want to update
  64697. * @param lightIndex Index of the light in the enabled light list of the material
  64698. */
  64699. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  64700. var scene = this._scene;
  64701. var light = this._light;
  64702. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64703. return;
  64704. }
  64705. defines["SHADOW" + lightIndex] = true;
  64706. if (this.useContactHardeningShadow) {
  64707. defines["SHADOWPCSS" + lightIndex] = true;
  64708. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64709. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64710. }
  64711. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64712. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64713. }
  64714. // else default to high.
  64715. }
  64716. if (this.usePercentageCloserFiltering) {
  64717. defines["SHADOWPCF" + lightIndex] = true;
  64718. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  64719. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  64720. }
  64721. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  64722. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  64723. }
  64724. // else default to high.
  64725. }
  64726. else if (this.usePoissonSampling) {
  64727. defines["SHADOWPOISSON" + lightIndex] = true;
  64728. }
  64729. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  64730. defines["SHADOWESM" + lightIndex] = true;
  64731. }
  64732. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  64733. defines["SHADOWCLOSEESM" + lightIndex] = true;
  64734. }
  64735. if (light.needCube()) {
  64736. defines["SHADOWCUBE" + lightIndex] = true;
  64737. }
  64738. };
  64739. /**
  64740. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  64741. * defined in the generator but impacting the effect).
  64742. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  64743. * @param effect The effect we are binfing the information for
  64744. */
  64745. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  64746. var light = this._light;
  64747. var scene = this._scene;
  64748. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  64749. return;
  64750. }
  64751. var camera = scene.activeCamera;
  64752. if (!camera) {
  64753. return;
  64754. }
  64755. var shadowMap = this.getShadowMap();
  64756. if (!shadowMap) {
  64757. return;
  64758. }
  64759. if (!light.needCube()) {
  64760. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  64761. }
  64762. // Only PCF uses depth stencil texture.
  64763. if (this._filter === ShadowGenerator.FILTER_PCF) {
  64764. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64765. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  64766. }
  64767. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  64768. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64769. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  64770. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  64771. }
  64772. else {
  64773. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  64774. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  64775. }
  64776. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  64777. };
  64778. /**
  64779. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  64780. * (eq to shadow prjection matrix * light transform matrix)
  64781. * @returns The transform matrix used to create the shadow map
  64782. */
  64783. ShadowGenerator.prototype.getTransformMatrix = function () {
  64784. var scene = this._scene;
  64785. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  64786. return this._transformMatrix;
  64787. }
  64788. this._currentRenderID = scene.getRenderId();
  64789. this._currentFaceIndexCache = this._currentFaceIndex;
  64790. var lightPosition = this._light.position;
  64791. if (this._light.computeTransformedInformation()) {
  64792. lightPosition = this._light.transformedPosition;
  64793. }
  64794. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  64795. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  64796. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  64797. }
  64798. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  64799. this._cachedPosition.copyFrom(lightPosition);
  64800. this._cachedDirection.copyFrom(this._lightDirection);
  64801. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  64802. var shadowMap = this.getShadowMap();
  64803. if (shadowMap) {
  64804. var renderList = shadowMap.renderList;
  64805. if (renderList) {
  64806. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  64807. }
  64808. }
  64809. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  64810. }
  64811. return this._transformMatrix;
  64812. };
  64813. /**
  64814. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  64815. * Cube and 2D textures for instance.
  64816. */
  64817. ShadowGenerator.prototype.recreateShadowMap = function () {
  64818. var shadowMap = this._shadowMap;
  64819. if (!shadowMap) {
  64820. return;
  64821. }
  64822. // Track render list.
  64823. var renderList = shadowMap.renderList;
  64824. // Clean up existing data.
  64825. this._disposeRTTandPostProcesses();
  64826. // Reinitializes.
  64827. this._initializeGenerator();
  64828. // Reaffect the filter to ensure a correct fallback if necessary.
  64829. this.filter = this.filter;
  64830. // Reaffect the filter.
  64831. this._applyFilterValues();
  64832. // Reaffect Render List.
  64833. this._shadowMap.renderList = renderList;
  64834. };
  64835. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  64836. if (this._shadowMap2) {
  64837. this._shadowMap2.dispose();
  64838. this._shadowMap2 = null;
  64839. }
  64840. if (this._boxBlurPostprocess) {
  64841. this._boxBlurPostprocess.dispose();
  64842. this._boxBlurPostprocess = null;
  64843. }
  64844. if (this._kernelBlurXPostprocess) {
  64845. this._kernelBlurXPostprocess.dispose();
  64846. this._kernelBlurXPostprocess = null;
  64847. }
  64848. if (this._kernelBlurYPostprocess) {
  64849. this._kernelBlurYPostprocess.dispose();
  64850. this._kernelBlurYPostprocess = null;
  64851. }
  64852. this._blurPostProcesses = [];
  64853. };
  64854. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  64855. if (this._shadowMap) {
  64856. this._shadowMap.dispose();
  64857. this._shadowMap = null;
  64858. }
  64859. this._disposeBlurPostProcesses();
  64860. };
  64861. /**
  64862. * Disposes the ShadowGenerator.
  64863. * Returns nothing.
  64864. */
  64865. ShadowGenerator.prototype.dispose = function () {
  64866. this._disposeRTTandPostProcesses();
  64867. if (this._light) {
  64868. this._light._shadowGenerator = null;
  64869. this._light._markMeshesAsLightDirty();
  64870. }
  64871. };
  64872. /**
  64873. * Serializes the shadow generator setup to a json object.
  64874. * @returns The serialized JSON object
  64875. */
  64876. ShadowGenerator.prototype.serialize = function () {
  64877. var serializationObject = {};
  64878. var shadowMap = this.getShadowMap();
  64879. if (!shadowMap) {
  64880. return serializationObject;
  64881. }
  64882. serializationObject.lightId = this._light.id;
  64883. serializationObject.mapSize = shadowMap.getRenderSize();
  64884. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  64885. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  64886. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  64887. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  64888. serializationObject.usePoissonSampling = this.usePoissonSampling;
  64889. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  64890. serializationObject.depthScale = this.depthScale;
  64891. serializationObject.darkness = this.getDarkness();
  64892. serializationObject.blurBoxOffset = this.blurBoxOffset;
  64893. serializationObject.blurKernel = this.blurKernel;
  64894. serializationObject.blurScale = this.blurScale;
  64895. serializationObject.useKernelBlur = this.useKernelBlur;
  64896. serializationObject.transparencyShadow = this._transparencyShadow;
  64897. serializationObject.bias = this.bias;
  64898. serializationObject.normalBias = this.normalBias;
  64899. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  64900. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  64901. serializationObject.filteringQuality = this.filteringQuality;
  64902. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  64903. serializationObject.renderList = [];
  64904. if (shadowMap.renderList) {
  64905. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  64906. var mesh = shadowMap.renderList[meshIndex];
  64907. serializationObject.renderList.push(mesh.id);
  64908. }
  64909. }
  64910. return serializationObject;
  64911. };
  64912. /**
  64913. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  64914. * @param parsedShadowGenerator The JSON object to parse
  64915. * @param scene The scene to create the shadow map for
  64916. * @returns The parsed shadow generator
  64917. */
  64918. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  64919. //casting to point light, as light is missing the position attr and typescript complains.
  64920. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  64921. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  64922. var shadowMap = shadowGenerator.getShadowMap();
  64923. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  64924. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  64925. meshes.forEach(function (mesh) {
  64926. if (!shadowMap) {
  64927. return;
  64928. }
  64929. if (!shadowMap.renderList) {
  64930. shadowMap.renderList = [];
  64931. }
  64932. shadowMap.renderList.push(mesh);
  64933. });
  64934. }
  64935. if (parsedShadowGenerator.usePoissonSampling) {
  64936. shadowGenerator.usePoissonSampling = true;
  64937. }
  64938. else if (parsedShadowGenerator.useExponentialShadowMap) {
  64939. shadowGenerator.useExponentialShadowMap = true;
  64940. }
  64941. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  64942. shadowGenerator.useBlurExponentialShadowMap = true;
  64943. }
  64944. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  64945. shadowGenerator.useCloseExponentialShadowMap = true;
  64946. }
  64947. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  64948. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  64949. }
  64950. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  64951. shadowGenerator.usePercentageCloserFiltering = true;
  64952. }
  64953. else if (parsedShadowGenerator.useContactHardeningShadow) {
  64954. shadowGenerator.useContactHardeningShadow = true;
  64955. }
  64956. if (parsedShadowGenerator.filteringQuality) {
  64957. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  64958. }
  64959. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  64960. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  64961. }
  64962. else if (parsedShadowGenerator.useVarianceShadowMap) {
  64963. shadowGenerator.useExponentialShadowMap = true;
  64964. }
  64965. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  64966. shadowGenerator.useBlurExponentialShadowMap = true;
  64967. }
  64968. if (parsedShadowGenerator.depthScale) {
  64969. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  64970. }
  64971. if (parsedShadowGenerator.blurScale) {
  64972. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  64973. }
  64974. if (parsedShadowGenerator.blurBoxOffset) {
  64975. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  64976. }
  64977. if (parsedShadowGenerator.useKernelBlur) {
  64978. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  64979. }
  64980. if (parsedShadowGenerator.blurKernel) {
  64981. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  64982. }
  64983. if (parsedShadowGenerator.bias !== undefined) {
  64984. shadowGenerator.bias = parsedShadowGenerator.bias;
  64985. }
  64986. if (parsedShadowGenerator.normalBias !== undefined) {
  64987. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  64988. }
  64989. if (parsedShadowGenerator.darkness) {
  64990. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  64991. }
  64992. if (parsedShadowGenerator.transparencyShadow) {
  64993. shadowGenerator.setTransparencyShadow(true);
  64994. }
  64995. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  64996. return shadowGenerator;
  64997. };
  64998. /**
  64999. * Shadow generator mode None: no filtering applied.
  65000. */
  65001. ShadowGenerator.FILTER_NONE = 0;
  65002. /**
  65003. * Shadow generator mode ESM: Exponential Shadow Mapping.
  65004. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65005. */
  65006. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  65007. /**
  65008. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  65009. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  65010. */
  65011. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  65012. /**
  65013. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  65014. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65015. */
  65016. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  65017. /**
  65018. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  65019. * edge artifacts on steep falloff.
  65020. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65021. */
  65022. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  65023. /**
  65024. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  65025. * edge artifacts on steep falloff.
  65026. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65027. */
  65028. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  65029. /**
  65030. * Shadow generator mode PCF: Percentage Closer Filtering
  65031. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65032. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  65033. */
  65034. ShadowGenerator.FILTER_PCF = 6;
  65035. /**
  65036. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  65037. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65038. * Contact Hardening
  65039. */
  65040. ShadowGenerator.FILTER_PCSS = 7;
  65041. /**
  65042. * Reserved for PCF and PCSS
  65043. * Highest Quality.
  65044. *
  65045. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  65046. *
  65047. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  65048. */
  65049. ShadowGenerator.QUALITY_HIGH = 0;
  65050. /**
  65051. * Reserved for PCF and PCSS
  65052. * Good tradeoff for quality/perf cross devices
  65053. *
  65054. * Execute PCF on a 3*3 kernel.
  65055. *
  65056. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  65057. */
  65058. ShadowGenerator.QUALITY_MEDIUM = 1;
  65059. /**
  65060. * Reserved for PCF and PCSS
  65061. * The lowest quality but the fastest.
  65062. *
  65063. * Execute PCF on a 1*1 kernel.
  65064. *
  65065. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  65066. */
  65067. ShadowGenerator.QUALITY_LOW = 2;
  65068. return ShadowGenerator;
  65069. }());
  65070. BABYLON.ShadowGenerator = ShadowGenerator;
  65071. })(BABYLON || (BABYLON = {}));
  65072. //# sourceMappingURL=babylon.shadowGenerator.js.map
  65073. "use strict";
  65074. var BABYLON;
  65075. (function (BABYLON) {
  65076. var DefaultLoadingScreen = /** @class */ (function () {
  65077. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  65078. if (_loadingText === void 0) { _loadingText = ""; }
  65079. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  65080. var _this = this;
  65081. this._renderingCanvas = _renderingCanvas;
  65082. this._loadingText = _loadingText;
  65083. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  65084. // Resize
  65085. this._resizeLoadingUI = function () {
  65086. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  65087. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  65088. if (!_this._loadingDiv) {
  65089. return;
  65090. }
  65091. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  65092. _this._loadingDiv.style.left = canvasRect.left + "px";
  65093. _this._loadingDiv.style.top = canvasRect.top + "px";
  65094. _this._loadingDiv.style.width = canvasRect.width + "px";
  65095. _this._loadingDiv.style.height = canvasRect.height + "px";
  65096. };
  65097. }
  65098. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  65099. if (this._loadingDiv) {
  65100. // Do not add a loading screen if there is already one
  65101. return;
  65102. }
  65103. this._loadingDiv = document.createElement("div");
  65104. this._loadingDiv.id = "babylonjsLoadingDiv";
  65105. this._loadingDiv.style.opacity = "0";
  65106. this._loadingDiv.style.transition = "opacity 1.5s ease";
  65107. this._loadingDiv.style.pointerEvents = "none";
  65108. // Loading text
  65109. this._loadingTextDiv = document.createElement("div");
  65110. this._loadingTextDiv.style.position = "absolute";
  65111. this._loadingTextDiv.style.left = "0";
  65112. this._loadingTextDiv.style.top = "50%";
  65113. this._loadingTextDiv.style.marginTop = "80px";
  65114. this._loadingTextDiv.style.width = "100%";
  65115. this._loadingTextDiv.style.height = "20px";
  65116. this._loadingTextDiv.style.fontFamily = "Arial";
  65117. this._loadingTextDiv.style.fontSize = "14px";
  65118. this._loadingTextDiv.style.color = "white";
  65119. this._loadingTextDiv.style.textAlign = "center";
  65120. this._loadingTextDiv.innerHTML = "Loading";
  65121. this._loadingDiv.appendChild(this._loadingTextDiv);
  65122. //set the predefined text
  65123. this._loadingTextDiv.innerHTML = this._loadingText;
  65124. // Generating keyframes
  65125. var style = document.createElement('style');
  65126. style.type = 'text/css';
  65127. 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 }";
  65128. style.innerHTML = keyFrames;
  65129. document.getElementsByTagName('head')[0].appendChild(style);
  65130. // Loading img
  65131. var imgBack = new Image();
  65132. 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";
  65133. imgBack.style.position = "absolute";
  65134. imgBack.style.left = "50%";
  65135. imgBack.style.top = "50%";
  65136. imgBack.style.marginLeft = "-60px";
  65137. imgBack.style.marginTop = "-60px";
  65138. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  65139. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  65140. imgBack.style.transformOrigin = "50% 50%";
  65141. imgBack.style.webkitTransformOrigin = "50% 50%";
  65142. this._loadingDiv.appendChild(imgBack);
  65143. this._resizeLoadingUI();
  65144. window.addEventListener("resize", this._resizeLoadingUI);
  65145. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65146. document.body.appendChild(this._loadingDiv);
  65147. this._loadingDiv.style.opacity = "1";
  65148. };
  65149. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  65150. var _this = this;
  65151. if (!this._loadingDiv) {
  65152. return;
  65153. }
  65154. var onTransitionEnd = function () {
  65155. if (!_this._loadingDiv) {
  65156. return;
  65157. }
  65158. document.body.removeChild(_this._loadingDiv);
  65159. window.removeEventListener("resize", _this._resizeLoadingUI);
  65160. _this._loadingDiv = null;
  65161. };
  65162. this._loadingDiv.style.opacity = "0";
  65163. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  65164. };
  65165. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  65166. set: function (text) {
  65167. this._loadingText = text;
  65168. if (this._loadingTextDiv) {
  65169. this._loadingTextDiv.innerHTML = this._loadingText;
  65170. }
  65171. },
  65172. enumerable: true,
  65173. configurable: true
  65174. });
  65175. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  65176. get: function () {
  65177. return this._loadingDivBackgroundColor;
  65178. },
  65179. set: function (color) {
  65180. this._loadingDivBackgroundColor = color;
  65181. if (!this._loadingDiv) {
  65182. return;
  65183. }
  65184. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  65185. },
  65186. enumerable: true,
  65187. configurable: true
  65188. });
  65189. return DefaultLoadingScreen;
  65190. }());
  65191. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  65192. })(BABYLON || (BABYLON = {}));
  65193. //# sourceMappingURL=babylon.loadingScreen.js.map
  65194. "use strict";
  65195. var BABYLON;
  65196. (function (BABYLON) {
  65197. var SceneLoaderProgressEvent = /** @class */ (function () {
  65198. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  65199. this.lengthComputable = lengthComputable;
  65200. this.loaded = loaded;
  65201. this.total = total;
  65202. }
  65203. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  65204. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  65205. };
  65206. return SceneLoaderProgressEvent;
  65207. }());
  65208. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  65209. var SceneLoader = /** @class */ (function () {
  65210. function SceneLoader() {
  65211. }
  65212. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  65213. get: function () {
  65214. return 0;
  65215. },
  65216. enumerable: true,
  65217. configurable: true
  65218. });
  65219. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  65220. get: function () {
  65221. return 1;
  65222. },
  65223. enumerable: true,
  65224. configurable: true
  65225. });
  65226. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  65227. get: function () {
  65228. return 2;
  65229. },
  65230. enumerable: true,
  65231. configurable: true
  65232. });
  65233. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  65234. get: function () {
  65235. return 3;
  65236. },
  65237. enumerable: true,
  65238. configurable: true
  65239. });
  65240. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  65241. get: function () {
  65242. return SceneLoader._ForceFullSceneLoadingForIncremental;
  65243. },
  65244. set: function (value) {
  65245. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  65246. },
  65247. enumerable: true,
  65248. configurable: true
  65249. });
  65250. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  65251. get: function () {
  65252. return SceneLoader._ShowLoadingScreen;
  65253. },
  65254. set: function (value) {
  65255. SceneLoader._ShowLoadingScreen = value;
  65256. },
  65257. enumerable: true,
  65258. configurable: true
  65259. });
  65260. Object.defineProperty(SceneLoader, "loggingLevel", {
  65261. get: function () {
  65262. return SceneLoader._loggingLevel;
  65263. },
  65264. set: function (value) {
  65265. SceneLoader._loggingLevel = value;
  65266. },
  65267. enumerable: true,
  65268. configurable: true
  65269. });
  65270. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  65271. get: function () {
  65272. return SceneLoader._CleanBoneMatrixWeights;
  65273. },
  65274. set: function (value) {
  65275. SceneLoader._CleanBoneMatrixWeights = value;
  65276. },
  65277. enumerable: true,
  65278. configurable: true
  65279. });
  65280. SceneLoader._getDefaultPlugin = function () {
  65281. return SceneLoader._registeredPlugins[".babylon"];
  65282. };
  65283. SceneLoader._getPluginForExtension = function (extension) {
  65284. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  65285. if (registeredPlugin) {
  65286. return registeredPlugin;
  65287. }
  65288. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  65289. return SceneLoader._getDefaultPlugin();
  65290. };
  65291. SceneLoader._getPluginForDirectLoad = function (data) {
  65292. for (var extension in SceneLoader._registeredPlugins) {
  65293. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  65294. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  65295. return SceneLoader._registeredPlugins[extension];
  65296. }
  65297. }
  65298. return SceneLoader._getDefaultPlugin();
  65299. };
  65300. SceneLoader._getPluginForFilename = function (sceneFilename) {
  65301. if (sceneFilename.name) {
  65302. sceneFilename = sceneFilename.name;
  65303. }
  65304. var queryStringPosition = sceneFilename.indexOf("?");
  65305. if (queryStringPosition !== -1) {
  65306. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  65307. }
  65308. var dotPosition = sceneFilename.lastIndexOf(".");
  65309. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  65310. return SceneLoader._getPluginForExtension(extension);
  65311. };
  65312. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  65313. SceneLoader._getDirectLoad = function (sceneFilename) {
  65314. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  65315. return sceneFilename.substr(5);
  65316. }
  65317. return null;
  65318. };
  65319. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  65320. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  65321. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  65322. var plugin;
  65323. if (registeredPlugin.plugin.createPlugin) {
  65324. plugin = registeredPlugin.plugin.createPlugin();
  65325. }
  65326. else {
  65327. plugin = registeredPlugin.plugin;
  65328. }
  65329. var useArrayBuffer = registeredPlugin.isBinary;
  65330. var database;
  65331. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  65332. var dataCallback = function (data, responseURL) {
  65333. if (scene.isDisposed) {
  65334. onError("Scene has been disposed");
  65335. return;
  65336. }
  65337. scene.database = database;
  65338. onSuccess(plugin, data, responseURL);
  65339. };
  65340. var request = null;
  65341. var pluginDisposed = false;
  65342. var onDisposeObservable = plugin.onDisposeObservable;
  65343. if (onDisposeObservable) {
  65344. onDisposeObservable.add(function () {
  65345. pluginDisposed = true;
  65346. if (request) {
  65347. request.abort();
  65348. request = null;
  65349. }
  65350. onDispose();
  65351. });
  65352. }
  65353. var manifestChecked = function () {
  65354. if (pluginDisposed) {
  65355. return;
  65356. }
  65357. var url = rootUrl + sceneFilename;
  65358. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  65359. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  65360. } : undefined, database, useArrayBuffer, function (request, exception) {
  65361. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  65362. });
  65363. };
  65364. if (directLoad) {
  65365. dataCallback(directLoad);
  65366. return plugin;
  65367. }
  65368. if (rootUrl.indexOf("file:") === -1) {
  65369. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  65370. if (canUseOfflineSupport) {
  65371. // Also check for exceptions
  65372. var exceptionFound = false;
  65373. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  65374. var regex = _a[_i];
  65375. if (regex.test(rootUrl + sceneFilename)) {
  65376. exceptionFound = true;
  65377. break;
  65378. }
  65379. }
  65380. canUseOfflineSupport = !exceptionFound;
  65381. }
  65382. if (canUseOfflineSupport) {
  65383. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  65384. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  65385. }
  65386. else {
  65387. manifestChecked();
  65388. }
  65389. }
  65390. else {
  65391. var fileOrString = sceneFilename;
  65392. if (fileOrString.name) {
  65393. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  65394. }
  65395. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  65396. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  65397. }
  65398. else {
  65399. onError("Unable to find file named " + sceneFilename);
  65400. }
  65401. }
  65402. return plugin;
  65403. };
  65404. // Public functions
  65405. SceneLoader.GetPluginForExtension = function (extension) {
  65406. return SceneLoader._getPluginForExtension(extension).plugin;
  65407. };
  65408. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  65409. return !!SceneLoader._registeredPlugins[extension];
  65410. };
  65411. SceneLoader.RegisterPlugin = function (plugin) {
  65412. if (typeof plugin.extensions === "string") {
  65413. var extension = plugin.extensions;
  65414. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65415. plugin: plugin,
  65416. isBinary: false
  65417. };
  65418. }
  65419. else {
  65420. var extensions = plugin.extensions;
  65421. Object.keys(extensions).forEach(function (extension) {
  65422. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  65423. plugin: plugin,
  65424. isBinary: extensions[extension].isBinary
  65425. };
  65426. });
  65427. }
  65428. };
  65429. /**
  65430. * Import meshes into a scene
  65431. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65432. * @param rootUrl a string that defines the root url for scene and resources
  65433. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65434. * @param scene the instance of BABYLON.Scene to append to
  65435. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  65436. * @param onProgress a callback with a progress event for each file being loaded
  65437. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65438. * @param pluginExtension the extension used to determine the plugin
  65439. * @returns The loaded plugin
  65440. */
  65441. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65442. if (onSuccess === void 0) { onSuccess = null; }
  65443. if (onProgress === void 0) { onProgress = null; }
  65444. if (onError === void 0) { onError = null; }
  65445. if (pluginExtension === void 0) { pluginExtension = null; }
  65446. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65447. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65448. return null;
  65449. }
  65450. var loadingToken = {};
  65451. scene._addPendingData(loadingToken);
  65452. var disposeHandler = function () {
  65453. scene._removePendingData(loadingToken);
  65454. };
  65455. var errorHandler = function (message, exception) {
  65456. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  65457. if (onError) {
  65458. onError(scene, errorMessage, exception);
  65459. }
  65460. else {
  65461. BABYLON.Tools.Error(errorMessage);
  65462. // should the exception be thrown?
  65463. }
  65464. disposeHandler();
  65465. };
  65466. var progressHandler = onProgress ? function (event) {
  65467. try {
  65468. onProgress(event);
  65469. }
  65470. catch (e) {
  65471. errorHandler("Error in onProgress callback", e);
  65472. }
  65473. } : undefined;
  65474. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  65475. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  65476. if (onSuccess) {
  65477. try {
  65478. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  65479. }
  65480. catch (e) {
  65481. errorHandler("Error in onSuccess callback", e);
  65482. }
  65483. }
  65484. scene._removePendingData(loadingToken);
  65485. };
  65486. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65487. if (plugin.rewriteRootURL) {
  65488. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  65489. }
  65490. if (sceneFilename === "") {
  65491. if (sceneFilename === "") {
  65492. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65493. }
  65494. }
  65495. if (plugin.importMesh) {
  65496. var syncedPlugin = plugin;
  65497. var meshes = new Array();
  65498. var particleSystems = new Array();
  65499. var skeletons = new Array();
  65500. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  65501. return;
  65502. }
  65503. scene.loadingPluginName = plugin.name;
  65504. successHandler(meshes, particleSystems, skeletons, []);
  65505. }
  65506. else {
  65507. var asyncedPlugin = plugin;
  65508. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  65509. scene.loadingPluginName = plugin.name;
  65510. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  65511. }).catch(function (error) {
  65512. errorHandler(error.message, error);
  65513. });
  65514. }
  65515. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65516. };
  65517. /**
  65518. * Import meshes into a scene
  65519. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  65520. * @param rootUrl a string that defines the root url for scene and resources
  65521. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65522. * @param scene the instance of BABYLON.Scene to append to
  65523. * @param onProgress a callback with a progress event for each file being loaded
  65524. * @param pluginExtension the extension used to determine the plugin
  65525. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  65526. */
  65527. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65528. if (onProgress === void 0) { onProgress = null; }
  65529. if (pluginExtension === void 0) { pluginExtension = null; }
  65530. return new Promise(function (resolve, reject) {
  65531. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  65532. resolve({
  65533. meshes: meshes,
  65534. particleSystems: particleSystems,
  65535. skeletons: skeletons,
  65536. animationGroups: animationGroups
  65537. });
  65538. }, onProgress, function (scene, message, exception) {
  65539. reject(exception || new Error(message));
  65540. });
  65541. });
  65542. };
  65543. /**
  65544. * Load a scene
  65545. * @param rootUrl a string that defines the root url for scene and resources
  65546. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65547. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65548. * @param onSuccess a callback with the scene when import succeeds
  65549. * @param onProgress a callback with a progress event for each file being loaded
  65550. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65551. * @param pluginExtension the extension used to determine the plugin
  65552. * @returns The loaded plugin
  65553. */
  65554. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  65555. if (onSuccess === void 0) { onSuccess = null; }
  65556. if (onProgress === void 0) { onProgress = null; }
  65557. if (onError === void 0) { onError = null; }
  65558. if (pluginExtension === void 0) { pluginExtension = null; }
  65559. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  65560. };
  65561. /**
  65562. * Load a scene
  65563. * @param rootUrl a string that defines the root url for scene and resources
  65564. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65565. * @param engine is the instance of BABYLON.Engine to use to create the scene
  65566. * @param onProgress a callback with a progress event for each file being loaded
  65567. * @param pluginExtension the extension used to determine the plugin
  65568. * @returns The loaded scene
  65569. */
  65570. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  65571. if (onProgress === void 0) { onProgress = null; }
  65572. if (pluginExtension === void 0) { pluginExtension = null; }
  65573. return new Promise(function (resolve, reject) {
  65574. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  65575. resolve(scene);
  65576. }, onProgress, function (scene, message, exception) {
  65577. reject(exception || new Error(message));
  65578. }, pluginExtension);
  65579. });
  65580. };
  65581. /**
  65582. * Append a scene
  65583. * @param rootUrl a string that defines the root url for scene and resources
  65584. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65585. * @param scene is the instance of BABYLON.Scene to append to
  65586. * @param onSuccess a callback with the scene when import succeeds
  65587. * @param onProgress a callback with a progress event for each file being loaded
  65588. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65589. * @param pluginExtension the extension used to determine the plugin
  65590. * @returns The loaded plugin
  65591. */
  65592. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65593. if (onSuccess === void 0) { onSuccess = null; }
  65594. if (onProgress === void 0) { onProgress = null; }
  65595. if (onError === void 0) { onError = null; }
  65596. if (pluginExtension === void 0) { pluginExtension = null; }
  65597. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65598. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65599. return null;
  65600. }
  65601. if (SceneLoader.ShowLoadingScreen) {
  65602. scene.getEngine().displayLoadingUI();
  65603. }
  65604. var loadingToken = {};
  65605. scene._addPendingData(loadingToken);
  65606. var disposeHandler = function () {
  65607. scene._removePendingData(loadingToken);
  65608. scene.getEngine().hideLoadingUI();
  65609. };
  65610. var errorHandler = function (message, exception) {
  65611. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65612. if (onError) {
  65613. onError(scene, errorMessage, exception);
  65614. }
  65615. else {
  65616. BABYLON.Tools.Error(errorMessage);
  65617. // should the exception be thrown?
  65618. }
  65619. disposeHandler();
  65620. };
  65621. var progressHandler = onProgress ? function (event) {
  65622. try {
  65623. onProgress(event);
  65624. }
  65625. catch (e) {
  65626. errorHandler("Error in onProgress callback", e);
  65627. }
  65628. } : undefined;
  65629. var successHandler = function () {
  65630. if (onSuccess) {
  65631. try {
  65632. onSuccess(scene);
  65633. }
  65634. catch (e) {
  65635. errorHandler("Error in onSuccess callback", e);
  65636. }
  65637. }
  65638. scene._removePendingData(loadingToken);
  65639. };
  65640. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65641. if (sceneFilename === "") {
  65642. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  65643. }
  65644. if (plugin.load) {
  65645. var syncedPlugin = plugin;
  65646. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  65647. return;
  65648. }
  65649. scene.loadingPluginName = plugin.name;
  65650. successHandler();
  65651. }
  65652. else {
  65653. var asyncedPlugin = plugin;
  65654. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  65655. scene.loadingPluginName = plugin.name;
  65656. successHandler();
  65657. }).catch(function (error) {
  65658. errorHandler(error.message, error);
  65659. });
  65660. }
  65661. if (SceneLoader.ShowLoadingScreen) {
  65662. scene.executeWhenReady(function () {
  65663. scene.getEngine().hideLoadingUI();
  65664. });
  65665. }
  65666. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65667. };
  65668. /**
  65669. * Append a scene
  65670. * @param rootUrl a string that defines the root url for scene and resources
  65671. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65672. * @param scene is the instance of BABYLON.Scene to append to
  65673. * @param onProgress a callback with a progress event for each file being loaded
  65674. * @param pluginExtension the extension used to determine the plugin
  65675. * @returns The given scene
  65676. */
  65677. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65678. if (onProgress === void 0) { onProgress = null; }
  65679. if (pluginExtension === void 0) { pluginExtension = null; }
  65680. return new Promise(function (resolve, reject) {
  65681. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  65682. resolve(scene);
  65683. }, onProgress, function (scene, message, exception) {
  65684. reject(exception || new Error(message));
  65685. }, pluginExtension);
  65686. });
  65687. };
  65688. /**
  65689. * Load a scene into an asset container
  65690. * @param rootUrl a string that defines the root url for scene and resources
  65691. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65692. * @param scene is the instance of BABYLON.Scene to append to
  65693. * @param onSuccess a callback with the scene when import succeeds
  65694. * @param onProgress a callback with a progress event for each file being loaded
  65695. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  65696. * @param pluginExtension the extension used to determine the plugin
  65697. * @returns The loaded plugin
  65698. */
  65699. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  65700. if (onSuccess === void 0) { onSuccess = null; }
  65701. if (onProgress === void 0) { onProgress = null; }
  65702. if (onError === void 0) { onError = null; }
  65703. if (pluginExtension === void 0) { pluginExtension = null; }
  65704. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  65705. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  65706. return null;
  65707. }
  65708. var loadingToken = {};
  65709. scene._addPendingData(loadingToken);
  65710. var disposeHandler = function () {
  65711. scene._removePendingData(loadingToken);
  65712. };
  65713. var errorHandler = function (message, exception) {
  65714. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  65715. if (onError) {
  65716. onError(scene, errorMessage, exception);
  65717. }
  65718. else {
  65719. BABYLON.Tools.Error(errorMessage);
  65720. // should the exception be thrown?
  65721. }
  65722. disposeHandler();
  65723. };
  65724. var progressHandler = onProgress ? function (event) {
  65725. try {
  65726. onProgress(event);
  65727. }
  65728. catch (e) {
  65729. errorHandler("Error in onProgress callback", e);
  65730. }
  65731. } : undefined;
  65732. var successHandler = function (assets) {
  65733. if (onSuccess) {
  65734. try {
  65735. onSuccess(assets);
  65736. }
  65737. catch (e) {
  65738. errorHandler("Error in onSuccess callback", e);
  65739. }
  65740. }
  65741. scene._removePendingData(loadingToken);
  65742. };
  65743. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  65744. if (plugin.loadAssetContainer) {
  65745. var syncedPlugin = plugin;
  65746. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  65747. if (!assetContainer) {
  65748. return;
  65749. }
  65750. scene.loadingPluginName = plugin.name;
  65751. successHandler(assetContainer);
  65752. }
  65753. else if (plugin.loadAssetContainerAsync) {
  65754. var asyncedPlugin = plugin;
  65755. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  65756. scene.loadingPluginName = plugin.name;
  65757. successHandler(assetContainer);
  65758. }).catch(function (error) {
  65759. errorHandler(error.message, error);
  65760. });
  65761. }
  65762. else {
  65763. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  65764. }
  65765. if (SceneLoader.ShowLoadingScreen) {
  65766. scene.executeWhenReady(function () {
  65767. scene.getEngine().hideLoadingUI();
  65768. });
  65769. }
  65770. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  65771. };
  65772. /**
  65773. * Load a scene into an asset container
  65774. * @param rootUrl a string that defines the root url for scene and resources
  65775. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  65776. * @param scene is the instance of BABYLON.Scene to append to
  65777. * @param onProgress a callback with a progress event for each file being loaded
  65778. * @param pluginExtension the extension used to determine the plugin
  65779. * @returns The loaded asset container
  65780. */
  65781. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  65782. if (onProgress === void 0) { onProgress = null; }
  65783. if (pluginExtension === void 0) { pluginExtension = null; }
  65784. return new Promise(function (resolve, reject) {
  65785. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  65786. resolve(assetContainer);
  65787. }, onProgress, function (scene, message, exception) {
  65788. reject(exception || new Error(message));
  65789. }, pluginExtension);
  65790. });
  65791. };
  65792. // Flags
  65793. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  65794. SceneLoader._ShowLoadingScreen = true;
  65795. SceneLoader._CleanBoneMatrixWeights = false;
  65796. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  65797. // Members
  65798. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  65799. SceneLoader._registeredPlugins = {};
  65800. return SceneLoader;
  65801. }());
  65802. BABYLON.SceneLoader = SceneLoader;
  65803. ;
  65804. })(BABYLON || (BABYLON = {}));
  65805. //# sourceMappingURL=babylon.sceneLoader.js.map
  65806. "use strict";
  65807. var BABYLON;
  65808. (function (BABYLON) {
  65809. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  65810. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  65811. var parsedMaterial = parsedData.materials[index];
  65812. if (parsedMaterial.id === id) {
  65813. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  65814. }
  65815. }
  65816. return null;
  65817. };
  65818. var isDescendantOf = function (mesh, names, hierarchyIds) {
  65819. for (var i in names) {
  65820. if (mesh.name === names[i]) {
  65821. hierarchyIds.push(mesh.id);
  65822. return true;
  65823. }
  65824. }
  65825. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  65826. hierarchyIds.push(mesh.id);
  65827. return true;
  65828. }
  65829. return false;
  65830. };
  65831. var logOperation = function (operation, producer) {
  65832. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  65833. };
  65834. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  65835. if (addToScene === void 0) { addToScene = false; }
  65836. var container = new BABYLON.AssetContainer(scene);
  65837. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  65838. // when SceneLoader.debugLogging = true (default), or exception encountered.
  65839. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  65840. // and avoid problems with multiple concurrent .babylon loads.
  65841. var log = "importScene has failed JSON parse";
  65842. try {
  65843. var parsedData = JSON.parse(data);
  65844. log = "";
  65845. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  65846. var index;
  65847. var cache;
  65848. // Lights
  65849. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  65850. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  65851. var parsedLight = parsedData.lights[index];
  65852. var light = BABYLON.Light.Parse(parsedLight, scene);
  65853. if (light) {
  65854. container.lights.push(light);
  65855. log += (index === 0 ? "\n\tLights:" : "");
  65856. log += "\n\t\t" + light.toString(fullDetails);
  65857. }
  65858. }
  65859. }
  65860. // Animations
  65861. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  65862. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  65863. var parsedAnimation = parsedData.animations[index];
  65864. var animation = BABYLON.Animation.Parse(parsedAnimation);
  65865. scene.animations.push(animation);
  65866. container.animations.push(animation);
  65867. log += (index === 0 ? "\n\tAnimations:" : "");
  65868. log += "\n\t\t" + animation.toString(fullDetails);
  65869. }
  65870. }
  65871. // Materials
  65872. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  65873. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  65874. var parsedMaterial = parsedData.materials[index];
  65875. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  65876. container.materials.push(mat);
  65877. log += (index === 0 ? "\n\tMaterials:" : "");
  65878. log += "\n\t\t" + mat.toString(fullDetails);
  65879. }
  65880. }
  65881. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  65882. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  65883. var parsedMultiMaterial = parsedData.multiMaterials[index];
  65884. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  65885. container.multiMaterials.push(mmat);
  65886. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  65887. log += "\n\t\t" + mmat.toString(fullDetails);
  65888. }
  65889. }
  65890. // Morph targets
  65891. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  65892. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  65893. var managerData = _a[_i];
  65894. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  65895. }
  65896. }
  65897. // Skeletons
  65898. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  65899. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  65900. var parsedSkeleton = parsedData.skeletons[index];
  65901. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  65902. container.skeletons.push(skeleton);
  65903. log += (index === 0 ? "\n\tSkeletons:" : "");
  65904. log += "\n\t\t" + skeleton.toString(fullDetails);
  65905. }
  65906. }
  65907. // Geometries
  65908. var geometries = parsedData.geometries;
  65909. if (geometries !== undefined && geometries !== null) {
  65910. var addedGeometry = new Array();
  65911. // Boxes
  65912. var boxes = geometries.boxes;
  65913. if (boxes !== undefined && boxes !== null) {
  65914. for (index = 0, cache = boxes.length; index < cache; index++) {
  65915. var parsedBox = boxes[index];
  65916. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  65917. }
  65918. }
  65919. // Spheres
  65920. var spheres = geometries.spheres;
  65921. if (spheres !== undefined && spheres !== null) {
  65922. for (index = 0, cache = spheres.length; index < cache; index++) {
  65923. var parsedSphere = spheres[index];
  65924. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  65925. }
  65926. }
  65927. // Cylinders
  65928. var cylinders = geometries.cylinders;
  65929. if (cylinders !== undefined && cylinders !== null) {
  65930. for (index = 0, cache = cylinders.length; index < cache; index++) {
  65931. var parsedCylinder = cylinders[index];
  65932. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  65933. }
  65934. }
  65935. // Toruses
  65936. var toruses = geometries.toruses;
  65937. if (toruses !== undefined && toruses !== null) {
  65938. for (index = 0, cache = toruses.length; index < cache; index++) {
  65939. var parsedTorus = toruses[index];
  65940. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  65941. }
  65942. }
  65943. // Grounds
  65944. var grounds = geometries.grounds;
  65945. if (grounds !== undefined && grounds !== null) {
  65946. for (index = 0, cache = grounds.length; index < cache; index++) {
  65947. var parsedGround = grounds[index];
  65948. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  65949. }
  65950. }
  65951. // Planes
  65952. var planes = geometries.planes;
  65953. if (planes !== undefined && planes !== null) {
  65954. for (index = 0, cache = planes.length; index < cache; index++) {
  65955. var parsedPlane = planes[index];
  65956. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  65957. }
  65958. }
  65959. // TorusKnots
  65960. var torusKnots = geometries.torusKnots;
  65961. if (torusKnots !== undefined && torusKnots !== null) {
  65962. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  65963. var parsedTorusKnot = torusKnots[index];
  65964. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  65965. }
  65966. }
  65967. // VertexData
  65968. var vertexData = geometries.vertexData;
  65969. if (vertexData !== undefined && vertexData !== null) {
  65970. for (index = 0, cache = vertexData.length; index < cache; index++) {
  65971. var parsedVertexData = vertexData[index];
  65972. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  65973. }
  65974. }
  65975. addedGeometry.forEach(function (g) {
  65976. if (g) {
  65977. container.geometries.push(g);
  65978. }
  65979. });
  65980. }
  65981. // Transform nodes
  65982. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  65983. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  65984. var parsedTransformNode = parsedData.transformNodes[index];
  65985. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  65986. container.transformNodes.push(node);
  65987. }
  65988. }
  65989. // Meshes
  65990. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  65991. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  65992. var parsedMesh = parsedData.meshes[index];
  65993. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  65994. container.meshes.push(mesh);
  65995. log += (index === 0 ? "\n\tMeshes:" : "");
  65996. log += "\n\t\t" + mesh.toString(fullDetails);
  65997. }
  65998. }
  65999. // Cameras
  66000. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  66001. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  66002. var parsedCamera = parsedData.cameras[index];
  66003. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  66004. container.cameras.push(camera);
  66005. log += (index === 0 ? "\n\tCameras:" : "");
  66006. log += "\n\t\t" + camera.toString(fullDetails);
  66007. }
  66008. }
  66009. // Browsing all the graph to connect the dots
  66010. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  66011. var camera = scene.cameras[index];
  66012. if (camera._waitingParentId) {
  66013. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  66014. camera._waitingParentId = null;
  66015. }
  66016. }
  66017. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66018. var light_1 = scene.lights[index];
  66019. if (light_1 && light_1._waitingParentId) {
  66020. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  66021. light_1._waitingParentId = null;
  66022. }
  66023. }
  66024. // Sounds
  66025. // TODO: add sound
  66026. var loadedSounds = [];
  66027. var loadedSound;
  66028. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66029. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66030. var parsedSound = parsedData.sounds[index];
  66031. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66032. if (!parsedSound.url)
  66033. parsedSound.url = parsedSound.name;
  66034. if (!loadedSounds[parsedSound.url]) {
  66035. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66036. loadedSounds[parsedSound.url] = loadedSound;
  66037. container.sounds.push(loadedSound);
  66038. }
  66039. else {
  66040. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66041. }
  66042. }
  66043. else {
  66044. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66045. }
  66046. }
  66047. }
  66048. loadedSounds = [];
  66049. // Connect parents & children and parse actions
  66050. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  66051. var transformNode = scene.transformNodes[index];
  66052. if (transformNode._waitingParentId) {
  66053. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  66054. transformNode._waitingParentId = null;
  66055. }
  66056. }
  66057. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66058. var mesh = scene.meshes[index];
  66059. if (mesh._waitingParentId) {
  66060. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  66061. mesh._waitingParentId = null;
  66062. }
  66063. if (mesh._waitingActions) {
  66064. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  66065. mesh._waitingActions = null;
  66066. }
  66067. }
  66068. // freeze world matrix application
  66069. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66070. var currentMesh = scene.meshes[index];
  66071. if (currentMesh._waitingFreezeWorldMatrix) {
  66072. currentMesh.freezeWorldMatrix();
  66073. currentMesh._waitingFreezeWorldMatrix = null;
  66074. }
  66075. else {
  66076. currentMesh.computeWorldMatrix(true);
  66077. }
  66078. }
  66079. // Particles Systems
  66080. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66081. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66082. var parsedParticleSystem = parsedData.particleSystems[index];
  66083. if (parsedParticleSystem.activeParticleCount) {
  66084. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66085. container.particleSystems.push(ps);
  66086. }
  66087. else {
  66088. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  66089. container.particleSystems.push(ps);
  66090. }
  66091. }
  66092. }
  66093. // Lens flares
  66094. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  66095. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  66096. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  66097. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  66098. container.lensFlareSystems.push(lf);
  66099. }
  66100. }
  66101. // Shadows
  66102. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  66103. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  66104. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  66105. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  66106. container.shadowGenerators.push(sg);
  66107. }
  66108. }
  66109. // Lights exclusions / inclusions
  66110. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66111. var light_2 = scene.lights[index];
  66112. // Excluded check
  66113. if (light_2._excludedMeshesIds.length > 0) {
  66114. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  66115. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  66116. if (excludedMesh) {
  66117. light_2.excludedMeshes.push(excludedMesh);
  66118. }
  66119. }
  66120. light_2._excludedMeshesIds = [];
  66121. }
  66122. // Included check
  66123. if (light_2._includedOnlyMeshesIds.length > 0) {
  66124. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  66125. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  66126. if (includedOnlyMesh) {
  66127. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  66128. }
  66129. }
  66130. light_2._includedOnlyMeshesIds = [];
  66131. }
  66132. }
  66133. // Effect layers
  66134. if (parsedData.effectLayers) {
  66135. for (index = 0; index < parsedData.effectLayers.length; index++) {
  66136. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  66137. container.effectLayers.push(effectLayer);
  66138. }
  66139. }
  66140. // Actions (scene)
  66141. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  66142. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  66143. }
  66144. if (!addToScene) {
  66145. container.removeAllFromScene();
  66146. }
  66147. }
  66148. catch (err) {
  66149. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  66150. if (onError) {
  66151. onError(msg, err);
  66152. }
  66153. else {
  66154. BABYLON.Tools.Log(msg);
  66155. throw err;
  66156. }
  66157. }
  66158. finally {
  66159. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66160. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66161. }
  66162. }
  66163. return container;
  66164. };
  66165. BABYLON.SceneLoader.RegisterPlugin({
  66166. name: "babylon.js",
  66167. extensions: ".babylon",
  66168. canDirectLoad: function (data) {
  66169. if (data.indexOf("babylon") !== -1) {
  66170. return true;
  66171. }
  66172. return false;
  66173. },
  66174. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  66175. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66176. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66177. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66178. // and avoid problems with multiple concurrent .babylon loads.
  66179. var log = "importMesh has failed JSON parse";
  66180. try {
  66181. var parsedData = JSON.parse(data);
  66182. log = "";
  66183. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66184. if (!meshesNames) {
  66185. meshesNames = null;
  66186. }
  66187. else if (!Array.isArray(meshesNames)) {
  66188. meshesNames = [meshesNames];
  66189. }
  66190. var hierarchyIds = new Array();
  66191. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66192. var loadedSkeletonsIds = [];
  66193. var loadedMaterialsIds = [];
  66194. var index;
  66195. var cache;
  66196. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66197. var parsedMesh = parsedData.meshes[index];
  66198. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  66199. if (meshesNames !== null) {
  66200. // Remove found mesh name from list.
  66201. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  66202. }
  66203. //Geometry?
  66204. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  66205. //does the file contain geometries?
  66206. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  66207. //find the correct geometry and add it to the scene
  66208. var found = false;
  66209. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  66210. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  66211. return;
  66212. }
  66213. else {
  66214. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  66215. if (parsedGeometryData.id === parsedMesh.geometryId) {
  66216. switch (geometryType) {
  66217. case "boxes":
  66218. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  66219. break;
  66220. case "spheres":
  66221. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  66222. break;
  66223. case "cylinders":
  66224. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  66225. break;
  66226. case "toruses":
  66227. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  66228. break;
  66229. case "grounds":
  66230. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  66231. break;
  66232. case "planes":
  66233. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  66234. break;
  66235. case "torusKnots":
  66236. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  66237. break;
  66238. case "vertexData":
  66239. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  66240. break;
  66241. }
  66242. found = true;
  66243. }
  66244. });
  66245. }
  66246. });
  66247. if (found === false) {
  66248. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  66249. }
  66250. }
  66251. }
  66252. // Material ?
  66253. if (parsedMesh.materialId) {
  66254. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  66255. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66256. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  66257. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  66258. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  66259. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  66260. var subMatId = parsedMultiMaterial.materials[matIndex];
  66261. loadedMaterialsIds.push(subMatId);
  66262. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  66263. if (mat) {
  66264. log += "\n\tMaterial " + mat.toString(fullDetails);
  66265. }
  66266. }
  66267. loadedMaterialsIds.push(parsedMultiMaterial.id);
  66268. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66269. if (mmat) {
  66270. materialFound = true;
  66271. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  66272. }
  66273. break;
  66274. }
  66275. }
  66276. }
  66277. if (materialFound === false) {
  66278. loadedMaterialsIds.push(parsedMesh.materialId);
  66279. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  66280. if (!mat) {
  66281. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  66282. }
  66283. else {
  66284. log += "\n\tMaterial " + mat.toString(fullDetails);
  66285. }
  66286. }
  66287. }
  66288. // Skeleton ?
  66289. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66290. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  66291. if (skeletonAlreadyLoaded === false) {
  66292. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  66293. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  66294. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  66295. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66296. skeletons.push(skeleton);
  66297. loadedSkeletonsIds.push(parsedSkeleton.id);
  66298. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  66299. }
  66300. }
  66301. }
  66302. }
  66303. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66304. meshes.push(mesh);
  66305. log += "\n\tMesh " + mesh.toString(fullDetails);
  66306. }
  66307. }
  66308. // Connecting parents
  66309. var currentMesh;
  66310. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66311. currentMesh = scene.meshes[index];
  66312. if (currentMesh._waitingParentId) {
  66313. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  66314. currentMesh._waitingParentId = null;
  66315. }
  66316. }
  66317. // freeze and compute world matrix application
  66318. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  66319. currentMesh = scene.meshes[index];
  66320. if (currentMesh._waitingFreezeWorldMatrix) {
  66321. currentMesh.freezeWorldMatrix();
  66322. currentMesh._waitingFreezeWorldMatrix = null;
  66323. }
  66324. else {
  66325. currentMesh.computeWorldMatrix(true);
  66326. }
  66327. }
  66328. }
  66329. // Particles
  66330. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  66331. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  66332. var parsedParticleSystem = parsedData.particleSystems[index];
  66333. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  66334. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  66335. }
  66336. }
  66337. }
  66338. return true;
  66339. }
  66340. catch (err) {
  66341. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  66342. if (onError) {
  66343. onError(msg, err);
  66344. }
  66345. else {
  66346. BABYLON.Tools.Log(msg);
  66347. throw err;
  66348. }
  66349. }
  66350. finally {
  66351. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66352. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66353. }
  66354. }
  66355. return false;
  66356. },
  66357. load: function (scene, data, rootUrl, onError) {
  66358. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66359. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66360. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66361. // and avoid problems with multiple concurrent .babylon loads.
  66362. var log = "importScene has failed JSON parse";
  66363. try {
  66364. var parsedData = JSON.parse(data);
  66365. log = "";
  66366. // Scene
  66367. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  66368. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  66369. }
  66370. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  66371. scene.autoClear = parsedData.autoClear;
  66372. }
  66373. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  66374. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  66375. }
  66376. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  66377. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  66378. }
  66379. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  66380. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  66381. }
  66382. // Fog
  66383. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  66384. scene.fogMode = parsedData.fogMode;
  66385. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  66386. scene.fogStart = parsedData.fogStart;
  66387. scene.fogEnd = parsedData.fogEnd;
  66388. scene.fogDensity = parsedData.fogDensity;
  66389. log += "\tFog mode for scene: ";
  66390. switch (scene.fogMode) {
  66391. // getters not compiling, so using hardcoded
  66392. case 1:
  66393. log += "exp\n";
  66394. break;
  66395. case 2:
  66396. log += "exp2\n";
  66397. break;
  66398. case 3:
  66399. log += "linear\n";
  66400. break;
  66401. }
  66402. }
  66403. //Physics
  66404. if (parsedData.physicsEnabled) {
  66405. var physicsPlugin;
  66406. if (parsedData.physicsEngine === "cannon") {
  66407. physicsPlugin = new BABYLON.CannonJSPlugin();
  66408. }
  66409. else if (parsedData.physicsEngine === "oimo") {
  66410. physicsPlugin = new BABYLON.OimoJSPlugin();
  66411. }
  66412. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  66413. //else - default engine, which is currently oimo
  66414. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  66415. scene.enablePhysics(physicsGravity, physicsPlugin);
  66416. }
  66417. // Metadata
  66418. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  66419. scene.metadata = parsedData.metadata;
  66420. }
  66421. //collisions, if defined. otherwise, default is true
  66422. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  66423. scene.collisionsEnabled = parsedData.collisionsEnabled;
  66424. }
  66425. scene.workerCollisions = !!parsedData.workerCollisions;
  66426. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  66427. if (!container) {
  66428. return false;
  66429. }
  66430. if (parsedData.autoAnimate) {
  66431. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  66432. }
  66433. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  66434. scene.setActiveCameraByID(parsedData.activeCameraID);
  66435. }
  66436. // Environment texture
  66437. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  66438. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  66439. if (parsedData.createDefaultSkybox === true) {
  66440. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  66441. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  66442. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  66443. }
  66444. }
  66445. // Finish
  66446. return true;
  66447. }
  66448. catch (err) {
  66449. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  66450. if (onError) {
  66451. onError(msg, err);
  66452. }
  66453. else {
  66454. BABYLON.Tools.Log(msg);
  66455. throw err;
  66456. }
  66457. }
  66458. finally {
  66459. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  66460. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  66461. }
  66462. }
  66463. return false;
  66464. },
  66465. loadAssetContainer: function (scene, data, rootUrl, onError) {
  66466. var container = loadAssetContainer(scene, data, rootUrl, onError);
  66467. return container;
  66468. }
  66469. });
  66470. })(BABYLON || (BABYLON = {}));
  66471. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  66472. "use strict";
  66473. var BABYLON;
  66474. (function (BABYLON) {
  66475. var FilesInput = /** @class */ (function () {
  66476. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  66477. this.onProcessFileCallback = function () { return true; };
  66478. this._engine = engine;
  66479. this._currentScene = scene;
  66480. this._sceneLoadedCallback = sceneLoadedCallback;
  66481. this._progressCallback = progressCallback;
  66482. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  66483. this._textureLoadingCallback = textureLoadingCallback;
  66484. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  66485. this._onReloadCallback = onReloadCallback;
  66486. this._errorCallback = errorCallback;
  66487. }
  66488. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  66489. var _this = this;
  66490. if (elementToMonitor) {
  66491. this._elementToMonitor = elementToMonitor;
  66492. this._dragEnterHandler = function (e) { _this.drag(e); };
  66493. this._dragOverHandler = function (e) { _this.drag(e); };
  66494. this._dropHandler = function (e) { _this.drop(e); };
  66495. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  66496. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  66497. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  66498. }
  66499. };
  66500. FilesInput.prototype.dispose = function () {
  66501. if (!this._elementToMonitor) {
  66502. return;
  66503. }
  66504. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  66505. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  66506. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  66507. };
  66508. FilesInput.prototype.renderFunction = function () {
  66509. if (this._additionalRenderLoopLogicCallback) {
  66510. this._additionalRenderLoopLogicCallback();
  66511. }
  66512. if (this._currentScene) {
  66513. if (this._textureLoadingCallback) {
  66514. var remaining = this._currentScene.getWaitingItemsCount();
  66515. if (remaining > 0) {
  66516. this._textureLoadingCallback(remaining);
  66517. }
  66518. }
  66519. this._currentScene.render();
  66520. }
  66521. };
  66522. FilesInput.prototype.drag = function (e) {
  66523. e.stopPropagation();
  66524. e.preventDefault();
  66525. };
  66526. FilesInput.prototype.drop = function (eventDrop) {
  66527. eventDrop.stopPropagation();
  66528. eventDrop.preventDefault();
  66529. this.loadFiles(eventDrop);
  66530. };
  66531. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  66532. var _this = this;
  66533. var reader = folder.createReader();
  66534. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  66535. reader.readEntries(function (entries) {
  66536. remaining.count += entries.length;
  66537. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  66538. var entry = entries_1[_i];
  66539. if (entry.isFile) {
  66540. entry.file(function (file) {
  66541. file.correctName = relativePath + file.name;
  66542. files.push(file);
  66543. if (--remaining.count === 0) {
  66544. callback();
  66545. }
  66546. });
  66547. }
  66548. else if (entry.isDirectory) {
  66549. _this._traverseFolder(entry, files, remaining, callback);
  66550. }
  66551. }
  66552. if (--remaining.count) {
  66553. callback();
  66554. }
  66555. });
  66556. };
  66557. FilesInput.prototype._processFiles = function (files) {
  66558. for (var i = 0; i < files.length; i++) {
  66559. var name = files[i].correctName.toLowerCase();
  66560. var extension = name.split('.').pop();
  66561. if (!this.onProcessFileCallback(files[i], name, extension)) {
  66562. continue;
  66563. }
  66564. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  66565. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  66566. this._sceneFileToLoad = files[i];
  66567. }
  66568. else {
  66569. FilesInput.FilesToLoad[name] = files[i];
  66570. }
  66571. }
  66572. };
  66573. FilesInput.prototype.loadFiles = function (event) {
  66574. var _this = this;
  66575. if (this._startingProcessingFilesCallback)
  66576. this._startingProcessingFilesCallback();
  66577. // Handling data transfer via drag'n'drop
  66578. if (event && event.dataTransfer && event.dataTransfer.files) {
  66579. this._filesToLoad = event.dataTransfer.files;
  66580. }
  66581. // Handling files from input files
  66582. if (event && event.target && event.target.files) {
  66583. this._filesToLoad = event.target.files;
  66584. }
  66585. if (this._filesToLoad && this._filesToLoad.length > 0) {
  66586. var files_1 = new Array();
  66587. var folders = [];
  66588. var items = event.dataTransfer ? event.dataTransfer.items : null;
  66589. for (var i = 0; i < this._filesToLoad.length; i++) {
  66590. var fileToLoad = this._filesToLoad[i];
  66591. var name_1 = fileToLoad.name.toLowerCase();
  66592. var entry = void 0;
  66593. fileToLoad.correctName = name_1;
  66594. if (items) {
  66595. var item = items[i];
  66596. if (item.getAsEntry) {
  66597. entry = item.getAsEntry();
  66598. }
  66599. else if (item.webkitGetAsEntry) {
  66600. entry = item.webkitGetAsEntry();
  66601. }
  66602. }
  66603. if (!entry) {
  66604. files_1.push(fileToLoad);
  66605. }
  66606. else {
  66607. if (entry.isDirectory) {
  66608. folders.push(entry);
  66609. }
  66610. else {
  66611. files_1.push(fileToLoad);
  66612. }
  66613. }
  66614. }
  66615. if (folders.length === 0) {
  66616. this._processFiles(files_1);
  66617. this._processReload();
  66618. }
  66619. else {
  66620. var remaining = { count: folders.length };
  66621. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  66622. var folder = folders_1[_i];
  66623. this._traverseFolder(folder, files_1, remaining, function () {
  66624. _this._processFiles(files_1);
  66625. if (remaining.count === 0) {
  66626. _this._processReload();
  66627. }
  66628. });
  66629. }
  66630. }
  66631. }
  66632. };
  66633. FilesInput.prototype._processReload = function () {
  66634. if (this._onReloadCallback) {
  66635. this._onReloadCallback(this._sceneFileToLoad);
  66636. }
  66637. else {
  66638. this.reload();
  66639. }
  66640. };
  66641. FilesInput.prototype.reload = function () {
  66642. var _this = this;
  66643. // If a scene file has been provided
  66644. if (this._sceneFileToLoad) {
  66645. if (this._currentScene) {
  66646. if (BABYLON.Tools.errorsCount > 0) {
  66647. BABYLON.Tools.ClearLogCache();
  66648. }
  66649. this._engine.stopRenderLoop();
  66650. this._currentScene.dispose();
  66651. }
  66652. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  66653. if (_this._progressCallback) {
  66654. _this._progressCallback(progress);
  66655. }
  66656. }).then(function (scene) {
  66657. _this._currentScene = scene;
  66658. if (_this._sceneLoadedCallback) {
  66659. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  66660. }
  66661. // Wait for textures and shaders to be ready
  66662. _this._currentScene.executeWhenReady(function () {
  66663. _this._engine.runRenderLoop(function () {
  66664. _this.renderFunction();
  66665. });
  66666. });
  66667. }).catch(function (error) {
  66668. if (_this._errorCallback) {
  66669. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  66670. }
  66671. });
  66672. }
  66673. else {
  66674. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  66675. }
  66676. };
  66677. FilesInput.FilesToLoad = {};
  66678. return FilesInput;
  66679. }());
  66680. BABYLON.FilesInput = FilesInput;
  66681. })(BABYLON || (BABYLON = {}));
  66682. //# sourceMappingURL=babylon.filesInput.js.map
  66683. "use strict";
  66684. var BABYLON;
  66685. (function (BABYLON) {
  66686. /**
  66687. * This class implement a typical dictionary using a string as key and the generic type T as value.
  66688. * The underlying implementation relies on an associative array to ensure the best performances.
  66689. * The value can be anything including 'null' but except 'undefined'
  66690. */
  66691. var StringDictionary = /** @class */ (function () {
  66692. function StringDictionary() {
  66693. this._count = 0;
  66694. this._data = {};
  66695. }
  66696. /**
  66697. * This will clear this dictionary and copy the content from the 'source' one.
  66698. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  66699. * @param source the dictionary to take the content from and copy to this dictionary
  66700. */
  66701. StringDictionary.prototype.copyFrom = function (source) {
  66702. var _this = this;
  66703. this.clear();
  66704. source.forEach(function (t, v) { return _this.add(t, v); });
  66705. };
  66706. /**
  66707. * Get a value based from its key
  66708. * @param key the given key to get the matching value from
  66709. * @return the value if found, otherwise undefined is returned
  66710. */
  66711. StringDictionary.prototype.get = function (key) {
  66712. var val = this._data[key];
  66713. if (val !== undefined) {
  66714. return val;
  66715. }
  66716. return undefined;
  66717. };
  66718. /**
  66719. * Get a value from its key or add it if it doesn't exist.
  66720. * This method will ensure you that a given key/data will be present in the dictionary.
  66721. * @param key the given key to get the matching value from
  66722. * @param factory the factory that will create the value if the key is not present in the dictionary.
  66723. * The factory will only be invoked if there's no data for the given key.
  66724. * @return the value corresponding to the key.
  66725. */
  66726. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  66727. var val = this.get(key);
  66728. if (val !== undefined) {
  66729. return val;
  66730. }
  66731. val = factory(key);
  66732. if (val) {
  66733. this.add(key, val);
  66734. }
  66735. return val;
  66736. };
  66737. /**
  66738. * Get a value from its key if present in the dictionary otherwise add it
  66739. * @param key the key to get the value from
  66740. * @param val if there's no such key/value pair in the dictionary add it with this value
  66741. * @return the value corresponding to the key
  66742. */
  66743. StringDictionary.prototype.getOrAdd = function (key, val) {
  66744. var curVal = this.get(key);
  66745. if (curVal !== undefined) {
  66746. return curVal;
  66747. }
  66748. this.add(key, val);
  66749. return val;
  66750. };
  66751. /**
  66752. * Check if there's a given key in the dictionary
  66753. * @param key the key to check for
  66754. * @return true if the key is present, false otherwise
  66755. */
  66756. StringDictionary.prototype.contains = function (key) {
  66757. return this._data[key] !== undefined;
  66758. };
  66759. /**
  66760. * Add a new key and its corresponding value
  66761. * @param key the key to add
  66762. * @param value the value corresponding to the key
  66763. * @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
  66764. */
  66765. StringDictionary.prototype.add = function (key, value) {
  66766. if (this._data[key] !== undefined) {
  66767. return false;
  66768. }
  66769. this._data[key] = value;
  66770. ++this._count;
  66771. return true;
  66772. };
  66773. StringDictionary.prototype.set = function (key, value) {
  66774. if (this._data[key] === undefined) {
  66775. return false;
  66776. }
  66777. this._data[key] = value;
  66778. return true;
  66779. };
  66780. /**
  66781. * Get the element of the given key and remove it from the dictionary
  66782. * @param key
  66783. */
  66784. StringDictionary.prototype.getAndRemove = function (key) {
  66785. var val = this.get(key);
  66786. if (val !== undefined) {
  66787. delete this._data[key];
  66788. --this._count;
  66789. return val;
  66790. }
  66791. return null;
  66792. };
  66793. /**
  66794. * Remove a key/value from the dictionary.
  66795. * @param key the key to remove
  66796. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  66797. */
  66798. StringDictionary.prototype.remove = function (key) {
  66799. if (this.contains(key)) {
  66800. delete this._data[key];
  66801. --this._count;
  66802. return true;
  66803. }
  66804. return false;
  66805. };
  66806. /**
  66807. * Clear the whole content of the dictionary
  66808. */
  66809. StringDictionary.prototype.clear = function () {
  66810. this._data = {};
  66811. this._count = 0;
  66812. };
  66813. Object.defineProperty(StringDictionary.prototype, "count", {
  66814. get: function () {
  66815. return this._count;
  66816. },
  66817. enumerable: true,
  66818. configurable: true
  66819. });
  66820. /**
  66821. * Execute a callback on each key/val of the dictionary.
  66822. * Note that you can remove any element in this dictionary in the callback implementation
  66823. * @param callback the callback to execute on a given key/value pair
  66824. */
  66825. StringDictionary.prototype.forEach = function (callback) {
  66826. for (var cur in this._data) {
  66827. var val = this._data[cur];
  66828. callback(cur, val);
  66829. }
  66830. };
  66831. /**
  66832. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  66833. * If the callback returns null or undefined the method will iterate to the next key/value pair
  66834. * Note that you can remove any element in this dictionary in the callback implementation
  66835. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  66836. */
  66837. StringDictionary.prototype.first = function (callback) {
  66838. for (var cur in this._data) {
  66839. var val = this._data[cur];
  66840. var res = callback(cur, val);
  66841. if (res) {
  66842. return res;
  66843. }
  66844. }
  66845. return null;
  66846. };
  66847. return StringDictionary;
  66848. }());
  66849. BABYLON.StringDictionary = StringDictionary;
  66850. })(BABYLON || (BABYLON = {}));
  66851. //# sourceMappingURL=babylon.stringDictionary.js.map
  66852. "use strict";
  66853. var BABYLON;
  66854. (function (BABYLON) {
  66855. var Tags = /** @class */ (function () {
  66856. function Tags() {
  66857. }
  66858. Tags.EnableFor = function (obj) {
  66859. obj._tags = obj._tags || {};
  66860. obj.hasTags = function () {
  66861. return Tags.HasTags(obj);
  66862. };
  66863. obj.addTags = function (tagsString) {
  66864. return Tags.AddTagsTo(obj, tagsString);
  66865. };
  66866. obj.removeTags = function (tagsString) {
  66867. return Tags.RemoveTagsFrom(obj, tagsString);
  66868. };
  66869. obj.matchesTagsQuery = function (tagsQuery) {
  66870. return Tags.MatchesQuery(obj, tagsQuery);
  66871. };
  66872. };
  66873. Tags.DisableFor = function (obj) {
  66874. delete obj._tags;
  66875. delete obj.hasTags;
  66876. delete obj.addTags;
  66877. delete obj.removeTags;
  66878. delete obj.matchesTagsQuery;
  66879. };
  66880. Tags.HasTags = function (obj) {
  66881. if (!obj._tags) {
  66882. return false;
  66883. }
  66884. return !BABYLON.Tools.IsEmpty(obj._tags);
  66885. };
  66886. Tags.GetTags = function (obj, asString) {
  66887. if (asString === void 0) { asString = true; }
  66888. if (!obj._tags) {
  66889. return null;
  66890. }
  66891. if (asString) {
  66892. var tagsArray = [];
  66893. for (var tag in obj._tags) {
  66894. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  66895. tagsArray.push(tag);
  66896. }
  66897. }
  66898. return tagsArray.join(" ");
  66899. }
  66900. else {
  66901. return obj._tags;
  66902. }
  66903. };
  66904. // the tags 'true' and 'false' are reserved and cannot be used as tags
  66905. // a tag cannot start with '||', '&&', and '!'
  66906. // it cannot contain whitespaces
  66907. Tags.AddTagsTo = function (obj, tagsString) {
  66908. if (!tagsString) {
  66909. return;
  66910. }
  66911. if (typeof tagsString !== "string") {
  66912. return;
  66913. }
  66914. var tags = tagsString.split(" ");
  66915. tags.forEach(function (tag, index, array) {
  66916. Tags._AddTagTo(obj, tag);
  66917. });
  66918. };
  66919. Tags._AddTagTo = function (obj, tag) {
  66920. tag = tag.trim();
  66921. if (tag === "" || tag === "true" || tag === "false") {
  66922. return;
  66923. }
  66924. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  66925. return;
  66926. }
  66927. Tags.EnableFor(obj);
  66928. obj._tags[tag] = true;
  66929. };
  66930. Tags.RemoveTagsFrom = function (obj, tagsString) {
  66931. if (!Tags.HasTags(obj)) {
  66932. return;
  66933. }
  66934. var tags = tagsString.split(" ");
  66935. for (var t in tags) {
  66936. Tags._RemoveTagFrom(obj, tags[t]);
  66937. }
  66938. };
  66939. Tags._RemoveTagFrom = function (obj, tag) {
  66940. delete obj._tags[tag];
  66941. };
  66942. Tags.MatchesQuery = function (obj, tagsQuery) {
  66943. if (tagsQuery === undefined) {
  66944. return true;
  66945. }
  66946. if (tagsQuery === "") {
  66947. return Tags.HasTags(obj);
  66948. }
  66949. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  66950. };
  66951. return Tags;
  66952. }());
  66953. BABYLON.Tags = Tags;
  66954. })(BABYLON || (BABYLON = {}));
  66955. //# sourceMappingURL=babylon.tags.js.map
  66956. "use strict";
  66957. var BABYLON;
  66958. (function (BABYLON) {
  66959. var AndOrNotEvaluator = /** @class */ (function () {
  66960. function AndOrNotEvaluator() {
  66961. }
  66962. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  66963. if (!query.match(/\([^\(\)]*\)/g)) {
  66964. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  66965. }
  66966. else {
  66967. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  66968. // remove parenthesis
  66969. r = r.slice(1, r.length - 1);
  66970. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  66971. });
  66972. }
  66973. if (query === "true") {
  66974. return true;
  66975. }
  66976. if (query === "false") {
  66977. return false;
  66978. }
  66979. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  66980. };
  66981. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  66982. evaluateCallback = evaluateCallback || (function (r) {
  66983. return r === "true" ? true : false;
  66984. });
  66985. var result;
  66986. var or = parenthesisContent.split("||");
  66987. for (var i in or) {
  66988. if (or.hasOwnProperty(i)) {
  66989. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  66990. var and = ori.split("&&");
  66991. if (and.length > 1) {
  66992. for (var j = 0; j < and.length; ++j) {
  66993. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  66994. if (andj !== "true" && andj !== "false") {
  66995. if (andj[0] === "!") {
  66996. result = !evaluateCallback(andj.substring(1));
  66997. }
  66998. else {
  66999. result = evaluateCallback(andj);
  67000. }
  67001. }
  67002. else {
  67003. result = andj === "true" ? true : false;
  67004. }
  67005. if (!result) {
  67006. ori = "false";
  67007. break;
  67008. }
  67009. }
  67010. }
  67011. if (result || ori === "true") {
  67012. result = true;
  67013. break;
  67014. }
  67015. // result equals false (or undefined)
  67016. if (ori !== "true" && ori !== "false") {
  67017. if (ori[0] === "!") {
  67018. result = !evaluateCallback(ori.substring(1));
  67019. }
  67020. else {
  67021. result = evaluateCallback(ori);
  67022. }
  67023. }
  67024. else {
  67025. result = ori === "true" ? true : false;
  67026. }
  67027. }
  67028. }
  67029. // the whole parenthesis scope is replaced by 'true' or 'false'
  67030. return result ? "true" : "false";
  67031. };
  67032. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  67033. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  67034. // remove whitespaces
  67035. r = r.replace(/[\s]/g, function () { return ""; });
  67036. return r.length % 2 ? "!" : "";
  67037. });
  67038. booleanString = booleanString.trim();
  67039. if (booleanString === "!true") {
  67040. booleanString = "false";
  67041. }
  67042. else if (booleanString === "!false") {
  67043. booleanString = "true";
  67044. }
  67045. return booleanString;
  67046. };
  67047. return AndOrNotEvaluator;
  67048. }());
  67049. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  67050. })(BABYLON || (BABYLON = {}));
  67051. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  67052. "use strict";
  67053. var BABYLON;
  67054. (function (BABYLON) {
  67055. var Database = /** @class */ (function () {
  67056. function Database(urlToScene, callbackManifestChecked) {
  67057. // Handling various flavors of prefixed version of IndexedDB
  67058. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  67059. this.callbackManifestChecked = callbackManifestChecked;
  67060. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  67061. this.db = null;
  67062. this._enableSceneOffline = false;
  67063. this._enableTexturesOffline = false;
  67064. this.manifestVersionFound = 0;
  67065. this.mustUpdateRessources = false;
  67066. this.hasReachedQuota = false;
  67067. if (!Database.IDBStorageEnabled) {
  67068. this.callbackManifestChecked(true);
  67069. }
  67070. else {
  67071. this.checkManifestFile();
  67072. }
  67073. }
  67074. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  67075. get: function () {
  67076. return this._enableSceneOffline;
  67077. },
  67078. enumerable: true,
  67079. configurable: true
  67080. });
  67081. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  67082. get: function () {
  67083. return this._enableTexturesOffline;
  67084. },
  67085. enumerable: true,
  67086. configurable: true
  67087. });
  67088. Database.prototype.checkManifestFile = function () {
  67089. var _this = this;
  67090. var noManifestFile = function () {
  67091. _this._enableSceneOffline = false;
  67092. _this._enableTexturesOffline = false;
  67093. _this.callbackManifestChecked(false);
  67094. };
  67095. var timeStampUsed = false;
  67096. var manifestURL = this.currentSceneUrl + ".manifest";
  67097. var xhr = new XMLHttpRequest();
  67098. if (navigator.onLine) {
  67099. // Adding a timestamp to by-pass browsers' cache
  67100. timeStampUsed = true;
  67101. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  67102. }
  67103. xhr.open("GET", manifestURL, true);
  67104. xhr.addEventListener("load", function () {
  67105. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  67106. try {
  67107. var manifestFile = JSON.parse(xhr.response);
  67108. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  67109. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  67110. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  67111. _this.manifestVersionFound = manifestFile.version;
  67112. }
  67113. if (_this.callbackManifestChecked) {
  67114. _this.callbackManifestChecked(true);
  67115. }
  67116. }
  67117. catch (ex) {
  67118. noManifestFile();
  67119. }
  67120. }
  67121. else {
  67122. noManifestFile();
  67123. }
  67124. }, false);
  67125. xhr.addEventListener("error", function (event) {
  67126. if (timeStampUsed) {
  67127. timeStampUsed = false;
  67128. // Let's retry without the timeStamp
  67129. // It could fail when coupled with HTML5 Offline API
  67130. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  67131. xhr.open("GET", retryManifestURL, true);
  67132. xhr.send();
  67133. }
  67134. else {
  67135. noManifestFile();
  67136. }
  67137. }, false);
  67138. try {
  67139. xhr.send();
  67140. }
  67141. catch (ex) {
  67142. BABYLON.Tools.Error("Error on XHR send request.");
  67143. this.callbackManifestChecked(false);
  67144. }
  67145. };
  67146. Database.prototype.openAsync = function (successCallback, errorCallback) {
  67147. var _this = this;
  67148. var handleError = function () {
  67149. _this.isSupported = false;
  67150. if (errorCallback)
  67151. errorCallback();
  67152. };
  67153. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  67154. // Your browser doesn't support IndexedDB
  67155. this.isSupported = false;
  67156. if (errorCallback)
  67157. errorCallback();
  67158. }
  67159. else {
  67160. // If the DB hasn't been opened or created yet
  67161. if (!this.db) {
  67162. this.hasReachedQuota = false;
  67163. this.isSupported = true;
  67164. var request = this.idbFactory.open("babylonjs", 1);
  67165. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  67166. request.onerror = function (event) {
  67167. handleError();
  67168. };
  67169. // executes when a version change transaction cannot complete due to other active transactions
  67170. request.onblocked = function (event) {
  67171. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  67172. handleError();
  67173. };
  67174. // DB has been opened successfully
  67175. request.onsuccess = function (event) {
  67176. _this.db = request.result;
  67177. successCallback();
  67178. };
  67179. // Initialization of the DB. Creating Scenes & Textures stores
  67180. request.onupgradeneeded = function (event) {
  67181. _this.db = (event.target).result;
  67182. if (_this.db) {
  67183. try {
  67184. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  67185. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  67186. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  67187. }
  67188. catch (ex) {
  67189. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  67190. handleError();
  67191. }
  67192. }
  67193. };
  67194. }
  67195. else {
  67196. if (successCallback)
  67197. successCallback();
  67198. }
  67199. }
  67200. };
  67201. Database.prototype.loadImageFromDB = function (url, image) {
  67202. var _this = this;
  67203. var completeURL = Database.ReturnFullUrlLocation(url);
  67204. var saveAndLoadImage = function () {
  67205. if (!_this.hasReachedQuota && _this.db !== null) {
  67206. // the texture is not yet in the DB, let's try to save it
  67207. _this._saveImageIntoDBAsync(completeURL, image);
  67208. }
  67209. else {
  67210. image.src = url;
  67211. }
  67212. };
  67213. if (!this.mustUpdateRessources) {
  67214. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  67215. }
  67216. else {
  67217. saveAndLoadImage();
  67218. }
  67219. };
  67220. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  67221. if (this.isSupported && this.db !== null) {
  67222. var texture;
  67223. var transaction = this.db.transaction(["textures"]);
  67224. transaction.onabort = function (event) {
  67225. image.src = url;
  67226. };
  67227. transaction.oncomplete = function (event) {
  67228. var blobTextureURL;
  67229. if (texture) {
  67230. var URL = window.URL || window.webkitURL;
  67231. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  67232. image.onerror = function () {
  67233. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  67234. image.src = url;
  67235. };
  67236. image.src = blobTextureURL;
  67237. }
  67238. else {
  67239. notInDBCallback();
  67240. }
  67241. };
  67242. var getRequest = transaction.objectStore("textures").get(url);
  67243. getRequest.onsuccess = function (event) {
  67244. texture = (event.target).result;
  67245. };
  67246. getRequest.onerror = function (event) {
  67247. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  67248. image.src = url;
  67249. };
  67250. }
  67251. else {
  67252. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67253. image.src = url;
  67254. }
  67255. };
  67256. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  67257. var _this = this;
  67258. if (this.isSupported) {
  67259. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  67260. var generateBlobUrl = function () {
  67261. var blobTextureURL;
  67262. if (blob) {
  67263. var URL = window.URL || window.webkitURL;
  67264. try {
  67265. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  67266. }
  67267. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  67268. catch (ex) {
  67269. blobTextureURL = URL.createObjectURL(blob);
  67270. }
  67271. }
  67272. if (blobTextureURL) {
  67273. image.src = blobTextureURL;
  67274. }
  67275. };
  67276. if (Database.IsUASupportingBlobStorage) {
  67277. var xhr = new XMLHttpRequest(), blob;
  67278. xhr.open("GET", url, true);
  67279. xhr.responseType = "blob";
  67280. xhr.addEventListener("load", function () {
  67281. if (xhr.status === 200 && _this.db) {
  67282. // Blob as response (XHR2)
  67283. blob = xhr.response;
  67284. var transaction = _this.db.transaction(["textures"], "readwrite");
  67285. // the transaction could abort because of a QuotaExceededError error
  67286. transaction.onabort = function (event) {
  67287. try {
  67288. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67289. var srcElement = (event.srcElement || event.target);
  67290. var error = srcElement.error;
  67291. if (error && error.name === "QuotaExceededError") {
  67292. _this.hasReachedQuota = true;
  67293. }
  67294. }
  67295. catch (ex) { }
  67296. generateBlobUrl();
  67297. };
  67298. transaction.oncomplete = function (event) {
  67299. generateBlobUrl();
  67300. };
  67301. var newTexture = { textureUrl: url, data: blob };
  67302. try {
  67303. // Put the blob into the dabase
  67304. var addRequest = transaction.objectStore("textures").put(newTexture);
  67305. addRequest.onsuccess = function (event) {
  67306. };
  67307. addRequest.onerror = function (event) {
  67308. generateBlobUrl();
  67309. };
  67310. }
  67311. catch (ex) {
  67312. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  67313. if (ex.code === 25) {
  67314. Database.IsUASupportingBlobStorage = false;
  67315. }
  67316. image.src = url;
  67317. }
  67318. }
  67319. else {
  67320. image.src = url;
  67321. }
  67322. }, false);
  67323. xhr.addEventListener("error", function (event) {
  67324. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  67325. image.src = url;
  67326. }, false);
  67327. xhr.send();
  67328. }
  67329. else {
  67330. image.src = url;
  67331. }
  67332. }
  67333. else {
  67334. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67335. image.src = url;
  67336. }
  67337. };
  67338. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  67339. var _this = this;
  67340. var updateVersion = function () {
  67341. // the version is not yet in the DB or we need to update it
  67342. _this._saveVersionIntoDBAsync(url, versionLoaded);
  67343. };
  67344. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  67345. };
  67346. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  67347. var _this = this;
  67348. if (this.isSupported && this.db) {
  67349. var version;
  67350. try {
  67351. var transaction = this.db.transaction(["versions"]);
  67352. transaction.oncomplete = function (event) {
  67353. if (version) {
  67354. // If the version in the JSON file is > than the version in DB
  67355. if (_this.manifestVersionFound > version.data) {
  67356. _this.mustUpdateRessources = true;
  67357. updateInDBCallback();
  67358. }
  67359. else {
  67360. callback(version.data);
  67361. }
  67362. }
  67363. else {
  67364. _this.mustUpdateRessources = true;
  67365. updateInDBCallback();
  67366. }
  67367. };
  67368. transaction.onabort = function (event) {
  67369. callback(-1);
  67370. };
  67371. var getRequest = transaction.objectStore("versions").get(url);
  67372. getRequest.onsuccess = function (event) {
  67373. version = (event.target).result;
  67374. };
  67375. getRequest.onerror = function (event) {
  67376. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  67377. callback(-1);
  67378. };
  67379. }
  67380. catch (ex) {
  67381. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  67382. callback(-1);
  67383. }
  67384. }
  67385. else {
  67386. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67387. callback(-1);
  67388. }
  67389. };
  67390. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  67391. var _this = this;
  67392. if (this.isSupported && !this.hasReachedQuota && this.db) {
  67393. try {
  67394. // Open a transaction to the database
  67395. var transaction = this.db.transaction(["versions"], "readwrite");
  67396. // the transaction could abort because of a QuotaExceededError error
  67397. transaction.onabort = function (event) {
  67398. try {
  67399. var error = event.srcElement['error'];
  67400. if (error && error.name === "QuotaExceededError") {
  67401. _this.hasReachedQuota = true;
  67402. }
  67403. }
  67404. catch (ex) { }
  67405. callback(-1);
  67406. };
  67407. transaction.oncomplete = function (event) {
  67408. callback(_this.manifestVersionFound);
  67409. };
  67410. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  67411. // Put the scene into the database
  67412. var addRequest = transaction.objectStore("versions").put(newVersion);
  67413. addRequest.onsuccess = function (event) {
  67414. };
  67415. addRequest.onerror = function (event) {
  67416. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  67417. };
  67418. }
  67419. catch (ex) {
  67420. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  67421. callback(-1);
  67422. }
  67423. }
  67424. else {
  67425. callback(-1);
  67426. }
  67427. };
  67428. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  67429. var _this = this;
  67430. var completeUrl = Database.ReturnFullUrlLocation(url);
  67431. var saveAndLoadFile = function () {
  67432. // the scene is not yet in the DB, let's try to save it
  67433. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  67434. };
  67435. this._checkVersionFromDB(completeUrl, function (version) {
  67436. if (version !== -1) {
  67437. if (!_this.mustUpdateRessources) {
  67438. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  67439. }
  67440. else {
  67441. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  67442. }
  67443. }
  67444. else {
  67445. if (errorCallback) {
  67446. errorCallback();
  67447. }
  67448. }
  67449. });
  67450. };
  67451. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  67452. if (this.isSupported && this.db) {
  67453. var targetStore;
  67454. if (url.indexOf(".babylon") !== -1) {
  67455. targetStore = "scenes";
  67456. }
  67457. else {
  67458. targetStore = "textures";
  67459. }
  67460. var file;
  67461. var transaction = this.db.transaction([targetStore]);
  67462. transaction.oncomplete = function (event) {
  67463. if (file) {
  67464. callback(file.data);
  67465. }
  67466. else {
  67467. notInDBCallback();
  67468. }
  67469. };
  67470. transaction.onabort = function (event) {
  67471. notInDBCallback();
  67472. };
  67473. var getRequest = transaction.objectStore(targetStore).get(url);
  67474. getRequest.onsuccess = function (event) {
  67475. file = (event.target).result;
  67476. };
  67477. getRequest.onerror = function (event) {
  67478. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  67479. notInDBCallback();
  67480. };
  67481. }
  67482. else {
  67483. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67484. callback();
  67485. }
  67486. };
  67487. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  67488. var _this = this;
  67489. if (this.isSupported) {
  67490. var targetStore;
  67491. if (url.indexOf(".babylon") !== -1) {
  67492. targetStore = "scenes";
  67493. }
  67494. else {
  67495. targetStore = "textures";
  67496. }
  67497. // Create XHR
  67498. var xhr = new XMLHttpRequest();
  67499. var fileData;
  67500. xhr.open("GET", url, true);
  67501. if (useArrayBuffer) {
  67502. xhr.responseType = "arraybuffer";
  67503. }
  67504. if (progressCallback) {
  67505. xhr.onprogress = progressCallback;
  67506. }
  67507. xhr.addEventListener("load", function () {
  67508. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  67509. // Blob as response (XHR2)
  67510. //fileData = xhr.responseText;
  67511. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  67512. if (!_this.hasReachedQuota && _this.db) {
  67513. // Open a transaction to the database
  67514. var transaction = _this.db.transaction([targetStore], "readwrite");
  67515. // the transaction could abort because of a QuotaExceededError error
  67516. transaction.onabort = function (event) {
  67517. try {
  67518. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  67519. var error = event.srcElement['error'];
  67520. if (error && error.name === "QuotaExceededError") {
  67521. _this.hasReachedQuota = true;
  67522. }
  67523. }
  67524. catch (ex) { }
  67525. callback(fileData);
  67526. };
  67527. transaction.oncomplete = function (event) {
  67528. callback(fileData);
  67529. };
  67530. var newFile;
  67531. if (targetStore === "scenes") {
  67532. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  67533. }
  67534. else {
  67535. newFile = { textureUrl: url, data: fileData };
  67536. }
  67537. try {
  67538. // Put the scene into the database
  67539. var addRequest = transaction.objectStore(targetStore).put(newFile);
  67540. addRequest.onsuccess = function (event) {
  67541. };
  67542. addRequest.onerror = function (event) {
  67543. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  67544. };
  67545. }
  67546. catch (ex) {
  67547. callback(fileData);
  67548. }
  67549. }
  67550. else {
  67551. callback(fileData);
  67552. }
  67553. }
  67554. else {
  67555. callback();
  67556. }
  67557. }, false);
  67558. xhr.addEventListener("error", function (event) {
  67559. BABYLON.Tools.Error("error on XHR request.");
  67560. callback();
  67561. }, false);
  67562. xhr.send();
  67563. }
  67564. else {
  67565. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  67566. callback();
  67567. }
  67568. };
  67569. Database.IsUASupportingBlobStorage = true;
  67570. Database.IDBStorageEnabled = true;
  67571. Database.parseURL = function (url) {
  67572. var a = document.createElement('a');
  67573. a.href = url;
  67574. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  67575. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  67576. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  67577. return absLocation;
  67578. };
  67579. Database.ReturnFullUrlLocation = function (url) {
  67580. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  67581. return (Database.parseURL(window.location.href) + url);
  67582. }
  67583. else {
  67584. return url;
  67585. }
  67586. };
  67587. return Database;
  67588. }());
  67589. BABYLON.Database = Database;
  67590. })(BABYLON || (BABYLON = {}));
  67591. //# sourceMappingURL=babylon.database.js.map
  67592. "use strict";
  67593. var BABYLON;
  67594. (function (BABYLON) {
  67595. var FresnelParameters = /** @class */ (function () {
  67596. function FresnelParameters() {
  67597. this._isEnabled = true;
  67598. this.leftColor = BABYLON.Color3.White();
  67599. this.rightColor = BABYLON.Color3.Black();
  67600. this.bias = 0;
  67601. this.power = 1;
  67602. }
  67603. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  67604. get: function () {
  67605. return this._isEnabled;
  67606. },
  67607. set: function (value) {
  67608. if (this._isEnabled === value) {
  67609. return;
  67610. }
  67611. this._isEnabled = value;
  67612. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  67613. },
  67614. enumerable: true,
  67615. configurable: true
  67616. });
  67617. FresnelParameters.prototype.clone = function () {
  67618. var newFresnelParameters = new FresnelParameters();
  67619. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  67620. return newFresnelParameters;
  67621. };
  67622. FresnelParameters.prototype.serialize = function () {
  67623. var serializationObject = {};
  67624. serializationObject.isEnabled = this.isEnabled;
  67625. serializationObject.leftColor = this.leftColor.asArray();
  67626. serializationObject.rightColor = this.rightColor.asArray();
  67627. serializationObject.bias = this.bias;
  67628. serializationObject.power = this.power;
  67629. return serializationObject;
  67630. };
  67631. FresnelParameters.Parse = function (parsedFresnelParameters) {
  67632. var fresnelParameters = new FresnelParameters();
  67633. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  67634. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  67635. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  67636. fresnelParameters.bias = parsedFresnelParameters.bias;
  67637. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  67638. return fresnelParameters;
  67639. };
  67640. return FresnelParameters;
  67641. }());
  67642. BABYLON.FresnelParameters = FresnelParameters;
  67643. })(BABYLON || (BABYLON = {}));
  67644. //# sourceMappingURL=babylon.fresnelParameters.js.map
  67645. "use strict";
  67646. var BABYLON;
  67647. (function (BABYLON) {
  67648. var MultiMaterial = /** @class */ (function (_super) {
  67649. __extends(MultiMaterial, _super);
  67650. function MultiMaterial(name, scene) {
  67651. var _this = _super.call(this, name, scene, true) || this;
  67652. scene.multiMaterials.push(_this);
  67653. _this.subMaterials = new Array();
  67654. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  67655. return _this;
  67656. }
  67657. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  67658. get: function () {
  67659. return this._subMaterials;
  67660. },
  67661. set: function (value) {
  67662. this._subMaterials = value;
  67663. this._hookArray(value);
  67664. },
  67665. enumerable: true,
  67666. configurable: true
  67667. });
  67668. MultiMaterial.prototype._hookArray = function (array) {
  67669. var _this = this;
  67670. var oldPush = array.push;
  67671. array.push = function () {
  67672. var items = [];
  67673. for (var _i = 0; _i < arguments.length; _i++) {
  67674. items[_i] = arguments[_i];
  67675. }
  67676. var result = oldPush.apply(array, items);
  67677. _this._markAllSubMeshesAsTexturesDirty();
  67678. return result;
  67679. };
  67680. var oldSplice = array.splice;
  67681. array.splice = function (index, deleteCount) {
  67682. var deleted = oldSplice.apply(array, [index, deleteCount]);
  67683. _this._markAllSubMeshesAsTexturesDirty();
  67684. return deleted;
  67685. };
  67686. };
  67687. // Properties
  67688. MultiMaterial.prototype.getSubMaterial = function (index) {
  67689. if (index < 0 || index >= this.subMaterials.length) {
  67690. return this.getScene().defaultMaterial;
  67691. }
  67692. return this.subMaterials[index];
  67693. };
  67694. MultiMaterial.prototype.getActiveTextures = function () {
  67695. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  67696. if (subMaterial) {
  67697. return subMaterial.getActiveTextures();
  67698. }
  67699. else {
  67700. return [];
  67701. }
  67702. }));
  67703. var _a;
  67704. };
  67705. // Methods
  67706. MultiMaterial.prototype.getClassName = function () {
  67707. return "MultiMaterial";
  67708. };
  67709. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  67710. for (var index = 0; index < this.subMaterials.length; index++) {
  67711. var subMaterial = this.subMaterials[index];
  67712. if (subMaterial) {
  67713. if (subMaterial.storeEffectOnSubMeshes) {
  67714. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  67715. return false;
  67716. }
  67717. continue;
  67718. }
  67719. if (!subMaterial.isReady(mesh)) {
  67720. return false;
  67721. }
  67722. }
  67723. }
  67724. return true;
  67725. };
  67726. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  67727. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  67728. for (var index = 0; index < this.subMaterials.length; index++) {
  67729. var subMaterial = null;
  67730. var current = this.subMaterials[index];
  67731. if (cloneChildren && current) {
  67732. subMaterial = current.clone(name + "-" + current.name);
  67733. }
  67734. else {
  67735. subMaterial = this.subMaterials[index];
  67736. }
  67737. newMultiMaterial.subMaterials.push(subMaterial);
  67738. }
  67739. return newMultiMaterial;
  67740. };
  67741. MultiMaterial.prototype.serialize = function () {
  67742. var serializationObject = {};
  67743. serializationObject.name = this.name;
  67744. serializationObject.id = this.id;
  67745. if (BABYLON.Tags) {
  67746. serializationObject.tags = BABYLON.Tags.GetTags(this);
  67747. }
  67748. serializationObject.materials = [];
  67749. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  67750. var subMat = this.subMaterials[matIndex];
  67751. if (subMat) {
  67752. serializationObject.materials.push(subMat.id);
  67753. }
  67754. else {
  67755. serializationObject.materials.push(null);
  67756. }
  67757. }
  67758. return serializationObject;
  67759. };
  67760. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  67761. var scene = this.getScene();
  67762. if (!scene) {
  67763. return;
  67764. }
  67765. var index = scene.multiMaterials.indexOf(this);
  67766. if (index >= 0) {
  67767. scene.multiMaterials.splice(index, 1);
  67768. }
  67769. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  67770. };
  67771. return MultiMaterial;
  67772. }(BABYLON.Material));
  67773. BABYLON.MultiMaterial = MultiMaterial;
  67774. })(BABYLON || (BABYLON = {}));
  67775. //# sourceMappingURL=babylon.multiMaterial.js.map
  67776. "use strict";
  67777. var BABYLON;
  67778. (function (BABYLON) {
  67779. var FreeCameraTouchInput = /** @class */ (function () {
  67780. function FreeCameraTouchInput() {
  67781. this._offsetX = null;
  67782. this._offsetY = null;
  67783. this._pointerPressed = new Array();
  67784. this.touchAngularSensibility = 200000.0;
  67785. this.touchMoveSensibility = 250.0;
  67786. }
  67787. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  67788. var _this = this;
  67789. var previousPosition = null;
  67790. if (this._pointerInput === undefined) {
  67791. this._onLostFocus = function (evt) {
  67792. _this._offsetX = null;
  67793. _this._offsetY = null;
  67794. };
  67795. this._pointerInput = function (p, s) {
  67796. var evt = p.event;
  67797. if (evt.pointerType === "mouse") {
  67798. return;
  67799. }
  67800. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  67801. if (!noPreventDefault) {
  67802. evt.preventDefault();
  67803. }
  67804. _this._pointerPressed.push(evt.pointerId);
  67805. if (_this._pointerPressed.length !== 1) {
  67806. return;
  67807. }
  67808. previousPosition = {
  67809. x: evt.clientX,
  67810. y: evt.clientY
  67811. };
  67812. }
  67813. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  67814. if (!noPreventDefault) {
  67815. evt.preventDefault();
  67816. }
  67817. var index = _this._pointerPressed.indexOf(evt.pointerId);
  67818. if (index === -1) {
  67819. return;
  67820. }
  67821. _this._pointerPressed.splice(index, 1);
  67822. if (index != 0) {
  67823. return;
  67824. }
  67825. previousPosition = null;
  67826. _this._offsetX = null;
  67827. _this._offsetY = null;
  67828. }
  67829. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  67830. if (!noPreventDefault) {
  67831. evt.preventDefault();
  67832. }
  67833. if (!previousPosition) {
  67834. return;
  67835. }
  67836. var index = _this._pointerPressed.indexOf(evt.pointerId);
  67837. if (index != 0) {
  67838. return;
  67839. }
  67840. _this._offsetX = evt.clientX - previousPosition.x;
  67841. _this._offsetY = -(evt.clientY - previousPosition.y);
  67842. }
  67843. };
  67844. }
  67845. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  67846. if (this._onLostFocus) {
  67847. element.addEventListener("blur", this._onLostFocus);
  67848. }
  67849. };
  67850. FreeCameraTouchInput.prototype.detachControl = function (element) {
  67851. if (this._pointerInput && element) {
  67852. if (this._observer) {
  67853. this.camera.getScene().onPointerObservable.remove(this._observer);
  67854. this._observer = null;
  67855. }
  67856. if (this._onLostFocus) {
  67857. element.removeEventListener("blur", this._onLostFocus);
  67858. this._onLostFocus = null;
  67859. }
  67860. this._pointerPressed = [];
  67861. this._offsetX = null;
  67862. this._offsetY = null;
  67863. }
  67864. };
  67865. FreeCameraTouchInput.prototype.checkInputs = function () {
  67866. if (this._offsetX && this._offsetY) {
  67867. var camera = this.camera;
  67868. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  67869. if (this._pointerPressed.length > 1) {
  67870. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  67871. }
  67872. else {
  67873. var speed = camera._computeLocalCameraSpeed();
  67874. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  67875. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  67876. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  67877. }
  67878. }
  67879. };
  67880. FreeCameraTouchInput.prototype.getClassName = function () {
  67881. return "FreeCameraTouchInput";
  67882. };
  67883. FreeCameraTouchInput.prototype.getSimpleName = function () {
  67884. return "touch";
  67885. };
  67886. __decorate([
  67887. BABYLON.serialize()
  67888. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  67889. __decorate([
  67890. BABYLON.serialize()
  67891. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  67892. return FreeCameraTouchInput;
  67893. }());
  67894. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  67895. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  67896. })(BABYLON || (BABYLON = {}));
  67897. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  67898. "use strict";
  67899. var BABYLON;
  67900. (function (BABYLON) {
  67901. // We're mainly based on the logic defined into the FreeCamera code
  67902. var TouchCamera = /** @class */ (function (_super) {
  67903. __extends(TouchCamera, _super);
  67904. //-- end properties for backward compatibility for inputs
  67905. function TouchCamera(name, position, scene) {
  67906. var _this = _super.call(this, name, position, scene) || this;
  67907. _this.inputs.addTouch();
  67908. _this._setupInputs();
  67909. return _this;
  67910. }
  67911. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  67912. //-- Begin properties for backward compatibility for inputs
  67913. get: function () {
  67914. var touch = this.inputs.attached["touch"];
  67915. if (touch)
  67916. return touch.touchAngularSensibility;
  67917. return 0;
  67918. },
  67919. set: function (value) {
  67920. var touch = this.inputs.attached["touch"];
  67921. if (touch)
  67922. touch.touchAngularSensibility = value;
  67923. },
  67924. enumerable: true,
  67925. configurable: true
  67926. });
  67927. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  67928. get: function () {
  67929. var touch = this.inputs.attached["touch"];
  67930. if (touch)
  67931. return touch.touchMoveSensibility;
  67932. return 0;
  67933. },
  67934. set: function (value) {
  67935. var touch = this.inputs.attached["touch"];
  67936. if (touch)
  67937. touch.touchMoveSensibility = value;
  67938. },
  67939. enumerable: true,
  67940. configurable: true
  67941. });
  67942. TouchCamera.prototype.getClassName = function () {
  67943. return "TouchCamera";
  67944. };
  67945. TouchCamera.prototype._setupInputs = function () {
  67946. var mouse = this.inputs.attached["mouse"];
  67947. if (mouse) {
  67948. mouse.touchEnabled = false;
  67949. }
  67950. };
  67951. return TouchCamera;
  67952. }(BABYLON.FreeCamera));
  67953. BABYLON.TouchCamera = TouchCamera;
  67954. })(BABYLON || (BABYLON = {}));
  67955. //# sourceMappingURL=babylon.touchCamera.js.map
  67956. "use strict";
  67957. var BABYLON;
  67958. (function (BABYLON) {
  67959. var ProceduralTexture = /** @class */ (function (_super) {
  67960. __extends(ProceduralTexture, _super);
  67961. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  67962. if (fallbackTexture === void 0) { fallbackTexture = null; }
  67963. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67964. if (isCube === void 0) { isCube = false; }
  67965. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  67966. _this.isCube = isCube;
  67967. _this.isEnabled = true;
  67968. _this._currentRefreshId = -1;
  67969. _this._refreshRate = 1;
  67970. _this._vertexBuffers = {};
  67971. _this._uniforms = new Array();
  67972. _this._samplers = new Array();
  67973. _this._textures = {};
  67974. _this._floats = {};
  67975. _this._floatsArrays = {};
  67976. _this._colors3 = {};
  67977. _this._colors4 = {};
  67978. _this._vectors2 = {};
  67979. _this._vectors3 = {};
  67980. _this._matrices = {};
  67981. _this._fallbackTextureUsed = false;
  67982. scene.proceduralTextures.push(_this);
  67983. _this._engine = scene.getEngine();
  67984. _this.name = name;
  67985. _this.isRenderTarget = true;
  67986. _this._size = size;
  67987. _this._generateMipMaps = generateMipMaps;
  67988. _this.setFragment(fragment);
  67989. _this._fallbackTexture = fallbackTexture;
  67990. if (isCube) {
  67991. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  67992. _this.setFloat("face", 0);
  67993. }
  67994. else {
  67995. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  67996. }
  67997. // VBO
  67998. var vertices = [];
  67999. vertices.push(1, 1);
  68000. vertices.push(-1, 1);
  68001. vertices.push(-1, -1);
  68002. vertices.push(1, -1);
  68003. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68004. _this._createIndexBuffer();
  68005. return _this;
  68006. }
  68007. ProceduralTexture.prototype._createIndexBuffer = function () {
  68008. var engine = this._engine;
  68009. // Indices
  68010. var indices = [];
  68011. indices.push(0);
  68012. indices.push(1);
  68013. indices.push(2);
  68014. indices.push(0);
  68015. indices.push(2);
  68016. indices.push(3);
  68017. this._indexBuffer = engine.createIndexBuffer(indices);
  68018. };
  68019. ProceduralTexture.prototype._rebuild = function () {
  68020. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68021. if (vb) {
  68022. vb._rebuild();
  68023. }
  68024. this._createIndexBuffer();
  68025. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68026. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68027. }
  68028. };
  68029. ProceduralTexture.prototype.reset = function () {
  68030. if (this._effect === undefined) {
  68031. return;
  68032. }
  68033. var engine = this._engine;
  68034. engine._releaseEffect(this._effect);
  68035. };
  68036. ProceduralTexture.prototype.isReady = function () {
  68037. var _this = this;
  68038. var engine = this._engine;
  68039. var shaders;
  68040. if (!this._fragment) {
  68041. return false;
  68042. }
  68043. if (this._fallbackTextureUsed) {
  68044. return true;
  68045. }
  68046. if (this._fragment.fragmentElement !== undefined) {
  68047. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  68048. }
  68049. else {
  68050. shaders = { vertex: "procedural", fragment: this._fragment };
  68051. }
  68052. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  68053. _this.releaseInternalTexture();
  68054. if (_this._fallbackTexture) {
  68055. _this._texture = _this._fallbackTexture._texture;
  68056. if (_this._texture) {
  68057. _this._texture.incrementReferences();
  68058. }
  68059. }
  68060. _this._fallbackTextureUsed = true;
  68061. });
  68062. return this._effect.isReady();
  68063. };
  68064. ProceduralTexture.prototype.resetRefreshCounter = function () {
  68065. this._currentRefreshId = -1;
  68066. };
  68067. ProceduralTexture.prototype.setFragment = function (fragment) {
  68068. this._fragment = fragment;
  68069. };
  68070. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  68071. get: function () {
  68072. return this._refreshRate;
  68073. },
  68074. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  68075. set: function (value) {
  68076. this._refreshRate = value;
  68077. this.resetRefreshCounter();
  68078. },
  68079. enumerable: true,
  68080. configurable: true
  68081. });
  68082. ProceduralTexture.prototype._shouldRender = function () {
  68083. if (!this.isEnabled || !this.isReady() || !this._texture) {
  68084. return false;
  68085. }
  68086. if (this._fallbackTextureUsed) {
  68087. return false;
  68088. }
  68089. if (this._currentRefreshId === -1) {
  68090. this._currentRefreshId = 1;
  68091. return true;
  68092. }
  68093. if (this.refreshRate === this._currentRefreshId) {
  68094. this._currentRefreshId = 1;
  68095. return true;
  68096. }
  68097. this._currentRefreshId++;
  68098. return false;
  68099. };
  68100. ProceduralTexture.prototype.getRenderSize = function () {
  68101. return this._size;
  68102. };
  68103. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  68104. if (this._fallbackTextureUsed) {
  68105. return;
  68106. }
  68107. this.releaseInternalTexture();
  68108. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  68109. };
  68110. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  68111. if (this._uniforms.indexOf(uniformName) === -1) {
  68112. this._uniforms.push(uniformName);
  68113. }
  68114. };
  68115. ProceduralTexture.prototype.setTexture = function (name, texture) {
  68116. if (this._samplers.indexOf(name) === -1) {
  68117. this._samplers.push(name);
  68118. }
  68119. this._textures[name] = texture;
  68120. return this;
  68121. };
  68122. ProceduralTexture.prototype.setFloat = function (name, value) {
  68123. this._checkUniform(name);
  68124. this._floats[name] = value;
  68125. return this;
  68126. };
  68127. ProceduralTexture.prototype.setFloats = function (name, value) {
  68128. this._checkUniform(name);
  68129. this._floatsArrays[name] = value;
  68130. return this;
  68131. };
  68132. ProceduralTexture.prototype.setColor3 = function (name, value) {
  68133. this._checkUniform(name);
  68134. this._colors3[name] = value;
  68135. return this;
  68136. };
  68137. ProceduralTexture.prototype.setColor4 = function (name, value) {
  68138. this._checkUniform(name);
  68139. this._colors4[name] = value;
  68140. return this;
  68141. };
  68142. ProceduralTexture.prototype.setVector2 = function (name, value) {
  68143. this._checkUniform(name);
  68144. this._vectors2[name] = value;
  68145. return this;
  68146. };
  68147. ProceduralTexture.prototype.setVector3 = function (name, value) {
  68148. this._checkUniform(name);
  68149. this._vectors3[name] = value;
  68150. return this;
  68151. };
  68152. ProceduralTexture.prototype.setMatrix = function (name, value) {
  68153. this._checkUniform(name);
  68154. this._matrices[name] = value;
  68155. return this;
  68156. };
  68157. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68158. var scene = this.getScene();
  68159. if (!scene) {
  68160. return;
  68161. }
  68162. var engine = this._engine;
  68163. // Render
  68164. engine.enableEffect(this._effect);
  68165. engine.setState(false);
  68166. // Texture
  68167. for (var name in this._textures) {
  68168. this._effect.setTexture(name, this._textures[name]);
  68169. }
  68170. // Float
  68171. for (name in this._floats) {
  68172. this._effect.setFloat(name, this._floats[name]);
  68173. }
  68174. // Floats
  68175. for (name in this._floatsArrays) {
  68176. this._effect.setArray(name, this._floatsArrays[name]);
  68177. }
  68178. // Color3
  68179. for (name in this._colors3) {
  68180. this._effect.setColor3(name, this._colors3[name]);
  68181. }
  68182. // Color4
  68183. for (name in this._colors4) {
  68184. var color = this._colors4[name];
  68185. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  68186. }
  68187. // Vector2
  68188. for (name in this._vectors2) {
  68189. this._effect.setVector2(name, this._vectors2[name]);
  68190. }
  68191. // Vector3
  68192. for (name in this._vectors3) {
  68193. this._effect.setVector3(name, this._vectors3[name]);
  68194. }
  68195. // Matrix
  68196. for (name in this._matrices) {
  68197. this._effect.setMatrix(name, this._matrices[name]);
  68198. }
  68199. if (!this._texture) {
  68200. return;
  68201. }
  68202. if (this.isCube) {
  68203. for (var face = 0; face < 6; face++) {
  68204. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  68205. // VBOs
  68206. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68207. this._effect.setFloat("face", face);
  68208. // Clear
  68209. engine.clear(scene.clearColor, true, true, true);
  68210. // Draw order
  68211. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68212. // Mipmaps
  68213. if (face === 5) {
  68214. engine.generateMipMapsForCubemap(this._texture);
  68215. }
  68216. }
  68217. }
  68218. else {
  68219. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  68220. // VBOs
  68221. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  68222. // Clear
  68223. engine.clear(scene.clearColor, true, true, true);
  68224. // Draw order
  68225. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68226. }
  68227. // Unbind
  68228. engine.unBindFramebuffer(this._texture, this.isCube);
  68229. if (this.onGenerated) {
  68230. this.onGenerated();
  68231. }
  68232. };
  68233. ProceduralTexture.prototype.clone = function () {
  68234. var textureSize = this.getSize();
  68235. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  68236. // Base texture
  68237. newTexture.hasAlpha = this.hasAlpha;
  68238. newTexture.level = this.level;
  68239. // RenderTarget Texture
  68240. newTexture.coordinatesMode = this.coordinatesMode;
  68241. return newTexture;
  68242. };
  68243. ProceduralTexture.prototype.dispose = function () {
  68244. var scene = this.getScene();
  68245. if (!scene) {
  68246. return;
  68247. }
  68248. var index = scene.proceduralTextures.indexOf(this);
  68249. if (index >= 0) {
  68250. scene.proceduralTextures.splice(index, 1);
  68251. }
  68252. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68253. if (vertexBuffer) {
  68254. vertexBuffer.dispose();
  68255. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68256. }
  68257. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  68258. this._indexBuffer = null;
  68259. }
  68260. _super.prototype.dispose.call(this);
  68261. };
  68262. return ProceduralTexture;
  68263. }(BABYLON.Texture));
  68264. BABYLON.ProceduralTexture = ProceduralTexture;
  68265. })(BABYLON || (BABYLON = {}));
  68266. //# sourceMappingURL=babylon.proceduralTexture.js.map
  68267. "use strict";
  68268. var BABYLON;
  68269. (function (BABYLON) {
  68270. var CustomProceduralTexture = /** @class */ (function (_super) {
  68271. __extends(CustomProceduralTexture, _super);
  68272. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  68273. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  68274. _this._animate = true;
  68275. _this._time = 0;
  68276. _this._texturePath = texturePath;
  68277. //Try to load json
  68278. _this.loadJson(texturePath);
  68279. _this.refreshRate = 1;
  68280. return _this;
  68281. }
  68282. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  68283. var _this = this;
  68284. var noConfigFile = function () {
  68285. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  68286. try {
  68287. _this.setFragment(_this._texturePath);
  68288. }
  68289. catch (ex) {
  68290. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  68291. }
  68292. };
  68293. var configFileUrl = jsonUrl + "/config.json";
  68294. var xhr = new XMLHttpRequest();
  68295. xhr.open("GET", configFileUrl, true);
  68296. xhr.addEventListener("load", function () {
  68297. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68298. try {
  68299. _this._config = JSON.parse(xhr.response);
  68300. _this.updateShaderUniforms();
  68301. _this.updateTextures();
  68302. _this.setFragment(_this._texturePath + "/custom");
  68303. _this._animate = _this._config.animate;
  68304. _this.refreshRate = _this._config.refreshrate;
  68305. }
  68306. catch (ex) {
  68307. noConfigFile();
  68308. }
  68309. }
  68310. else {
  68311. noConfigFile();
  68312. }
  68313. }, false);
  68314. xhr.addEventListener("error", function () {
  68315. noConfigFile();
  68316. }, false);
  68317. try {
  68318. xhr.send();
  68319. }
  68320. catch (ex) {
  68321. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  68322. }
  68323. };
  68324. CustomProceduralTexture.prototype.isReady = function () {
  68325. if (!_super.prototype.isReady.call(this)) {
  68326. return false;
  68327. }
  68328. for (var name in this._textures) {
  68329. var texture = this._textures[name];
  68330. if (!texture.isReady()) {
  68331. return false;
  68332. }
  68333. }
  68334. return true;
  68335. };
  68336. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  68337. var scene = this.getScene();
  68338. if (this._animate && scene) {
  68339. this._time += scene.getAnimationRatio() * 0.03;
  68340. this.updateShaderUniforms();
  68341. }
  68342. _super.prototype.render.call(this, useCameraPostProcess);
  68343. };
  68344. CustomProceduralTexture.prototype.updateTextures = function () {
  68345. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  68346. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  68347. }
  68348. };
  68349. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  68350. if (this._config) {
  68351. for (var j = 0; j < this._config.uniforms.length; j++) {
  68352. var uniform = this._config.uniforms[j];
  68353. switch (uniform.type) {
  68354. case "float":
  68355. this.setFloat(uniform.name, uniform.value);
  68356. break;
  68357. case "color3":
  68358. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  68359. break;
  68360. case "color4":
  68361. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  68362. break;
  68363. case "vector2":
  68364. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  68365. break;
  68366. case "vector3":
  68367. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  68368. break;
  68369. }
  68370. }
  68371. }
  68372. this.setFloat("time", this._time);
  68373. };
  68374. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  68375. get: function () {
  68376. return this._animate;
  68377. },
  68378. set: function (value) {
  68379. this._animate = value;
  68380. },
  68381. enumerable: true,
  68382. configurable: true
  68383. });
  68384. return CustomProceduralTexture;
  68385. }(BABYLON.ProceduralTexture));
  68386. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  68387. })(BABYLON || (BABYLON = {}));
  68388. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  68389. "use strict";
  68390. var BABYLON;
  68391. (function (BABYLON) {
  68392. var FreeCameraGamepadInput = /** @class */ (function () {
  68393. function FreeCameraGamepadInput() {
  68394. this.gamepadAngularSensibility = 200;
  68395. this.gamepadMoveSensibility = 40;
  68396. // private members
  68397. this._cameraTransform = BABYLON.Matrix.Identity();
  68398. this._deltaTransform = BABYLON.Vector3.Zero();
  68399. this._vector3 = BABYLON.Vector3.Zero();
  68400. this._vector2 = BABYLON.Vector2.Zero();
  68401. }
  68402. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68403. var _this = this;
  68404. var manager = this.camera.getScene().gamepadManager;
  68405. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68406. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68407. // prioritize XBOX gamepads.
  68408. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68409. _this.gamepad = gamepad;
  68410. }
  68411. }
  68412. });
  68413. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68414. if (_this.gamepad === gamepad) {
  68415. _this.gamepad = null;
  68416. }
  68417. });
  68418. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68419. };
  68420. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  68421. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68422. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68423. this.gamepad = null;
  68424. };
  68425. FreeCameraGamepadInput.prototype.checkInputs = function () {
  68426. if (this.gamepad && this.gamepad.leftStick) {
  68427. var camera = this.camera;
  68428. var LSValues = this.gamepad.leftStick;
  68429. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  68430. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68431. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  68432. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  68433. var RSValues = this.gamepad.rightStick;
  68434. if (RSValues) {
  68435. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  68436. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  68437. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  68438. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  68439. }
  68440. else {
  68441. RSValues = { x: 0, y: 0 };
  68442. }
  68443. if (!camera.rotationQuaternion) {
  68444. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  68445. }
  68446. else {
  68447. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  68448. }
  68449. var speed = camera._computeLocalCameraSpeed() * 50.0;
  68450. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  68451. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  68452. camera.cameraDirection.addInPlace(this._deltaTransform);
  68453. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  68454. camera.cameraRotation.addInPlace(this._vector2);
  68455. }
  68456. };
  68457. FreeCameraGamepadInput.prototype.getClassName = function () {
  68458. return "FreeCameraGamepadInput";
  68459. };
  68460. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  68461. return "gamepad";
  68462. };
  68463. __decorate([
  68464. BABYLON.serialize()
  68465. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  68466. __decorate([
  68467. BABYLON.serialize()
  68468. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68469. return FreeCameraGamepadInput;
  68470. }());
  68471. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  68472. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  68473. })(BABYLON || (BABYLON = {}));
  68474. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  68475. "use strict";
  68476. var BABYLON;
  68477. (function (BABYLON) {
  68478. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  68479. function ArcRotateCameraGamepadInput() {
  68480. this.gamepadRotationSensibility = 80;
  68481. this.gamepadMoveSensibility = 40;
  68482. }
  68483. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  68484. var _this = this;
  68485. var manager = this.camera.getScene().gamepadManager;
  68486. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  68487. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  68488. // prioritize XBOX gamepads.
  68489. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  68490. _this.gamepad = gamepad;
  68491. }
  68492. }
  68493. });
  68494. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  68495. if (_this.gamepad === gamepad) {
  68496. _this.gamepad = null;
  68497. }
  68498. });
  68499. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  68500. };
  68501. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  68502. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  68503. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  68504. this.gamepad = null;
  68505. };
  68506. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  68507. if (this.gamepad) {
  68508. var camera = this.camera;
  68509. var RSValues = this.gamepad.rightStick;
  68510. if (RSValues) {
  68511. if (RSValues.x != 0) {
  68512. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  68513. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  68514. camera.inertialAlphaOffset += normalizedRX;
  68515. }
  68516. }
  68517. if (RSValues.y != 0) {
  68518. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  68519. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  68520. camera.inertialBetaOffset += normalizedRY;
  68521. }
  68522. }
  68523. }
  68524. var LSValues = this.gamepad.leftStick;
  68525. if (LSValues && LSValues.y != 0) {
  68526. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  68527. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  68528. this.camera.inertialRadiusOffset -= normalizedLY;
  68529. }
  68530. }
  68531. }
  68532. };
  68533. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  68534. return "ArcRotateCameraGamepadInput";
  68535. };
  68536. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  68537. return "gamepad";
  68538. };
  68539. __decorate([
  68540. BABYLON.serialize()
  68541. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  68542. __decorate([
  68543. BABYLON.serialize()
  68544. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  68545. return ArcRotateCameraGamepadInput;
  68546. }());
  68547. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  68548. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  68549. })(BABYLON || (BABYLON = {}));
  68550. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  68551. "use strict";
  68552. var BABYLON;
  68553. (function (BABYLON) {
  68554. var GamepadManager = /** @class */ (function () {
  68555. function GamepadManager(_scene) {
  68556. var _this = this;
  68557. this._scene = _scene;
  68558. this._babylonGamepads = [];
  68559. this._oneGamepadConnected = false;
  68560. this._isMonitoring = false;
  68561. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  68562. if (!BABYLON.Tools.IsWindowObjectExist()) {
  68563. this._gamepadEventSupported = false;
  68564. }
  68565. else {
  68566. this._gamepadEventSupported = 'GamepadEvent' in window;
  68567. this._gamepadSupport = (navigator.getGamepads ||
  68568. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  68569. }
  68570. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  68571. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  68572. for (var i in _this._babylonGamepads) {
  68573. var gamepad = _this._babylonGamepads[i];
  68574. if (gamepad && gamepad._isConnected) {
  68575. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  68576. }
  68577. }
  68578. });
  68579. this._onGamepadConnectedEvent = function (evt) {
  68580. var gamepad = evt.gamepad;
  68581. if (gamepad.index in _this._babylonGamepads) {
  68582. if (_this._babylonGamepads[gamepad.index].isConnected) {
  68583. return;
  68584. }
  68585. }
  68586. var newGamepad;
  68587. if (_this._babylonGamepads[gamepad.index]) {
  68588. newGamepad = _this._babylonGamepads[gamepad.index];
  68589. newGamepad.browserGamepad = gamepad;
  68590. newGamepad._isConnected = true;
  68591. }
  68592. else {
  68593. newGamepad = _this._addNewGamepad(gamepad);
  68594. }
  68595. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68596. _this._startMonitoringGamepads();
  68597. };
  68598. this._onGamepadDisconnectedEvent = function (evt) {
  68599. var gamepad = evt.gamepad;
  68600. // Remove the gamepad from the list of gamepads to monitor.
  68601. for (var i in _this._babylonGamepads) {
  68602. if (_this._babylonGamepads[i].index === gamepad.index) {
  68603. var disconnectedGamepad = _this._babylonGamepads[i];
  68604. disconnectedGamepad._isConnected = false;
  68605. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  68606. break;
  68607. }
  68608. }
  68609. };
  68610. if (this._gamepadSupport) {
  68611. //first add already-connected gamepads
  68612. this._updateGamepadObjects();
  68613. if (this._babylonGamepads.length) {
  68614. this._startMonitoringGamepads();
  68615. }
  68616. // Checking if the gamepad connected event is supported (like in Firefox)
  68617. if (this._gamepadEventSupported) {
  68618. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  68619. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  68620. }
  68621. else {
  68622. this._startMonitoringGamepads();
  68623. }
  68624. }
  68625. }
  68626. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  68627. get: function () {
  68628. return this._babylonGamepads;
  68629. },
  68630. enumerable: true,
  68631. configurable: true
  68632. });
  68633. GamepadManager.prototype.getGamepadByType = function (type) {
  68634. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  68635. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  68636. var gamepad = _a[_i];
  68637. if (gamepad && gamepad.type === type) {
  68638. return gamepad;
  68639. }
  68640. }
  68641. return null;
  68642. };
  68643. GamepadManager.prototype.dispose = function () {
  68644. if (this._gamepadEventSupported) {
  68645. if (this._onGamepadConnectedEvent) {
  68646. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  68647. }
  68648. if (this._onGamepadDisconnectedEvent) {
  68649. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  68650. }
  68651. this._onGamepadConnectedEvent = null;
  68652. this._onGamepadDisconnectedEvent = null;
  68653. }
  68654. this._babylonGamepads.forEach(function (gamepad) {
  68655. gamepad.dispose();
  68656. });
  68657. this.onGamepadConnectedObservable.clear();
  68658. this.onGamepadDisconnectedObservable.clear();
  68659. this._oneGamepadConnected = false;
  68660. this._stopMonitoringGamepads();
  68661. this._babylonGamepads = [];
  68662. };
  68663. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  68664. if (!this._oneGamepadConnected) {
  68665. this._oneGamepadConnected = true;
  68666. }
  68667. var newGamepad;
  68668. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  68669. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  68670. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  68671. }
  68672. else if (gamepad.pose) {
  68673. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  68674. }
  68675. else {
  68676. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  68677. }
  68678. this._babylonGamepads[newGamepad.index] = newGamepad;
  68679. return newGamepad;
  68680. };
  68681. GamepadManager.prototype._startMonitoringGamepads = function () {
  68682. if (!this._isMonitoring) {
  68683. this._isMonitoring = true;
  68684. //back-comp
  68685. if (!this._scene) {
  68686. this._checkGamepadsStatus();
  68687. }
  68688. }
  68689. };
  68690. GamepadManager.prototype._stopMonitoringGamepads = function () {
  68691. this._isMonitoring = false;
  68692. };
  68693. GamepadManager.prototype._checkGamepadsStatus = function () {
  68694. var _this = this;
  68695. // Hack to be compatible Chrome
  68696. this._updateGamepadObjects();
  68697. for (var i in this._babylonGamepads) {
  68698. var gamepad = this._babylonGamepads[i];
  68699. if (!gamepad || !gamepad.isConnected) {
  68700. continue;
  68701. }
  68702. gamepad.update();
  68703. }
  68704. if (this._isMonitoring && !this._scene) {
  68705. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  68706. }
  68707. };
  68708. // This function is called only on Chrome, which does not properly support
  68709. // connection/disconnection events and forces you to recopy again the gamepad object
  68710. GamepadManager.prototype._updateGamepadObjects = function () {
  68711. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  68712. for (var i = 0; i < gamepads.length; i++) {
  68713. if (gamepads[i]) {
  68714. if (!this._babylonGamepads[gamepads[i].index]) {
  68715. var newGamepad = this._addNewGamepad(gamepads[i]);
  68716. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  68717. }
  68718. else {
  68719. // Forced to copy again this object for Chrome for unknown reason
  68720. this._babylonGamepads[i].browserGamepad = gamepads[i];
  68721. if (!this._babylonGamepads[i].isConnected) {
  68722. this._babylonGamepads[i]._isConnected = true;
  68723. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  68724. }
  68725. }
  68726. }
  68727. }
  68728. };
  68729. return GamepadManager;
  68730. }());
  68731. BABYLON.GamepadManager = GamepadManager;
  68732. })(BABYLON || (BABYLON = {}));
  68733. //# sourceMappingURL=babylon.gamepadManager.js.map
  68734. "use strict";
  68735. var BABYLON;
  68736. (function (BABYLON) {
  68737. var StickValues = /** @class */ (function () {
  68738. function StickValues(x, y) {
  68739. this.x = x;
  68740. this.y = y;
  68741. }
  68742. return StickValues;
  68743. }());
  68744. BABYLON.StickValues = StickValues;
  68745. var Gamepad = /** @class */ (function () {
  68746. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  68747. if (leftStickX === void 0) { leftStickX = 0; }
  68748. if (leftStickY === void 0) { leftStickY = 1; }
  68749. if (rightStickX === void 0) { rightStickX = 2; }
  68750. if (rightStickY === void 0) { rightStickY = 3; }
  68751. this.id = id;
  68752. this.index = index;
  68753. this.browserGamepad = browserGamepad;
  68754. this._isConnected = true;
  68755. this._invertLeftStickY = false;
  68756. this.type = Gamepad.GAMEPAD;
  68757. this._leftStickAxisX = leftStickX;
  68758. this._leftStickAxisY = leftStickY;
  68759. this._rightStickAxisX = rightStickX;
  68760. this._rightStickAxisY = rightStickY;
  68761. if (this.browserGamepad.axes.length >= 2) {
  68762. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  68763. }
  68764. if (this.browserGamepad.axes.length >= 4) {
  68765. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  68766. }
  68767. }
  68768. Object.defineProperty(Gamepad.prototype, "isConnected", {
  68769. get: function () {
  68770. return this._isConnected;
  68771. },
  68772. enumerable: true,
  68773. configurable: true
  68774. });
  68775. Gamepad.prototype.onleftstickchanged = function (callback) {
  68776. this._onleftstickchanged = callback;
  68777. };
  68778. Gamepad.prototype.onrightstickchanged = function (callback) {
  68779. this._onrightstickchanged = callback;
  68780. };
  68781. Object.defineProperty(Gamepad.prototype, "leftStick", {
  68782. get: function () {
  68783. return this._leftStick;
  68784. },
  68785. set: function (newValues) {
  68786. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  68787. this._onleftstickchanged(newValues);
  68788. }
  68789. this._leftStick = newValues;
  68790. },
  68791. enumerable: true,
  68792. configurable: true
  68793. });
  68794. Object.defineProperty(Gamepad.prototype, "rightStick", {
  68795. get: function () {
  68796. return this._rightStick;
  68797. },
  68798. set: function (newValues) {
  68799. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  68800. this._onrightstickchanged(newValues);
  68801. }
  68802. this._rightStick = newValues;
  68803. },
  68804. enumerable: true,
  68805. configurable: true
  68806. });
  68807. Gamepad.prototype.update = function () {
  68808. if (this._leftStick) {
  68809. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  68810. if (this._invertLeftStickY) {
  68811. this.leftStick.y *= -1;
  68812. }
  68813. }
  68814. if (this._rightStick) {
  68815. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  68816. }
  68817. };
  68818. Gamepad.prototype.dispose = function () {
  68819. };
  68820. Gamepad.GAMEPAD = 0;
  68821. Gamepad.GENERIC = 1;
  68822. Gamepad.XBOX = 2;
  68823. Gamepad.POSE_ENABLED = 3;
  68824. return Gamepad;
  68825. }());
  68826. BABYLON.Gamepad = Gamepad;
  68827. var GenericPad = /** @class */ (function (_super) {
  68828. __extends(GenericPad, _super);
  68829. function GenericPad(id, index, browserGamepad) {
  68830. var _this = _super.call(this, id, index, browserGamepad) || this;
  68831. _this.onButtonDownObservable = new BABYLON.Observable();
  68832. _this.onButtonUpObservable = new BABYLON.Observable();
  68833. _this.type = Gamepad.GENERIC;
  68834. _this._buttons = new Array(browserGamepad.buttons.length);
  68835. return _this;
  68836. }
  68837. GenericPad.prototype.onbuttondown = function (callback) {
  68838. this._onbuttondown = callback;
  68839. };
  68840. GenericPad.prototype.onbuttonup = function (callback) {
  68841. this._onbuttonup = callback;
  68842. };
  68843. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  68844. if (newValue !== currentValue) {
  68845. if (newValue === 1) {
  68846. if (this._onbuttondown) {
  68847. this._onbuttondown(buttonIndex);
  68848. }
  68849. this.onButtonDownObservable.notifyObservers(buttonIndex);
  68850. }
  68851. if (newValue === 0) {
  68852. if (this._onbuttonup) {
  68853. this._onbuttonup(buttonIndex);
  68854. }
  68855. this.onButtonUpObservable.notifyObservers(buttonIndex);
  68856. }
  68857. }
  68858. return newValue;
  68859. };
  68860. GenericPad.prototype.update = function () {
  68861. _super.prototype.update.call(this);
  68862. for (var index = 0; index < this._buttons.length; index++) {
  68863. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  68864. }
  68865. };
  68866. GenericPad.prototype.dispose = function () {
  68867. _super.prototype.dispose.call(this);
  68868. this.onButtonDownObservable.clear();
  68869. this.onButtonUpObservable.clear();
  68870. };
  68871. return GenericPad;
  68872. }(Gamepad));
  68873. BABYLON.GenericPad = GenericPad;
  68874. })(BABYLON || (BABYLON = {}));
  68875. //# sourceMappingURL=babylon.gamepad.js.map
  68876. "use strict";
  68877. var BABYLON;
  68878. (function (BABYLON) {
  68879. var Xbox360Button;
  68880. (function (Xbox360Button) {
  68881. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  68882. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  68883. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  68884. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  68885. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  68886. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  68887. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  68888. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  68889. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  68890. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  68891. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  68892. var Xbox360Dpad;
  68893. (function (Xbox360Dpad) {
  68894. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  68895. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  68896. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  68897. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  68898. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  68899. var Xbox360Pad = /** @class */ (function (_super) {
  68900. __extends(Xbox360Pad, _super);
  68901. function Xbox360Pad(id, index, gamepad, xboxOne) {
  68902. if (xboxOne === void 0) { xboxOne = false; }
  68903. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  68904. _this._leftTrigger = 0;
  68905. _this._rightTrigger = 0;
  68906. _this.onButtonDownObservable = new BABYLON.Observable();
  68907. _this.onButtonUpObservable = new BABYLON.Observable();
  68908. _this.onPadDownObservable = new BABYLON.Observable();
  68909. _this.onPadUpObservable = new BABYLON.Observable();
  68910. _this._buttonA = 0;
  68911. _this._buttonB = 0;
  68912. _this._buttonX = 0;
  68913. _this._buttonY = 0;
  68914. _this._buttonBack = 0;
  68915. _this._buttonStart = 0;
  68916. _this._buttonLB = 0;
  68917. _this._buttonRB = 0;
  68918. _this._buttonLeftStick = 0;
  68919. _this._buttonRightStick = 0;
  68920. _this._dPadUp = 0;
  68921. _this._dPadDown = 0;
  68922. _this._dPadLeft = 0;
  68923. _this._dPadRight = 0;
  68924. _this._isXboxOnePad = false;
  68925. _this.type = BABYLON.Gamepad.XBOX;
  68926. _this._isXboxOnePad = xboxOne;
  68927. return _this;
  68928. }
  68929. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  68930. this._onlefttriggerchanged = callback;
  68931. };
  68932. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  68933. this._onrighttriggerchanged = callback;
  68934. };
  68935. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  68936. get: function () {
  68937. return this._leftTrigger;
  68938. },
  68939. set: function (newValue) {
  68940. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  68941. this._onlefttriggerchanged(newValue);
  68942. }
  68943. this._leftTrigger = newValue;
  68944. },
  68945. enumerable: true,
  68946. configurable: true
  68947. });
  68948. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  68949. get: function () {
  68950. return this._rightTrigger;
  68951. },
  68952. set: function (newValue) {
  68953. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  68954. this._onrighttriggerchanged(newValue);
  68955. }
  68956. this._rightTrigger = newValue;
  68957. },
  68958. enumerable: true,
  68959. configurable: true
  68960. });
  68961. Xbox360Pad.prototype.onbuttondown = function (callback) {
  68962. this._onbuttondown = callback;
  68963. };
  68964. Xbox360Pad.prototype.onbuttonup = function (callback) {
  68965. this._onbuttonup = callback;
  68966. };
  68967. Xbox360Pad.prototype.ondpaddown = function (callback) {
  68968. this._ondpaddown = callback;
  68969. };
  68970. Xbox360Pad.prototype.ondpadup = function (callback) {
  68971. this._ondpadup = callback;
  68972. };
  68973. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  68974. if (newValue !== currentValue) {
  68975. if (newValue === 1) {
  68976. if (this._onbuttondown) {
  68977. this._onbuttondown(buttonType);
  68978. }
  68979. this.onButtonDownObservable.notifyObservers(buttonType);
  68980. }
  68981. if (newValue === 0) {
  68982. if (this._onbuttonup) {
  68983. this._onbuttonup(buttonType);
  68984. }
  68985. this.onButtonUpObservable.notifyObservers(buttonType);
  68986. }
  68987. }
  68988. return newValue;
  68989. };
  68990. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  68991. if (newValue !== currentValue) {
  68992. if (newValue === 1) {
  68993. if (this._ondpaddown) {
  68994. this._ondpaddown(buttonType);
  68995. }
  68996. this.onPadDownObservable.notifyObservers(buttonType);
  68997. }
  68998. if (newValue === 0) {
  68999. if (this._ondpadup) {
  69000. this._ondpadup(buttonType);
  69001. }
  69002. this.onPadUpObservable.notifyObservers(buttonType);
  69003. }
  69004. }
  69005. return newValue;
  69006. };
  69007. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  69008. get: function () {
  69009. return this._buttonA;
  69010. },
  69011. set: function (value) {
  69012. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  69013. },
  69014. enumerable: true,
  69015. configurable: true
  69016. });
  69017. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  69018. get: function () {
  69019. return this._buttonB;
  69020. },
  69021. set: function (value) {
  69022. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  69023. },
  69024. enumerable: true,
  69025. configurable: true
  69026. });
  69027. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  69028. get: function () {
  69029. return this._buttonX;
  69030. },
  69031. set: function (value) {
  69032. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  69033. },
  69034. enumerable: true,
  69035. configurable: true
  69036. });
  69037. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  69038. get: function () {
  69039. return this._buttonY;
  69040. },
  69041. set: function (value) {
  69042. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  69043. },
  69044. enumerable: true,
  69045. configurable: true
  69046. });
  69047. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  69048. get: function () {
  69049. return this._buttonStart;
  69050. },
  69051. set: function (value) {
  69052. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  69053. },
  69054. enumerable: true,
  69055. configurable: true
  69056. });
  69057. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  69058. get: function () {
  69059. return this._buttonBack;
  69060. },
  69061. set: function (value) {
  69062. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  69063. },
  69064. enumerable: true,
  69065. configurable: true
  69066. });
  69067. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  69068. get: function () {
  69069. return this._buttonLB;
  69070. },
  69071. set: function (value) {
  69072. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  69073. },
  69074. enumerable: true,
  69075. configurable: true
  69076. });
  69077. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  69078. get: function () {
  69079. return this._buttonRB;
  69080. },
  69081. set: function (value) {
  69082. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  69083. },
  69084. enumerable: true,
  69085. configurable: true
  69086. });
  69087. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  69088. get: function () {
  69089. return this._buttonLeftStick;
  69090. },
  69091. set: function (value) {
  69092. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  69093. },
  69094. enumerable: true,
  69095. configurable: true
  69096. });
  69097. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  69098. get: function () {
  69099. return this._buttonRightStick;
  69100. },
  69101. set: function (value) {
  69102. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  69103. },
  69104. enumerable: true,
  69105. configurable: true
  69106. });
  69107. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  69108. get: function () {
  69109. return this._dPadUp;
  69110. },
  69111. set: function (value) {
  69112. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  69113. },
  69114. enumerable: true,
  69115. configurable: true
  69116. });
  69117. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  69118. get: function () {
  69119. return this._dPadDown;
  69120. },
  69121. set: function (value) {
  69122. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  69123. },
  69124. enumerable: true,
  69125. configurable: true
  69126. });
  69127. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  69128. get: function () {
  69129. return this._dPadLeft;
  69130. },
  69131. set: function (value) {
  69132. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  69133. },
  69134. enumerable: true,
  69135. configurable: true
  69136. });
  69137. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  69138. get: function () {
  69139. return this._dPadRight;
  69140. },
  69141. set: function (value) {
  69142. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  69143. },
  69144. enumerable: true,
  69145. configurable: true
  69146. });
  69147. Xbox360Pad.prototype.update = function () {
  69148. _super.prototype.update.call(this);
  69149. if (this._isXboxOnePad) {
  69150. this.buttonA = this.browserGamepad.buttons[0].value;
  69151. this.buttonB = this.browserGamepad.buttons[1].value;
  69152. this.buttonX = this.browserGamepad.buttons[2].value;
  69153. this.buttonY = this.browserGamepad.buttons[3].value;
  69154. this.buttonLB = this.browserGamepad.buttons[4].value;
  69155. this.buttonRB = this.browserGamepad.buttons[5].value;
  69156. this.leftTrigger = this.browserGamepad.axes[2];
  69157. this.rightTrigger = this.browserGamepad.axes[5];
  69158. this.buttonBack = this.browserGamepad.buttons[9].value;
  69159. this.buttonStart = this.browserGamepad.buttons[8].value;
  69160. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  69161. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  69162. this.dPadUp = this.browserGamepad.buttons[11].value;
  69163. this.dPadDown = this.browserGamepad.buttons[12].value;
  69164. this.dPadLeft = this.browserGamepad.buttons[13].value;
  69165. this.dPadRight = this.browserGamepad.buttons[14].value;
  69166. }
  69167. else {
  69168. this.buttonA = this.browserGamepad.buttons[0].value;
  69169. this.buttonB = this.browserGamepad.buttons[1].value;
  69170. this.buttonX = this.browserGamepad.buttons[2].value;
  69171. this.buttonY = this.browserGamepad.buttons[3].value;
  69172. this.buttonLB = this.browserGamepad.buttons[4].value;
  69173. this.buttonRB = this.browserGamepad.buttons[5].value;
  69174. this.leftTrigger = this.browserGamepad.buttons[6].value;
  69175. this.rightTrigger = this.browserGamepad.buttons[7].value;
  69176. this.buttonBack = this.browserGamepad.buttons[8].value;
  69177. this.buttonStart = this.browserGamepad.buttons[9].value;
  69178. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  69179. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  69180. this.dPadUp = this.browserGamepad.buttons[12].value;
  69181. this.dPadDown = this.browserGamepad.buttons[13].value;
  69182. this.dPadLeft = this.browserGamepad.buttons[14].value;
  69183. this.dPadRight = this.browserGamepad.buttons[15].value;
  69184. }
  69185. };
  69186. Xbox360Pad.prototype.dispose = function () {
  69187. _super.prototype.dispose.call(this);
  69188. this.onButtonDownObservable.clear();
  69189. this.onButtonUpObservable.clear();
  69190. this.onPadDownObservable.clear();
  69191. this.onPadUpObservable.clear();
  69192. };
  69193. return Xbox360Pad;
  69194. }(BABYLON.Gamepad));
  69195. BABYLON.Xbox360Pad = Xbox360Pad;
  69196. })(BABYLON || (BABYLON = {}));
  69197. //# sourceMappingURL=babylon.xboxGamepad.js.map
  69198. "use strict";
  69199. var BABYLON;
  69200. (function (BABYLON) {
  69201. /**
  69202. * Defines the types of pose enabled controllers that are supported
  69203. */
  69204. var PoseEnabledControllerType;
  69205. (function (PoseEnabledControllerType) {
  69206. /**
  69207. * HTC Vive
  69208. */
  69209. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  69210. /**
  69211. * Oculus Rift
  69212. */
  69213. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  69214. /**
  69215. * Windows mixed reality
  69216. */
  69217. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  69218. /**
  69219. * Samsung gear VR
  69220. */
  69221. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  69222. /**
  69223. * Google Daydream
  69224. */
  69225. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  69226. /**
  69227. * Generic
  69228. */
  69229. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  69230. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  69231. /**
  69232. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69233. */
  69234. var PoseEnabledControllerHelper = /** @class */ (function () {
  69235. function PoseEnabledControllerHelper() {
  69236. }
  69237. /**
  69238. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  69239. * @param vrGamepad the gamepad to initialized
  69240. * @returns a vr controller of the type the gamepad identified as
  69241. */
  69242. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  69243. // Oculus Touch
  69244. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  69245. return new BABYLON.OculusTouchController(vrGamepad);
  69246. }
  69247. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  69248. return new BABYLON.WindowsMotionController(vrGamepad);
  69249. }
  69250. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  69251. return new BABYLON.ViveController(vrGamepad);
  69252. }
  69253. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  69254. return new BABYLON.GearVRController(vrGamepad);
  69255. }
  69256. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  69257. return new BABYLON.DaydreamController(vrGamepad);
  69258. }
  69259. else {
  69260. return new BABYLON.GenericController(vrGamepad);
  69261. }
  69262. };
  69263. return PoseEnabledControllerHelper;
  69264. }());
  69265. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  69266. /**
  69267. * Defines the PoseEnabledController object that contains state of a vr capable controller
  69268. */
  69269. var PoseEnabledController = /** @class */ (function (_super) {
  69270. __extends(PoseEnabledController, _super);
  69271. /**
  69272. * Creates a new PoseEnabledController from a gamepad
  69273. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  69274. */
  69275. function PoseEnabledController(browserGamepad) {
  69276. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  69277. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  69278. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  69279. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  69280. /**
  69281. * The device position in babylon space
  69282. */
  69283. _this.devicePosition = BABYLON.Vector3.Zero();
  69284. /**
  69285. * The device rotation in babylon space
  69286. */
  69287. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69288. /**
  69289. * The scale factor of the device in babylon space
  69290. */
  69291. _this.deviceScaleFactor = 1;
  69292. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  69293. /**
  69294. * Internal, matrix used to convert room space to babylon space
  69295. */
  69296. _this._deviceToWorld = BABYLON.Matrix.Identity();
  69297. /**
  69298. * Node to be used when casting a ray from the controller
  69299. */
  69300. _this._pointingPoseNode = null;
  69301. _this._workingMatrix = BABYLON.Matrix.Identity();
  69302. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  69303. _this.controllerType = PoseEnabledControllerType.GENERIC;
  69304. _this.position = BABYLON.Vector3.Zero();
  69305. _this.rotationQuaternion = new BABYLON.Quaternion();
  69306. _this._calculatedPosition = BABYLON.Vector3.Zero();
  69307. _this._calculatedRotation = new BABYLON.Quaternion();
  69308. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  69309. return _this;
  69310. }
  69311. /**
  69312. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  69313. */
  69314. PoseEnabledController.prototype.update = function () {
  69315. _super.prototype.update.call(this);
  69316. var pose = this.browserGamepad.pose;
  69317. this.updateFromDevice(pose);
  69318. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  69319. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  69320. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  69321. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  69322. if (this._mesh) {
  69323. this._mesh.position.copyFrom(this.devicePosition);
  69324. if (this._mesh.rotationQuaternion) {
  69325. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69326. }
  69327. }
  69328. };
  69329. /**
  69330. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  69331. * @param poseData raw pose fromthe device
  69332. */
  69333. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  69334. if (poseData) {
  69335. this.rawPose = poseData;
  69336. if (poseData.position) {
  69337. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  69338. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  69339. this._deviceRoomPosition.z *= -1;
  69340. }
  69341. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  69342. this._calculatedPosition.addInPlace(this.position);
  69343. }
  69344. var pose = this.rawPose;
  69345. if (poseData.orientation && pose.orientation) {
  69346. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  69347. if (this._mesh) {
  69348. if (this._mesh.getScene().useRightHandedSystem) {
  69349. this._deviceRoomRotationQuaternion.z *= -1;
  69350. this._deviceRoomRotationQuaternion.w *= -1;
  69351. }
  69352. else {
  69353. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  69354. }
  69355. }
  69356. // if the camera is set, rotate to the camera's rotation
  69357. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  69358. }
  69359. }
  69360. };
  69361. /**
  69362. * Attaches a mesh to the controller
  69363. * @param mesh the mesh to be attached
  69364. */
  69365. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  69366. if (this._mesh) {
  69367. this._mesh.parent = null;
  69368. }
  69369. this._mesh = mesh;
  69370. if (this._poseControlledCamera) {
  69371. this._mesh.parent = this._poseControlledCamera;
  69372. }
  69373. if (!this._mesh.rotationQuaternion) {
  69374. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  69375. }
  69376. };
  69377. /**
  69378. * Attaches the controllers mesh to a camera
  69379. * @param camera the camera the mesh should be attached to
  69380. */
  69381. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  69382. this._poseControlledCamera = camera;
  69383. if (this._mesh) {
  69384. this._mesh.parent = this._poseControlledCamera;
  69385. }
  69386. };
  69387. /**
  69388. * Disposes of the controller
  69389. */
  69390. PoseEnabledController.prototype.dispose = function () {
  69391. if (this._mesh) {
  69392. this._mesh.dispose();
  69393. }
  69394. this._mesh = null;
  69395. _super.prototype.dispose.call(this);
  69396. };
  69397. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  69398. /**
  69399. * The mesh that is attached to the controller
  69400. */
  69401. get: function () {
  69402. return this._mesh;
  69403. },
  69404. enumerable: true,
  69405. configurable: true
  69406. });
  69407. /**
  69408. * Gets the ray of the controller in the direction the controller is pointing
  69409. * @param length the length the resulting ray should be
  69410. * @returns a ray in the direction the controller is pointing
  69411. */
  69412. PoseEnabledController.prototype.getForwardRay = function (length) {
  69413. if (length === void 0) { length = 100; }
  69414. if (!this.mesh) {
  69415. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  69416. }
  69417. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  69418. var origin = m.getTranslation();
  69419. var forward = new BABYLON.Vector3(0, 0, -1);
  69420. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  69421. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  69422. return new BABYLON.Ray(origin, direction, length);
  69423. };
  69424. /**
  69425. * Name of the child mesh that can be used to cast a ray from the controller
  69426. */
  69427. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  69428. return PoseEnabledController;
  69429. }(BABYLON.Gamepad));
  69430. BABYLON.PoseEnabledController = PoseEnabledController;
  69431. })(BABYLON || (BABYLON = {}));
  69432. //# sourceMappingURL=babylon.poseEnabledController.js.map
  69433. "use strict";
  69434. var BABYLON;
  69435. (function (BABYLON) {
  69436. /**
  69437. * Defines the WebVRController object that represents controllers tracked in 3D space
  69438. */
  69439. var WebVRController = /** @class */ (function (_super) {
  69440. __extends(WebVRController, _super);
  69441. /**
  69442. * Creates a new WebVRController from a gamepad
  69443. * @param vrGamepad the gamepad that the WebVRController should be created from
  69444. */
  69445. function WebVRController(vrGamepad) {
  69446. var _this = _super.call(this, vrGamepad) || this;
  69447. // Observables
  69448. /**
  69449. * Fired when the trigger state has changed
  69450. */
  69451. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  69452. /**
  69453. * Fired when the main button state has changed
  69454. */
  69455. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  69456. /**
  69457. * Fired when the secondary button state has changed
  69458. */
  69459. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  69460. /**
  69461. * Fired when the pad state has changed
  69462. */
  69463. _this.onPadStateChangedObservable = new BABYLON.Observable();
  69464. /**
  69465. * Fired when controllers stick values have changed
  69466. */
  69467. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  69468. /**
  69469. * X and Y axis corrisponding to the controllers joystick
  69470. */
  69471. _this.pad = { x: 0, y: 0 };
  69472. // avoid GC, store state in a tmp object
  69473. _this._changes = {
  69474. pressChanged: false,
  69475. touchChanged: false,
  69476. valueChanged: false,
  69477. changed: false
  69478. };
  69479. _this._buttons = new Array(vrGamepad.buttons.length);
  69480. _this.hand = vrGamepad.hand;
  69481. return _this;
  69482. }
  69483. /**
  69484. * Fired when a controller button's state has changed
  69485. * @param callback the callback containing the button that was modified
  69486. */
  69487. WebVRController.prototype.onButtonStateChange = function (callback) {
  69488. this._onButtonStateChange = callback;
  69489. };
  69490. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  69491. /**
  69492. * The default controller model for the controller
  69493. */
  69494. get: function () {
  69495. return this._defaultModel;
  69496. },
  69497. enumerable: true,
  69498. configurable: true
  69499. });
  69500. /**
  69501. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  69502. */
  69503. WebVRController.prototype.update = function () {
  69504. _super.prototype.update.call(this);
  69505. for (var index = 0; index < this._buttons.length; index++) {
  69506. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  69507. }
  69508. ;
  69509. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  69510. this.pad.x = this.leftStick.x;
  69511. this.pad.y = this.leftStick.y;
  69512. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  69513. }
  69514. };
  69515. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  69516. if (!newState) {
  69517. newState = {
  69518. pressed: false,
  69519. touched: false,
  69520. value: 0
  69521. };
  69522. }
  69523. if (!currentState) {
  69524. this._buttons[buttonIndex] = {
  69525. pressed: newState.pressed,
  69526. touched: newState.touched,
  69527. value: newState.value
  69528. };
  69529. return;
  69530. }
  69531. this._checkChanges(newState, currentState);
  69532. if (this._changes.changed) {
  69533. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  69534. this._handleButtonChange(buttonIndex, newState, this._changes);
  69535. }
  69536. this._buttons[buttonIndex].pressed = newState.pressed;
  69537. this._buttons[buttonIndex].touched = newState.touched;
  69538. // oculus triggers are never 0, thou not touched.
  69539. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  69540. };
  69541. WebVRController.prototype._checkChanges = function (newState, currentState) {
  69542. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  69543. this._changes.touchChanged = newState.touched !== currentState.touched;
  69544. this._changes.valueChanged = newState.value !== currentState.value;
  69545. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  69546. return this._changes;
  69547. };
  69548. /**
  69549. * Disposes of th webVRCOntroller
  69550. */
  69551. WebVRController.prototype.dispose = function () {
  69552. _super.prototype.dispose.call(this);
  69553. this.onTriggerStateChangedObservable.clear();
  69554. this.onMainButtonStateChangedObservable.clear();
  69555. this.onSecondaryButtonStateChangedObservable.clear();
  69556. this.onPadStateChangedObservable.clear();
  69557. this.onPadValuesChangedObservable.clear();
  69558. };
  69559. return WebVRController;
  69560. }(BABYLON.PoseEnabledController));
  69561. BABYLON.WebVRController = WebVRController;
  69562. })(BABYLON || (BABYLON = {}));
  69563. //# sourceMappingURL=babylon.webVRController.js.map
  69564. "use strict";
  69565. var BABYLON;
  69566. (function (BABYLON) {
  69567. /**
  69568. * Oculus Touch Controller
  69569. */
  69570. var OculusTouchController = /** @class */ (function (_super) {
  69571. __extends(OculusTouchController, _super);
  69572. /**
  69573. * Creates a new OculusTouchController from a gamepad
  69574. * @param vrGamepad the gamepad that the controller should be created from
  69575. */
  69576. function OculusTouchController(vrGamepad) {
  69577. var _this = _super.call(this, vrGamepad) || this;
  69578. /**
  69579. * Fired when the secondary trigger on this controller is modified
  69580. */
  69581. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  69582. /**
  69583. * Fired when the thumb rest on this controller is modified
  69584. */
  69585. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  69586. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  69587. return _this;
  69588. }
  69589. /**
  69590. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69591. * @param scene scene in which to add meshes
  69592. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69593. */
  69594. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69595. var _this = this;
  69596. var meshName;
  69597. // Hand
  69598. if (this.hand === 'left') {
  69599. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  69600. }
  69601. else {
  69602. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  69603. }
  69604. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  69605. /*
  69606. Parent Mesh name: oculus_touch_left
  69607. - body
  69608. - trigger
  69609. - thumbstick
  69610. - grip
  69611. - button_y
  69612. - button_x
  69613. - button_enter
  69614. */
  69615. _this._defaultModel = newMeshes[1];
  69616. _this.attachToMesh(_this._defaultModel);
  69617. if (meshLoaded) {
  69618. meshLoaded(_this._defaultModel);
  69619. }
  69620. });
  69621. };
  69622. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  69623. /**
  69624. * Fired when the A button on this controller is modified
  69625. */
  69626. get: function () {
  69627. if (this.hand === 'right') {
  69628. return this.onMainButtonStateChangedObservable;
  69629. }
  69630. else {
  69631. throw new Error('No A button on left hand');
  69632. }
  69633. },
  69634. enumerable: true,
  69635. configurable: true
  69636. });
  69637. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  69638. /**
  69639. * Fired when the B button on this controller is modified
  69640. */
  69641. get: function () {
  69642. if (this.hand === 'right') {
  69643. return this.onSecondaryButtonStateChangedObservable;
  69644. }
  69645. else {
  69646. throw new Error('No B button on left hand');
  69647. }
  69648. },
  69649. enumerable: true,
  69650. configurable: true
  69651. });
  69652. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  69653. /**
  69654. * Fired when the X button on this controller is modified
  69655. */
  69656. get: function () {
  69657. if (this.hand === 'left') {
  69658. return this.onMainButtonStateChangedObservable;
  69659. }
  69660. else {
  69661. throw new Error('No X button on right hand');
  69662. }
  69663. },
  69664. enumerable: true,
  69665. configurable: true
  69666. });
  69667. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  69668. /**
  69669. * Fired when the Y button on this controller is modified
  69670. */
  69671. get: function () {
  69672. if (this.hand === 'left') {
  69673. return this.onSecondaryButtonStateChangedObservable;
  69674. }
  69675. else {
  69676. throw new Error('No Y button on right hand');
  69677. }
  69678. },
  69679. enumerable: true,
  69680. configurable: true
  69681. });
  69682. /**
  69683. * Called once for each button that changed state since the last frame
  69684. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  69685. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  69686. * 2) secondary trigger (same)
  69687. * 3) A (right) X (left), touch, pressed = value
  69688. * 4) B / Y
  69689. * 5) thumb rest
  69690. * @param buttonIdx Which button index changed
  69691. * @param state New state of the button
  69692. * @param changes Which properties on the state changed since last frame
  69693. */
  69694. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69695. var notifyObject = state; //{ state: state, changes: changes };
  69696. var triggerDirection = this.hand === 'right' ? -1 : 1;
  69697. switch (buttonIdx) {
  69698. case 0:
  69699. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69700. return;
  69701. case 1:// index trigger
  69702. if (this._defaultModel) {
  69703. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  69704. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  69705. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  69706. }
  69707. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69708. return;
  69709. case 2:// secondary trigger
  69710. if (this._defaultModel) {
  69711. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  69712. }
  69713. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  69714. return;
  69715. case 3:
  69716. if (this._defaultModel) {
  69717. if (notifyObject.pressed) {
  69718. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  69719. }
  69720. else {
  69721. (this._defaultModel.getChildren()[1]).position.y = 0;
  69722. }
  69723. }
  69724. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  69725. return;
  69726. case 4:
  69727. if (this._defaultModel) {
  69728. if (notifyObject.pressed) {
  69729. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  69730. }
  69731. else {
  69732. (this._defaultModel.getChildren()[2]).position.y = 0;
  69733. }
  69734. }
  69735. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  69736. return;
  69737. case 5:
  69738. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  69739. return;
  69740. }
  69741. };
  69742. /**
  69743. * Base Url for the controller model.
  69744. */
  69745. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  69746. /**
  69747. * File name for the left controller model.
  69748. */
  69749. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  69750. /**
  69751. * File name for the right controller model.
  69752. */
  69753. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  69754. return OculusTouchController;
  69755. }(BABYLON.WebVRController));
  69756. BABYLON.OculusTouchController = OculusTouchController;
  69757. })(BABYLON || (BABYLON = {}));
  69758. //# sourceMappingURL=babylon.oculusTouchController.js.map
  69759. "use strict";
  69760. var BABYLON;
  69761. (function (BABYLON) {
  69762. /**
  69763. * Vive Controller
  69764. */
  69765. var ViveController = /** @class */ (function (_super) {
  69766. __extends(ViveController, _super);
  69767. /**
  69768. * Creates a new ViveController from a gamepad
  69769. * @param vrGamepad the gamepad that the controller should be created from
  69770. */
  69771. function ViveController(vrGamepad) {
  69772. var _this = _super.call(this, vrGamepad) || this;
  69773. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  69774. _this._invertLeftStickY = true;
  69775. return _this;
  69776. }
  69777. /**
  69778. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69779. * @param scene scene in which to add meshes
  69780. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69781. */
  69782. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69783. var _this = this;
  69784. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  69785. /*
  69786. Parent Mesh name: ViveWand
  69787. - body
  69788. - r_gripper
  69789. - l_gripper
  69790. - menu_button
  69791. - system_button
  69792. - trackpad
  69793. - trigger
  69794. - LED
  69795. */
  69796. _this._defaultModel = newMeshes[1];
  69797. _this.attachToMesh(_this._defaultModel);
  69798. if (meshLoaded) {
  69799. meshLoaded(_this._defaultModel);
  69800. }
  69801. });
  69802. };
  69803. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  69804. /**
  69805. * Fired when the left button on this controller is modified
  69806. */
  69807. get: function () {
  69808. return this.onMainButtonStateChangedObservable;
  69809. },
  69810. enumerable: true,
  69811. configurable: true
  69812. });
  69813. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  69814. /**
  69815. * Fired when the right button on this controller is modified
  69816. */
  69817. get: function () {
  69818. return this.onMainButtonStateChangedObservable;
  69819. },
  69820. enumerable: true,
  69821. configurable: true
  69822. });
  69823. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  69824. /**
  69825. * Fired when the menu button on this controller is modified
  69826. */
  69827. get: function () {
  69828. return this.onSecondaryButtonStateChangedObservable;
  69829. },
  69830. enumerable: true,
  69831. configurable: true
  69832. });
  69833. /**
  69834. * Called once for each button that changed state since the last frame
  69835. * Vive mapping:
  69836. * 0: touchpad
  69837. * 1: trigger
  69838. * 2: left AND right buttons
  69839. * 3: menu button
  69840. * @param buttonIdx Which button index changed
  69841. * @param state New state of the button
  69842. * @param changes Which properties on the state changed since last frame
  69843. */
  69844. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69845. var notifyObject = state; //{ state: state, changes: changes };
  69846. switch (buttonIdx) {
  69847. case 0:
  69848. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  69849. return;
  69850. case 1:// index trigger
  69851. if (this._defaultModel) {
  69852. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  69853. }
  69854. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  69855. return;
  69856. case 2:// left AND right button
  69857. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  69858. return;
  69859. case 3:
  69860. if (this._defaultModel) {
  69861. if (notifyObject.pressed) {
  69862. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  69863. }
  69864. else {
  69865. (this._defaultModel.getChildren()[2]).position.y = 0;
  69866. }
  69867. }
  69868. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  69869. return;
  69870. }
  69871. };
  69872. /**
  69873. * Base Url for the controller model.
  69874. */
  69875. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  69876. /**
  69877. * File name for the controller model.
  69878. */
  69879. ViveController.MODEL_FILENAME = 'wand.babylon';
  69880. return ViveController;
  69881. }(BABYLON.WebVRController));
  69882. BABYLON.ViveController = ViveController;
  69883. })(BABYLON || (BABYLON = {}));
  69884. //# sourceMappingURL=babylon.viveController.js.map
  69885. "use strict";
  69886. var BABYLON;
  69887. (function (BABYLON) {
  69888. /**
  69889. * Generic Controller
  69890. */
  69891. var GenericController = /** @class */ (function (_super) {
  69892. __extends(GenericController, _super);
  69893. /**
  69894. * Creates a new GenericController from a gamepad
  69895. * @param vrGamepad the gamepad that the controller should be created from
  69896. */
  69897. function GenericController(vrGamepad) {
  69898. return _super.call(this, vrGamepad) || this;
  69899. }
  69900. /**
  69901. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  69902. * @param scene scene in which to add meshes
  69903. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  69904. */
  69905. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  69906. var _this = this;
  69907. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  69908. _this._defaultModel = newMeshes[1];
  69909. _this.attachToMesh(_this._defaultModel);
  69910. if (meshLoaded) {
  69911. meshLoaded(_this._defaultModel);
  69912. }
  69913. });
  69914. };
  69915. /**
  69916. * Called once for each button that changed state since the last frame
  69917. * @param buttonIdx Which button index changed
  69918. * @param state New state of the button
  69919. * @param changes Which properties on the state changed since last frame
  69920. */
  69921. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  69922. console.log("Button id: " + buttonIdx + "state: ");
  69923. console.dir(state);
  69924. };
  69925. /**
  69926. * Base Url for the controller model.
  69927. */
  69928. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  69929. /**
  69930. * File name for the controller model.
  69931. */
  69932. GenericController.MODEL_FILENAME = 'generic.babylon';
  69933. return GenericController;
  69934. }(BABYLON.WebVRController));
  69935. BABYLON.GenericController = GenericController;
  69936. })(BABYLON || (BABYLON = {}));
  69937. //# sourceMappingURL=babylon.genericController.js.map
  69938. "use strict";
  69939. var BABYLON;
  69940. (function (BABYLON) {
  69941. /**
  69942. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  69943. */
  69944. var LoadedMeshInfo = /** @class */ (function () {
  69945. function LoadedMeshInfo() {
  69946. /**
  69947. * Map of the button meshes contained in the controller
  69948. */
  69949. this.buttonMeshes = {};
  69950. /**
  69951. * Map of the axis meshes contained in the controller
  69952. */
  69953. this.axisMeshes = {};
  69954. }
  69955. return LoadedMeshInfo;
  69956. }());
  69957. /**
  69958. * Defines the WindowsMotionController object that the state of the windows motion controller
  69959. */
  69960. var WindowsMotionController = /** @class */ (function (_super) {
  69961. __extends(WindowsMotionController, _super);
  69962. /**
  69963. * Creates a new WindowsMotionController from a gamepad
  69964. * @param vrGamepad the gamepad that the controller should be created from
  69965. */
  69966. function WindowsMotionController(vrGamepad) {
  69967. var _this = _super.call(this, vrGamepad) || this;
  69968. _this._mapping = {
  69969. // Semantic button names
  69970. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  69971. // A mapping of the button name to glTF model node name
  69972. // that should be transformed by button value.
  69973. buttonMeshNames: {
  69974. 'trigger': 'SELECT',
  69975. 'menu': 'MENU',
  69976. 'grip': 'GRASP',
  69977. 'thumbstick': 'THUMBSTICK_PRESS',
  69978. 'trackpad': 'TOUCHPAD_PRESS'
  69979. },
  69980. // This mapping is used to translate from the Motion Controller to Babylon semantics
  69981. buttonObservableNames: {
  69982. 'trigger': 'onTriggerStateChangedObservable',
  69983. 'menu': 'onSecondaryButtonStateChangedObservable',
  69984. 'grip': 'onMainButtonStateChangedObservable',
  69985. 'thumbstick': 'onPadStateChangedObservable',
  69986. 'trackpad': 'onTrackpadChangedObservable'
  69987. },
  69988. // A mapping of the axis name to glTF model node name
  69989. // that should be transformed by axis value.
  69990. // This array mirrors the browserGamepad.axes array, such that
  69991. // the mesh corresponding to axis 0 is in this array index 0.
  69992. axisMeshNames: [
  69993. 'THUMBSTICK_X',
  69994. 'THUMBSTICK_Y',
  69995. 'TOUCHPAD_TOUCH_X',
  69996. 'TOUCHPAD_TOUCH_Y'
  69997. ],
  69998. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  69999. };
  70000. /**
  70001. * Fired when the trackpad on this controller is clicked
  70002. */
  70003. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  70004. /**
  70005. * Fired when the trackpad on this controller is modified
  70006. */
  70007. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  70008. /**
  70009. * The current x and y values of this controller's trackpad
  70010. */
  70011. _this.trackpad = { x: 0, y: 0 };
  70012. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  70013. _this._loadedMeshInfo = null;
  70014. return _this;
  70015. }
  70016. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  70017. /**
  70018. * Fired when the trigger on this controller is modified
  70019. */
  70020. get: function () {
  70021. return this.onTriggerStateChangedObservable;
  70022. },
  70023. enumerable: true,
  70024. configurable: true
  70025. });
  70026. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  70027. /**
  70028. * Fired when the menu button on this controller is modified
  70029. */
  70030. get: function () {
  70031. return this.onSecondaryButtonStateChangedObservable;
  70032. },
  70033. enumerable: true,
  70034. configurable: true
  70035. });
  70036. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  70037. /**
  70038. * Fired when the grip button on this controller is modified
  70039. */
  70040. get: function () {
  70041. return this.onMainButtonStateChangedObservable;
  70042. },
  70043. enumerable: true,
  70044. configurable: true
  70045. });
  70046. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  70047. /**
  70048. * Fired when the thumbstick button on this controller is modified
  70049. */
  70050. get: function () {
  70051. return this.onPadStateChangedObservable;
  70052. },
  70053. enumerable: true,
  70054. configurable: true
  70055. });
  70056. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  70057. /**
  70058. * Fired when the touchpad button on this controller is modified
  70059. */
  70060. get: function () {
  70061. return this.onTrackpadChangedObservable;
  70062. },
  70063. enumerable: true,
  70064. configurable: true
  70065. });
  70066. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  70067. /**
  70068. * Fired when the touchpad values on this controller are modified
  70069. */
  70070. get: function () {
  70071. return this.onTrackpadValuesChangedObservable;
  70072. },
  70073. enumerable: true,
  70074. configurable: true
  70075. });
  70076. /**
  70077. * Called once per frame by the engine.
  70078. */
  70079. WindowsMotionController.prototype.update = function () {
  70080. _super.prototype.update.call(this);
  70081. if (this.browserGamepad.axes) {
  70082. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  70083. this.trackpad.x = this.browserGamepad["axes"][2];
  70084. this.trackpad.y = this.browserGamepad["axes"][3];
  70085. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  70086. }
  70087. // Only need to animate axes if there is a loaded mesh
  70088. if (this._loadedMeshInfo) {
  70089. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  70090. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  70091. }
  70092. }
  70093. }
  70094. };
  70095. /**
  70096. * Called once for each button that changed state since the last frame
  70097. * @param buttonIdx Which button index changed
  70098. * @param state New state of the button
  70099. * @param changes Which properties on the state changed since last frame
  70100. */
  70101. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70102. var buttonName = this._mapping.buttons[buttonIdx];
  70103. if (!buttonName) {
  70104. return;
  70105. }
  70106. // Only emit events for buttons that we know how to map from index to name
  70107. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  70108. if (observable) {
  70109. observable.notifyObservers(state);
  70110. }
  70111. this._lerpButtonTransform(buttonName, state.value);
  70112. };
  70113. /**
  70114. * Moves the buttons on the controller mesh based on their current state
  70115. * @param buttonName the name of the button to move
  70116. * @param buttonValue the value of the button which determines the buttons new position
  70117. */
  70118. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  70119. // If there is no loaded mesh, there is nothing to transform.
  70120. if (!this._loadedMeshInfo) {
  70121. return;
  70122. }
  70123. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  70124. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70125. return;
  70126. }
  70127. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  70128. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  70129. };
  70130. /**
  70131. * Moves the axis on the controller mesh based on its current state
  70132. * @param axis the index of the axis
  70133. * @param axisValue the value of the axis which determines the meshes new position
  70134. * @ignore
  70135. */
  70136. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  70137. if (!this._loadedMeshInfo) {
  70138. return;
  70139. }
  70140. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  70141. if (!meshInfo) {
  70142. return;
  70143. }
  70144. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  70145. return;
  70146. }
  70147. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  70148. var lerpValue = axisValue * 0.5 + 0.5;
  70149. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  70150. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  70151. };
  70152. /**
  70153. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70154. * @param scene scene in which to add meshes
  70155. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70156. */
  70157. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  70158. var _this = this;
  70159. if (forceDefault === void 0) { forceDefault = false; }
  70160. var path;
  70161. var filename;
  70162. // Checking if GLB loader is present
  70163. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  70164. // Determine the device specific folder based on the ID suffix
  70165. var device = 'default';
  70166. if (this.id && !forceDefault) {
  70167. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  70168. device = ((match && match[0]) || device);
  70169. }
  70170. // Hand
  70171. if (this.hand === 'left') {
  70172. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  70173. }
  70174. else {
  70175. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  70176. }
  70177. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  70178. }
  70179. else {
  70180. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  70181. path = BABYLON.GenericController.MODEL_BASE_URL;
  70182. filename = BABYLON.GenericController.MODEL_FILENAME;
  70183. }
  70184. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  70185. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  70186. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  70187. if (!_this._loadedMeshInfo) {
  70188. return;
  70189. }
  70190. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  70191. _this.attachToMesh(_this._defaultModel);
  70192. if (meshLoaded) {
  70193. meshLoaded(_this._defaultModel);
  70194. }
  70195. }, null, function (scene, message) {
  70196. BABYLON.Tools.Log(message);
  70197. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  70198. if (!forceDefault) {
  70199. _this.initControllerMesh(scene, meshLoaded, true);
  70200. }
  70201. });
  70202. };
  70203. /**
  70204. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  70205. * can be transformed by button presses and axes values, based on this._mapping.
  70206. *
  70207. * @param scene scene in which the meshes exist
  70208. * @param meshes list of meshes that make up the controller model to process
  70209. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  70210. */
  70211. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  70212. var loadedMeshInfo = null;
  70213. // Create a new mesh to contain the glTF hierarchy
  70214. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  70215. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  70216. var childMesh = null;
  70217. for (var i = 0; i < meshes.length; i++) {
  70218. var mesh = meshes[i];
  70219. if (!mesh.parent) {
  70220. // Exclude controller meshes from picking results
  70221. mesh.isPickable = false;
  70222. // Handle root node, attach to the new parentMesh
  70223. childMesh = mesh;
  70224. break;
  70225. }
  70226. }
  70227. if (childMesh) {
  70228. childMesh.setParent(parentMesh);
  70229. // Create our mesh info. Note that this method will always return non-null.
  70230. loadedMeshInfo = this.createMeshInfo(parentMesh);
  70231. }
  70232. else {
  70233. BABYLON.Tools.Warn('Could not find root node in model file.');
  70234. }
  70235. return loadedMeshInfo;
  70236. };
  70237. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  70238. var loadedMeshInfo = new LoadedMeshInfo();
  70239. var i;
  70240. loadedMeshInfo.rootNode = rootNode;
  70241. // Reset the caches
  70242. loadedMeshInfo.buttonMeshes = {};
  70243. loadedMeshInfo.axisMeshes = {};
  70244. // Button Meshes
  70245. for (i = 0; i < this._mapping.buttons.length; i++) {
  70246. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  70247. if (!buttonMeshName) {
  70248. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  70249. continue;
  70250. }
  70251. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  70252. if (!buttonMesh) {
  70253. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  70254. continue;
  70255. }
  70256. var buttonMeshInfo = {
  70257. index: i,
  70258. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  70259. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  70260. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  70261. };
  70262. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  70263. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  70264. }
  70265. else {
  70266. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  70267. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  70268. '(VALUE: ' + !!buttonMeshInfo.value +
  70269. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  70270. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  70271. ')');
  70272. }
  70273. }
  70274. // Axis Meshes
  70275. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  70276. var axisMeshName = this._mapping.axisMeshNames[i];
  70277. if (!axisMeshName) {
  70278. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  70279. continue;
  70280. }
  70281. var axisMesh = getChildByName(rootNode, axisMeshName);
  70282. if (!axisMesh) {
  70283. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  70284. continue;
  70285. }
  70286. var axisMeshInfo = {
  70287. index: i,
  70288. value: getImmediateChildByName(axisMesh, 'VALUE'),
  70289. min: getImmediateChildByName(axisMesh, 'MIN'),
  70290. max: getImmediateChildByName(axisMesh, 'MAX')
  70291. };
  70292. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  70293. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  70294. }
  70295. else {
  70296. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  70297. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  70298. '(VALUE: ' + !!axisMeshInfo.value +
  70299. ', MIN: ' + !!axisMeshInfo.min +
  70300. ', MAX:' + !!axisMeshInfo.max +
  70301. ')');
  70302. }
  70303. }
  70304. // Pointing Ray
  70305. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  70306. if (!loadedMeshInfo.pointingPoseNode) {
  70307. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  70308. }
  70309. return loadedMeshInfo;
  70310. // Look through all children recursively. This will return null if no mesh exists with the given name.
  70311. function getChildByName(node, name) {
  70312. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  70313. }
  70314. // Look through only immediate children. This will return null if no mesh exists with the given name.
  70315. function getImmediateChildByName(node, name) {
  70316. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  70317. }
  70318. };
  70319. /**
  70320. * Gets the ray of the controller in the direction the controller is pointing
  70321. * @param length the length the resulting ray should be
  70322. * @returns a ray in the direction the controller is pointing
  70323. */
  70324. WindowsMotionController.prototype.getForwardRay = function (length) {
  70325. if (length === void 0) { length = 100; }
  70326. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  70327. return _super.prototype.getForwardRay.call(this, length);
  70328. }
  70329. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  70330. var origin = m.getTranslation();
  70331. var forward = new BABYLON.Vector3(0, 0, -1);
  70332. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70333. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70334. return new BABYLON.Ray(origin, direction, length);
  70335. };
  70336. /**
  70337. * Disposes of the controller
  70338. */
  70339. WindowsMotionController.prototype.dispose = function () {
  70340. _super.prototype.dispose.call(this);
  70341. this.onTrackpadChangedObservable.clear();
  70342. };
  70343. /**
  70344. * The base url used to load the left and right controller models
  70345. */
  70346. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  70347. /**
  70348. * The name of the left controller model file
  70349. */
  70350. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  70351. /**
  70352. * The name of the right controller model file
  70353. */
  70354. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  70355. /**
  70356. * The controller name prefix for this controller type
  70357. */
  70358. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  70359. /**
  70360. * The controller id pattern for this controller type
  70361. */
  70362. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  70363. return WindowsMotionController;
  70364. }(BABYLON.WebVRController));
  70365. BABYLON.WindowsMotionController = WindowsMotionController;
  70366. })(BABYLON || (BABYLON = {}));
  70367. //# sourceMappingURL=babylon.windowsMotionController.js.map
  70368. "use strict";
  70369. var BABYLON;
  70370. (function (BABYLON) {
  70371. /**
  70372. * Gear VR Controller
  70373. */
  70374. var GearVRController = /** @class */ (function (_super) {
  70375. __extends(GearVRController, _super);
  70376. /**
  70377. * Creates a new GearVRController from a gamepad
  70378. * @param vrGamepad the gamepad that the controller should be created from
  70379. */
  70380. function GearVRController(vrGamepad) {
  70381. var _this = _super.call(this, vrGamepad) || this;
  70382. _this._buttonIndexToObservableNameMap = [
  70383. 'onTrackpadChangedObservable',
  70384. 'onTriggerStateChangedObservable' // Trigger
  70385. ];
  70386. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  70387. return _this;
  70388. }
  70389. /**
  70390. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70391. * @param scene scene in which to add meshes
  70392. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70393. */
  70394. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70395. var _this = this;
  70396. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  70397. _this._defaultModel = newMeshes[1];
  70398. _this.attachToMesh(_this._defaultModel);
  70399. if (meshLoaded) {
  70400. meshLoaded(_this._defaultModel);
  70401. }
  70402. });
  70403. };
  70404. /**
  70405. * Called once for each button that changed state since the last frame
  70406. * @param buttonIdx Which button index changed
  70407. * @param state New state of the button
  70408. * @param changes Which properties on the state changed since last frame
  70409. */
  70410. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70411. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  70412. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  70413. // Only emit events for buttons that we know how to map from index to observable
  70414. var observable = this[observableName];
  70415. if (observable) {
  70416. observable.notifyObservers(state);
  70417. }
  70418. }
  70419. };
  70420. /**
  70421. * Base Url for the controller model.
  70422. */
  70423. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70424. /**
  70425. * File name for the controller model.
  70426. */
  70427. GearVRController.MODEL_FILENAME = 'generic.babylon';
  70428. /**
  70429. * Gamepad Id prefix used to identify this controller.
  70430. */
  70431. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  70432. return GearVRController;
  70433. }(BABYLON.WebVRController));
  70434. BABYLON.GearVRController = GearVRController;
  70435. })(BABYLON || (BABYLON = {}));
  70436. //# sourceMappingURL=babylon.gearVRController.js.map
  70437. "use strict";
  70438. var BABYLON;
  70439. (function (BABYLON) {
  70440. /**
  70441. * Google Daydream controller
  70442. */
  70443. var DaydreamController = /** @class */ (function (_super) {
  70444. __extends(DaydreamController, _super);
  70445. /**
  70446. * Creates a new DaydreamController from a gamepad
  70447. * @param vrGamepad the gamepad that the controller should be created from
  70448. */
  70449. function DaydreamController(vrGamepad) {
  70450. var _this = _super.call(this, vrGamepad) || this;
  70451. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  70452. return _this;
  70453. }
  70454. /**
  70455. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70456. * @param scene scene in which to add meshes
  70457. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70458. */
  70459. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70460. var _this = this;
  70461. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  70462. _this._defaultModel = newMeshes[1];
  70463. _this.attachToMesh(_this._defaultModel);
  70464. if (meshLoaded) {
  70465. meshLoaded(_this._defaultModel);
  70466. }
  70467. });
  70468. };
  70469. /**
  70470. * Called once for each button that changed state since the last frame
  70471. * @param buttonIdx Which button index changed
  70472. * @param state New state of the button
  70473. * @param changes Which properties on the state changed since last frame
  70474. */
  70475. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70476. // Daydream controller only has 1 GamepadButton (on the trackpad).
  70477. if (buttonIdx === 0) {
  70478. var observable = this.onTriggerStateChangedObservable;
  70479. if (observable) {
  70480. observable.notifyObservers(state);
  70481. }
  70482. }
  70483. else {
  70484. // If the app or home buttons are ever made available
  70485. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  70486. }
  70487. };
  70488. /**
  70489. * Base Url for the controller model.
  70490. */
  70491. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70492. /**
  70493. * File name for the controller model.
  70494. */
  70495. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  70496. /**
  70497. * Gamepad Id prefix used to identify Daydream Controller.
  70498. */
  70499. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  70500. return DaydreamController;
  70501. }(BABYLON.WebVRController));
  70502. BABYLON.DaydreamController = DaydreamController;
  70503. })(BABYLON || (BABYLON = {}));
  70504. //# sourceMappingURL=babylon.daydreamController.js.map
  70505. "use strict";
  70506. var BABYLON;
  70507. (function (BABYLON) {
  70508. var FollowCamera = /** @class */ (function (_super) {
  70509. __extends(FollowCamera, _super);
  70510. function FollowCamera(name, position, scene, lockedTarget) {
  70511. if (lockedTarget === void 0) { lockedTarget = null; }
  70512. var _this = _super.call(this, name, position, scene) || this;
  70513. _this.radius = 12;
  70514. _this.rotationOffset = 0;
  70515. _this.heightOffset = 4;
  70516. _this.cameraAcceleration = 0.05;
  70517. _this.maxCameraSpeed = 20;
  70518. _this.lockedTarget = lockedTarget;
  70519. return _this;
  70520. }
  70521. FollowCamera.prototype.getRadians = function (degrees) {
  70522. return degrees * Math.PI / 180;
  70523. };
  70524. FollowCamera.prototype.follow = function (cameraTarget) {
  70525. if (!cameraTarget)
  70526. return;
  70527. var yRotation;
  70528. if (cameraTarget.rotationQuaternion) {
  70529. var rotMatrix = new BABYLON.Matrix();
  70530. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  70531. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  70532. }
  70533. else {
  70534. yRotation = cameraTarget.rotation.y;
  70535. }
  70536. var radians = this.getRadians(this.rotationOffset) + yRotation;
  70537. var targetPosition = cameraTarget.getAbsolutePosition();
  70538. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  70539. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  70540. var dx = targetX - this.position.x;
  70541. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  70542. var dz = (targetZ) - this.position.z;
  70543. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  70544. var vy = dy * this.cameraAcceleration;
  70545. var vz = dz * this.cameraAcceleration * 2;
  70546. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  70547. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70548. }
  70549. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  70550. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70551. }
  70552. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  70553. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  70554. }
  70555. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  70556. this.setTarget(targetPosition);
  70557. };
  70558. FollowCamera.prototype._checkInputs = function () {
  70559. _super.prototype._checkInputs.call(this);
  70560. if (this.lockedTarget) {
  70561. this.follow(this.lockedTarget);
  70562. }
  70563. };
  70564. FollowCamera.prototype.getClassName = function () {
  70565. return "FollowCamera";
  70566. };
  70567. __decorate([
  70568. BABYLON.serialize()
  70569. ], FollowCamera.prototype, "radius", void 0);
  70570. __decorate([
  70571. BABYLON.serialize()
  70572. ], FollowCamera.prototype, "rotationOffset", void 0);
  70573. __decorate([
  70574. BABYLON.serialize()
  70575. ], FollowCamera.prototype, "heightOffset", void 0);
  70576. __decorate([
  70577. BABYLON.serialize()
  70578. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  70579. __decorate([
  70580. BABYLON.serialize()
  70581. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  70582. __decorate([
  70583. BABYLON.serializeAsMeshReference("lockedTargetId")
  70584. ], FollowCamera.prototype, "lockedTarget", void 0);
  70585. return FollowCamera;
  70586. }(BABYLON.TargetCamera));
  70587. BABYLON.FollowCamera = FollowCamera;
  70588. var ArcFollowCamera = /** @class */ (function (_super) {
  70589. __extends(ArcFollowCamera, _super);
  70590. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  70591. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  70592. _this.alpha = alpha;
  70593. _this.beta = beta;
  70594. _this.radius = radius;
  70595. _this.target = target;
  70596. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  70597. _this.follow();
  70598. return _this;
  70599. }
  70600. ArcFollowCamera.prototype.follow = function () {
  70601. if (!this.target) {
  70602. return;
  70603. }
  70604. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  70605. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  70606. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  70607. var targetPosition = this.target.getAbsolutePosition();
  70608. this.position = targetPosition.add(this._cartesianCoordinates);
  70609. this.setTarget(targetPosition);
  70610. };
  70611. ArcFollowCamera.prototype._checkInputs = function () {
  70612. _super.prototype._checkInputs.call(this);
  70613. this.follow();
  70614. };
  70615. ArcFollowCamera.prototype.getClassName = function () {
  70616. return "ArcFollowCamera";
  70617. };
  70618. return ArcFollowCamera;
  70619. }(BABYLON.TargetCamera));
  70620. BABYLON.ArcFollowCamera = ArcFollowCamera;
  70621. })(BABYLON || (BABYLON = {}));
  70622. //# sourceMappingURL=babylon.followCamera.js.map
  70623. "use strict";
  70624. var BABYLON;
  70625. (function (BABYLON) {
  70626. // We're mainly based on the logic defined into the FreeCamera code
  70627. var UniversalCamera = /** @class */ (function (_super) {
  70628. __extends(UniversalCamera, _super);
  70629. //-- end properties for backward compatibility for inputs
  70630. function UniversalCamera(name, position, scene) {
  70631. var _this = _super.call(this, name, position, scene) || this;
  70632. _this.inputs.addGamepad();
  70633. return _this;
  70634. }
  70635. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  70636. //-- Begin properties for backward compatibility for inputs
  70637. get: function () {
  70638. var gamepad = this.inputs.attached["gamepad"];
  70639. if (gamepad)
  70640. return gamepad.gamepadAngularSensibility;
  70641. return 0;
  70642. },
  70643. set: function (value) {
  70644. var gamepad = this.inputs.attached["gamepad"];
  70645. if (gamepad)
  70646. gamepad.gamepadAngularSensibility = value;
  70647. },
  70648. enumerable: true,
  70649. configurable: true
  70650. });
  70651. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  70652. get: function () {
  70653. var gamepad = this.inputs.attached["gamepad"];
  70654. if (gamepad)
  70655. return gamepad.gamepadMoveSensibility;
  70656. return 0;
  70657. },
  70658. set: function (value) {
  70659. var gamepad = this.inputs.attached["gamepad"];
  70660. if (gamepad)
  70661. gamepad.gamepadMoveSensibility = value;
  70662. },
  70663. enumerable: true,
  70664. configurable: true
  70665. });
  70666. UniversalCamera.prototype.getClassName = function () {
  70667. return "UniversalCamera";
  70668. };
  70669. return UniversalCamera;
  70670. }(BABYLON.TouchCamera));
  70671. BABYLON.UniversalCamera = UniversalCamera;
  70672. })(BABYLON || (BABYLON = {}));
  70673. //# sourceMappingURL=babylon.universalCamera.js.map
  70674. "use strict";
  70675. var BABYLON;
  70676. (function (BABYLON) {
  70677. // We're mainly based on the logic defined into the FreeCamera code
  70678. var GamepadCamera = /** @class */ (function (_super) {
  70679. __extends(GamepadCamera, _super);
  70680. //-- end properties for backward compatibility for inputs
  70681. function GamepadCamera(name, position, scene) {
  70682. return _super.call(this, name, position, scene) || this;
  70683. }
  70684. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  70685. //-- Begin properties for backward compatibility for inputs
  70686. get: function () {
  70687. var gamepad = this.inputs.attached["gamepad"];
  70688. if (gamepad)
  70689. return gamepad.gamepadAngularSensibility;
  70690. return 0;
  70691. },
  70692. set: function (value) {
  70693. var gamepad = this.inputs.attached["gamepad"];
  70694. if (gamepad)
  70695. gamepad.gamepadAngularSensibility = value;
  70696. },
  70697. enumerable: true,
  70698. configurable: true
  70699. });
  70700. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  70701. get: function () {
  70702. var gamepad = this.inputs.attached["gamepad"];
  70703. if (gamepad)
  70704. return gamepad.gamepadMoveSensibility;
  70705. return 0;
  70706. },
  70707. set: function (value) {
  70708. var gamepad = this.inputs.attached["gamepad"];
  70709. if (gamepad)
  70710. gamepad.gamepadMoveSensibility = value;
  70711. },
  70712. enumerable: true,
  70713. configurable: true
  70714. });
  70715. GamepadCamera.prototype.getClassName = function () {
  70716. return "GamepadCamera";
  70717. };
  70718. return GamepadCamera;
  70719. }(BABYLON.UniversalCamera));
  70720. BABYLON.GamepadCamera = GamepadCamera;
  70721. })(BABYLON || (BABYLON = {}));
  70722. //# sourceMappingURL=babylon.gamepadCamera.js.map
  70723. "use strict";
  70724. var BABYLON;
  70725. (function (BABYLON) {
  70726. var PostProcessRenderPipelineManager = /** @class */ (function () {
  70727. function PostProcessRenderPipelineManager() {
  70728. this._renderPipelines = {};
  70729. }
  70730. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  70731. this._renderPipelines[renderPipeline._name] = renderPipeline;
  70732. };
  70733. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  70734. if (unique === void 0) { unique = false; }
  70735. var renderPipeline = this._renderPipelines[renderPipelineName];
  70736. if (!renderPipeline) {
  70737. return;
  70738. }
  70739. renderPipeline._attachCameras(cameras, unique);
  70740. };
  70741. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  70742. var renderPipeline = this._renderPipelines[renderPipelineName];
  70743. if (!renderPipeline) {
  70744. return;
  70745. }
  70746. renderPipeline._detachCameras(cameras);
  70747. };
  70748. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  70749. var renderPipeline = this._renderPipelines[renderPipelineName];
  70750. if (!renderPipeline) {
  70751. return;
  70752. }
  70753. renderPipeline._enableEffect(renderEffectName, cameras);
  70754. };
  70755. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  70756. var renderPipeline = this._renderPipelines[renderPipelineName];
  70757. if (!renderPipeline) {
  70758. return;
  70759. }
  70760. renderPipeline._disableEffect(renderEffectName, cameras);
  70761. };
  70762. PostProcessRenderPipelineManager.prototype.update = function () {
  70763. for (var renderPipelineName in this._renderPipelines) {
  70764. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70765. var pipeline = this._renderPipelines[renderPipelineName];
  70766. if (!pipeline.isSupported) {
  70767. pipeline.dispose();
  70768. delete this._renderPipelines[renderPipelineName];
  70769. }
  70770. else {
  70771. pipeline._update();
  70772. }
  70773. }
  70774. }
  70775. };
  70776. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  70777. for (var renderPipelineName in this._renderPipelines) {
  70778. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70779. var pipeline = this._renderPipelines[renderPipelineName];
  70780. pipeline._rebuild();
  70781. }
  70782. }
  70783. };
  70784. PostProcessRenderPipelineManager.prototype.dispose = function () {
  70785. for (var renderPipelineName in this._renderPipelines) {
  70786. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  70787. var pipeline = this._renderPipelines[renderPipelineName];
  70788. pipeline.dispose();
  70789. }
  70790. }
  70791. };
  70792. return PostProcessRenderPipelineManager;
  70793. }());
  70794. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  70795. })(BABYLON || (BABYLON = {}));
  70796. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  70797. "use strict";
  70798. var BABYLON;
  70799. (function (BABYLON) {
  70800. /**
  70801. * This represents a set of one or more post processes in Babylon.
  70802. * A post process can be used to apply a shader to a texture after it is rendered.
  70803. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  70804. */
  70805. var PostProcessRenderEffect = /** @class */ (function () {
  70806. /**
  70807. * Instantiates a post process render effect.
  70808. * A post process can be used to apply a shader to a texture after it is rendered.
  70809. * @param engine The engine the effect is tied to
  70810. * @param name The name of the effect
  70811. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  70812. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  70813. */
  70814. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  70815. this._name = name;
  70816. this._singleInstance = singleInstance || true;
  70817. this._getPostProcesses = getPostProcesses;
  70818. this._cameras = {};
  70819. this._indicesForCamera = {};
  70820. this._postProcesses = {};
  70821. }
  70822. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  70823. /**
  70824. * Checks if all the post processes in the effect are supported.
  70825. */
  70826. get: function () {
  70827. for (var index in this._postProcesses) {
  70828. for (var ppIndex in this._postProcesses[index]) {
  70829. if (!this._postProcesses[index][ppIndex].isSupported) {
  70830. return false;
  70831. }
  70832. }
  70833. }
  70834. return true;
  70835. },
  70836. enumerable: true,
  70837. configurable: true
  70838. });
  70839. /**
  70840. * Updates the current state of the effect
  70841. */
  70842. PostProcessRenderEffect.prototype._update = function () {
  70843. };
  70844. /**
  70845. * Attaches the effect on cameras
  70846. * @param cameras The camera to attach to.
  70847. */
  70848. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  70849. var _this = this;
  70850. var cameraKey;
  70851. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70852. if (!cams) {
  70853. return;
  70854. }
  70855. for (var i = 0; i < cams.length; i++) {
  70856. var camera = cams[i];
  70857. var cameraName = camera.name;
  70858. if (this._singleInstance) {
  70859. cameraKey = 0;
  70860. }
  70861. else {
  70862. cameraKey = cameraName;
  70863. }
  70864. if (!this._postProcesses[cameraKey]) {
  70865. var postProcess = this._getPostProcesses();
  70866. if (postProcess) {
  70867. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  70868. }
  70869. }
  70870. if (!this._indicesForCamera[cameraName]) {
  70871. this._indicesForCamera[cameraName] = [];
  70872. }
  70873. this._postProcesses[cameraKey].forEach(function (postProcess) {
  70874. var index = camera.attachPostProcess(postProcess);
  70875. _this._indicesForCamera[cameraName].push(index);
  70876. });
  70877. if (!this._cameras[cameraName]) {
  70878. this._cameras[cameraName] = camera;
  70879. }
  70880. }
  70881. };
  70882. /**
  70883. * Detatches the effect on cameras
  70884. * @param cameras The camera to detatch from.
  70885. */
  70886. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  70887. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70888. if (!cams) {
  70889. return;
  70890. }
  70891. for (var i = 0; i < cams.length; i++) {
  70892. var camera = cams[i];
  70893. var cameraName = camera.name;
  70894. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70895. camera.detachPostProcess(postProcess);
  70896. });
  70897. if (this._cameras[cameraName]) {
  70898. //this._indicesForCamera.splice(index, 1);
  70899. this._cameras[cameraName] = null;
  70900. }
  70901. }
  70902. };
  70903. /**
  70904. * Enables the effect on given cameras
  70905. * @param cameras The camera to enable.
  70906. */
  70907. PostProcessRenderEffect.prototype._enable = function (cameras) {
  70908. var _this = this;
  70909. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70910. if (!cams) {
  70911. return;
  70912. }
  70913. for (var i = 0; i < cams.length; i++) {
  70914. var camera = cams[i];
  70915. var cameraName = camera.name;
  70916. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  70917. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  70918. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70919. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  70920. });
  70921. }
  70922. }
  70923. }
  70924. };
  70925. /**
  70926. * Disables the effect on the given cameras
  70927. * @param cameras The camera to disable.
  70928. */
  70929. PostProcessRenderEffect.prototype._disable = function (cameras) {
  70930. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  70931. if (!cams) {
  70932. return;
  70933. }
  70934. for (var i = 0; i < cams.length; i++) {
  70935. var camera = cams[i];
  70936. var cameraName = camera.name;
  70937. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  70938. camera.detachPostProcess(postProcess);
  70939. });
  70940. }
  70941. };
  70942. /**
  70943. * Gets a list of the post processes contained in the effect.
  70944. * @param camera The camera to get the post processes on.
  70945. * @returns The list of the post processes in the effect.
  70946. */
  70947. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  70948. if (this._singleInstance) {
  70949. return this._postProcesses[0];
  70950. }
  70951. else {
  70952. if (!camera) {
  70953. return null;
  70954. }
  70955. return this._postProcesses[camera.name];
  70956. }
  70957. };
  70958. return PostProcessRenderEffect;
  70959. }());
  70960. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  70961. })(BABYLON || (BABYLON = {}));
  70962. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  70963. "use strict";
  70964. var BABYLON;
  70965. (function (BABYLON) {
  70966. var PostProcessRenderPipeline = /** @class */ (function () {
  70967. function PostProcessRenderPipeline(engine, name) {
  70968. this.engine = engine;
  70969. this._name = name;
  70970. this._renderEffects = {};
  70971. this._renderEffectsForIsolatedPass = new Array();
  70972. this._cameras = [];
  70973. }
  70974. PostProcessRenderPipeline.prototype.getClassName = function () {
  70975. return "PostProcessRenderPipeline";
  70976. };
  70977. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  70978. get: function () {
  70979. for (var renderEffectName in this._renderEffects) {
  70980. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  70981. if (!this._renderEffects[renderEffectName].isSupported) {
  70982. return false;
  70983. }
  70984. }
  70985. }
  70986. return true;
  70987. },
  70988. enumerable: true,
  70989. configurable: true
  70990. });
  70991. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  70992. this._renderEffects[renderEffect._name] = renderEffect;
  70993. };
  70994. // private
  70995. PostProcessRenderPipeline.prototype._rebuild = function () {
  70996. };
  70997. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  70998. var renderEffects = this._renderEffects[renderEffectName];
  70999. if (!renderEffects) {
  71000. return;
  71001. }
  71002. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71003. };
  71004. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  71005. var renderEffects = this._renderEffects[renderEffectName];
  71006. if (!renderEffects) {
  71007. return;
  71008. }
  71009. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71010. };
  71011. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  71012. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71013. if (!cams) {
  71014. return;
  71015. }
  71016. var indicesToDelete = [];
  71017. var i;
  71018. for (i = 0; i < cams.length; i++) {
  71019. var camera = cams[i];
  71020. var cameraName = camera.name;
  71021. if (this._cameras.indexOf(camera) === -1) {
  71022. this._cameras[cameraName] = camera;
  71023. }
  71024. else if (unique) {
  71025. indicesToDelete.push(i);
  71026. }
  71027. }
  71028. for (i = 0; i < indicesToDelete.length; i++) {
  71029. cameras.splice(indicesToDelete[i], 1);
  71030. }
  71031. for (var renderEffectName in this._renderEffects) {
  71032. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71033. this._renderEffects[renderEffectName]._attachCameras(cams);
  71034. }
  71035. }
  71036. };
  71037. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  71038. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71039. if (!cams) {
  71040. return;
  71041. }
  71042. for (var renderEffectName in this._renderEffects) {
  71043. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71044. this._renderEffects[renderEffectName]._detachCameras(cams);
  71045. }
  71046. }
  71047. for (var i = 0; i < cams.length; i++) {
  71048. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  71049. }
  71050. };
  71051. PostProcessRenderPipeline.prototype._update = function () {
  71052. for (var renderEffectName in this._renderEffects) {
  71053. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71054. this._renderEffects[renderEffectName]._update();
  71055. }
  71056. }
  71057. for (var i = 0; i < this._cameras.length; i++) {
  71058. var cameraName = this._cameras[i].name;
  71059. if (this._renderEffectsForIsolatedPass[cameraName]) {
  71060. this._renderEffectsForIsolatedPass[cameraName]._update();
  71061. }
  71062. }
  71063. };
  71064. PostProcessRenderPipeline.prototype._reset = function () {
  71065. this._renderEffects = {};
  71066. this._renderEffectsForIsolatedPass = new Array();
  71067. };
  71068. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  71069. // 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)
  71070. var effectKeys = Object.keys(this._renderEffects);
  71071. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  71072. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  71073. if (postProcesses) {
  71074. postProcesses[0].samples = sampleCount;
  71075. return true;
  71076. }
  71077. }
  71078. return false;
  71079. };
  71080. PostProcessRenderPipeline.prototype.dispose = function () {
  71081. // Must be implemented by children
  71082. };
  71083. __decorate([
  71084. BABYLON.serialize()
  71085. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  71086. return PostProcessRenderPipeline;
  71087. }());
  71088. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  71089. })(BABYLON || (BABYLON = {}));
  71090. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  71091. "use strict";
  71092. var BABYLON;
  71093. (function (BABYLON) {
  71094. /**
  71095. * This represents a depth renderer in Babylon.
  71096. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  71097. */
  71098. var DepthRenderer = /** @class */ (function () {
  71099. /**
  71100. * Instantiates a depth renderer
  71101. * @param scene The scene the renderer belongs to
  71102. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  71103. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  71104. */
  71105. function DepthRenderer(scene, type, camera) {
  71106. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  71107. if (camera === void 0) { camera = null; }
  71108. var _this = this;
  71109. this._scene = scene;
  71110. this._camera = camera;
  71111. var engine = scene.getEngine();
  71112. // Render target
  71113. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  71114. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71115. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71116. this._depthMap.refreshRate = 1;
  71117. this._depthMap.renderParticles = false;
  71118. this._depthMap.renderList = null;
  71119. // Camera to get depth map from to support multiple concurrent cameras
  71120. this._depthMap.activeCamera = this._camera;
  71121. this._depthMap.ignoreCameraViewport = true;
  71122. this._depthMap.useCameraPostProcesses = false;
  71123. // set default depth value to 1.0 (far away)
  71124. this._depthMap.onClearObservable.add(function (engine) {
  71125. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  71126. });
  71127. // Custom render function
  71128. var renderSubMesh = function (subMesh) {
  71129. var mesh = subMesh.getRenderingMesh();
  71130. var scene = _this._scene;
  71131. var engine = scene.getEngine();
  71132. var material = subMesh.getMaterial();
  71133. if (!material) {
  71134. return;
  71135. }
  71136. // Culling and reverse (right handed system)
  71137. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71138. // Managing instances
  71139. var batch = mesh._getInstancesRenderList(subMesh._id);
  71140. if (batch.mustReturn) {
  71141. return;
  71142. }
  71143. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71144. var camera = _this._camera || scene.activeCamera;
  71145. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  71146. engine.enableEffect(_this._effect);
  71147. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71148. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71149. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  71150. // Alpha test
  71151. if (material && material.needAlphaTesting()) {
  71152. var alphaTexture = material.getAlphaTestTexture();
  71153. if (alphaTexture) {
  71154. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71155. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71156. }
  71157. }
  71158. // Bones
  71159. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71160. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71161. }
  71162. // Draw
  71163. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71164. }
  71165. };
  71166. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71167. var index;
  71168. if (depthOnlySubMeshes.length) {
  71169. engine.setColorWrite(false);
  71170. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71171. renderSubMesh(depthOnlySubMeshes.data[index]);
  71172. }
  71173. engine.setColorWrite(true);
  71174. }
  71175. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71176. renderSubMesh(opaqueSubMeshes.data[index]);
  71177. }
  71178. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71179. renderSubMesh(alphaTestSubMeshes.data[index]);
  71180. }
  71181. };
  71182. }
  71183. /**
  71184. * Creates the depth rendering effect and checks if the effect is ready.
  71185. * @param subMesh The submesh to be used to render the depth map of
  71186. * @param useInstances If multiple world instances should be used
  71187. * @returns if the depth renderer is ready to render the depth map
  71188. */
  71189. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  71190. var material = subMesh.getMaterial();
  71191. if (material.disableDepthWrite) {
  71192. return false;
  71193. }
  71194. var defines = [];
  71195. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71196. var mesh = subMesh.getMesh();
  71197. // Alpha test
  71198. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  71199. defines.push("#define ALPHATEST");
  71200. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71201. attribs.push(BABYLON.VertexBuffer.UVKind);
  71202. defines.push("#define UV1");
  71203. }
  71204. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71205. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71206. defines.push("#define UV2");
  71207. }
  71208. }
  71209. // Bones
  71210. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71211. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71212. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71213. if (mesh.numBoneInfluencers > 4) {
  71214. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71215. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71216. }
  71217. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71218. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71219. }
  71220. else {
  71221. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71222. }
  71223. // Instances
  71224. if (useInstances) {
  71225. defines.push("#define INSTANCES");
  71226. attribs.push("world0");
  71227. attribs.push("world1");
  71228. attribs.push("world2");
  71229. attribs.push("world3");
  71230. }
  71231. // Get correct effect
  71232. var join = defines.join("\n");
  71233. if (this._cachedDefines !== join) {
  71234. this._cachedDefines = join;
  71235. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  71236. }
  71237. return this._effect.isReady();
  71238. };
  71239. /**
  71240. * Gets the texture which the depth map will be written to.
  71241. * @returns The depth map texture
  71242. */
  71243. DepthRenderer.prototype.getDepthMap = function () {
  71244. return this._depthMap;
  71245. };
  71246. /**
  71247. * Disposes of the depth renderer.
  71248. */
  71249. DepthRenderer.prototype.dispose = function () {
  71250. this._depthMap.dispose();
  71251. };
  71252. return DepthRenderer;
  71253. }());
  71254. BABYLON.DepthRenderer = DepthRenderer;
  71255. })(BABYLON || (BABYLON = {}));
  71256. //# sourceMappingURL=babylon.depthRenderer.js.map
  71257. "use strict";
  71258. var BABYLON;
  71259. (function (BABYLON) {
  71260. var SSAORenderingPipeline = /** @class */ (function (_super) {
  71261. __extends(SSAORenderingPipeline, _super);
  71262. /**
  71263. * @constructor
  71264. * @param {string} name - The rendering pipeline name
  71265. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71266. * @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 }
  71267. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71268. */
  71269. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  71270. var _this = _super.call(this, scene.getEngine(), name) || this;
  71271. // Members
  71272. /**
  71273. * The PassPostProcess id in the pipeline that contains the original scene color
  71274. */
  71275. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71276. /**
  71277. * The SSAO PostProcess id in the pipeline
  71278. */
  71279. _this.SSAORenderEffect = "SSAORenderEffect";
  71280. /**
  71281. * The horizontal blur PostProcess id in the pipeline
  71282. */
  71283. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71284. /**
  71285. * The vertical blur PostProcess id in the pipeline
  71286. */
  71287. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71288. /**
  71289. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71290. */
  71291. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71292. /**
  71293. * The output strength of the SSAO post-process. Default value is 1.0.
  71294. */
  71295. _this.totalStrength = 1.0;
  71296. /**
  71297. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  71298. */
  71299. _this.radius = 0.0001;
  71300. /**
  71301. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  71302. * Must not be equal to fallOff and superior to fallOff.
  71303. * Default value is 0.975
  71304. */
  71305. _this.area = 0.0075;
  71306. /**
  71307. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  71308. * Must not be equal to area and inferior to area.
  71309. * Default value is 0.0
  71310. */
  71311. _this.fallOff = 0.000001;
  71312. /**
  71313. * The base color of the SSAO post-process
  71314. * The final result is "base + ssao" between [0, 1]
  71315. */
  71316. _this.base = 0.5;
  71317. _this._firstUpdate = true;
  71318. _this._scene = scene;
  71319. // Set up assets
  71320. _this._createRandomTexture();
  71321. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71322. var ssaoRatio = ratio.ssaoRatio || ratio;
  71323. var combineRatio = ratio.combineRatio || ratio;
  71324. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71325. _this._createSSAOPostProcess(ssaoRatio);
  71326. _this._createBlurPostProcess(ssaoRatio);
  71327. _this._createSSAOCombinePostProcess(combineRatio);
  71328. // Set up pipeline
  71329. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71330. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71331. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71332. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71333. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71334. // Finish
  71335. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71336. if (cameras)
  71337. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71338. return _this;
  71339. }
  71340. // Public Methods
  71341. /**
  71342. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71343. */
  71344. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71345. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71346. for (var i = 0; i < this._scene.cameras.length; i++) {
  71347. var camera = this._scene.cameras[i];
  71348. this._originalColorPostProcess.dispose(camera);
  71349. this._ssaoPostProcess.dispose(camera);
  71350. this._blurHPostProcess.dispose(camera);
  71351. this._blurVPostProcess.dispose(camera);
  71352. this._ssaoCombinePostProcess.dispose(camera);
  71353. }
  71354. this._randomTexture.dispose();
  71355. if (disableDepthRender)
  71356. this._scene.disableDepthRenderer();
  71357. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71358. _super.prototype.dispose.call(this);
  71359. };
  71360. // Private Methods
  71361. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  71362. var _this = this;
  71363. var size = 16;
  71364. 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);
  71365. 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);
  71366. this._blurHPostProcess.onActivateObservable.add(function () {
  71367. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  71368. _this._blurHPostProcess.kernel = size * dw;
  71369. });
  71370. this._blurVPostProcess.onActivateObservable.add(function () {
  71371. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  71372. _this._blurVPostProcess.kernel = size * dw;
  71373. });
  71374. };
  71375. SSAORenderingPipeline.prototype._rebuild = function () {
  71376. this._firstUpdate = true;
  71377. _super.prototype._rebuild.call(this);
  71378. };
  71379. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71380. var _this = this;
  71381. var numSamples = 16;
  71382. var sampleSphere = [
  71383. 0.5381, 0.1856, -0.4319,
  71384. 0.1379, 0.2486, 0.4430,
  71385. 0.3371, 0.5679, -0.0057,
  71386. -0.6999, -0.0451, -0.0019,
  71387. 0.0689, -0.1598, -0.8547,
  71388. 0.0560, 0.0069, -0.1843,
  71389. -0.0146, 0.1402, 0.0762,
  71390. 0.0100, -0.1924, -0.0344,
  71391. -0.3577, -0.5301, -0.4358,
  71392. -0.3169, 0.1063, 0.0158,
  71393. 0.0103, -0.5869, 0.0046,
  71394. -0.0897, -0.4940, 0.3287,
  71395. 0.7119, -0.0154, -0.0918,
  71396. -0.0533, 0.0596, -0.5411,
  71397. 0.0352, -0.0631, 0.5460,
  71398. -0.4776, 0.2847, -0.0271
  71399. ];
  71400. var samplesFactor = 1.0 / numSamples;
  71401. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  71402. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71403. "area", "fallOff", "base", "range", "viewport"
  71404. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71405. this._ssaoPostProcess.onApply = function (effect) {
  71406. if (_this._firstUpdate) {
  71407. effect.setArray3("sampleSphere", sampleSphere);
  71408. effect.setFloat("samplesFactor", samplesFactor);
  71409. effect.setFloat("randTextureTiles", 4.0);
  71410. }
  71411. effect.setFloat("totalStrength", _this.totalStrength);
  71412. effect.setFloat("radius", _this.radius);
  71413. effect.setFloat("area", _this.area);
  71414. effect.setFloat("fallOff", _this.fallOff);
  71415. effect.setFloat("base", _this.base);
  71416. effect.setTexture("textureSampler", _this._depthTexture);
  71417. effect.setTexture("randomSampler", _this._randomTexture);
  71418. };
  71419. };
  71420. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71421. var _this = this;
  71422. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71423. this._ssaoCombinePostProcess.onApply = function (effect) {
  71424. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71425. };
  71426. };
  71427. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  71428. var size = 512;
  71429. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71430. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71431. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71432. var context = this._randomTexture.getContext();
  71433. var rand = function (min, max) {
  71434. return Math.random() * (max - min) + min;
  71435. };
  71436. var randVector = BABYLON.Vector3.Zero();
  71437. for (var x = 0; x < size; x++) {
  71438. for (var y = 0; y < size; y++) {
  71439. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  71440. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  71441. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  71442. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71443. context.fillRect(x, y, 1, 1);
  71444. }
  71445. }
  71446. this._randomTexture.update(false);
  71447. };
  71448. __decorate([
  71449. BABYLON.serialize()
  71450. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  71451. __decorate([
  71452. BABYLON.serialize()
  71453. ], SSAORenderingPipeline.prototype, "radius", void 0);
  71454. __decorate([
  71455. BABYLON.serialize()
  71456. ], SSAORenderingPipeline.prototype, "area", void 0);
  71457. __decorate([
  71458. BABYLON.serialize()
  71459. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  71460. __decorate([
  71461. BABYLON.serialize()
  71462. ], SSAORenderingPipeline.prototype, "base", void 0);
  71463. return SSAORenderingPipeline;
  71464. }(BABYLON.PostProcessRenderPipeline));
  71465. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  71466. })(BABYLON || (BABYLON = {}));
  71467. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  71468. "use strict";
  71469. var BABYLON;
  71470. (function (BABYLON) {
  71471. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  71472. __extends(SSAO2RenderingPipeline, _super);
  71473. /**
  71474. * @constructor
  71475. * @param {string} name - The rendering pipeline name
  71476. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71477. * @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 }
  71478. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71479. */
  71480. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  71481. var _this = _super.call(this, scene.getEngine(), name) || this;
  71482. // Members
  71483. /**
  71484. * The PassPostProcess id in the pipeline that contains the original scene color
  71485. */
  71486. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  71487. /**
  71488. * The SSAO PostProcess id in the pipeline
  71489. */
  71490. _this.SSAORenderEffect = "SSAORenderEffect";
  71491. /**
  71492. * The horizontal blur PostProcess id in the pipeline
  71493. */
  71494. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  71495. /**
  71496. * The vertical blur PostProcess id in the pipeline
  71497. */
  71498. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  71499. /**
  71500. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  71501. */
  71502. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  71503. /**
  71504. * The output strength of the SSAO post-process. Default value is 1.0.
  71505. */
  71506. _this.totalStrength = 1.0;
  71507. /**
  71508. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  71509. */
  71510. _this.maxZ = 100.0;
  71511. /**
  71512. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  71513. */
  71514. _this.minZAspect = 0.2;
  71515. /**
  71516. * Number of samples used for the SSAO calculations. Default value is 8
  71517. */
  71518. _this._samples = 8;
  71519. /**
  71520. * Are we using bilateral blur ?
  71521. */
  71522. _this._expensiveBlur = true;
  71523. /**
  71524. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  71525. */
  71526. _this.radius = 2.0;
  71527. /**
  71528. * The base color of the SSAO post-process
  71529. * The final result is "base + ssao" between [0, 1]
  71530. */
  71531. _this.base = 0.1;
  71532. _this._firstUpdate = true;
  71533. _this._scene = scene;
  71534. if (!_this.isSupported) {
  71535. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  71536. return _this;
  71537. }
  71538. var ssaoRatio = ratio.ssaoRatio || ratio;
  71539. var blurRatio = ratio.blurRatio || ratio;
  71540. // Set up assets
  71541. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  71542. _this._createRandomTexture();
  71543. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  71544. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  71545. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  71546. _this._createSSAOPostProcess(1.0);
  71547. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  71548. _this._createSSAOCombinePostProcess(blurRatio);
  71549. // Set up pipeline
  71550. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  71551. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  71552. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  71553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  71554. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  71555. // Finish
  71556. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71557. if (cameras)
  71558. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71559. return _this;
  71560. }
  71561. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  71562. get: function () {
  71563. return this._samples;
  71564. },
  71565. set: function (n) {
  71566. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  71567. this._samples = n;
  71568. this._sampleSphere = this._generateHemisphere();
  71569. this._firstUpdate = true;
  71570. },
  71571. enumerable: true,
  71572. configurable: true
  71573. });
  71574. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  71575. get: function () {
  71576. return this._expensiveBlur;
  71577. },
  71578. set: function (b) {
  71579. 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"]);
  71580. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  71581. this._expensiveBlur = b;
  71582. this._firstUpdate = true;
  71583. },
  71584. enumerable: true,
  71585. configurable: true
  71586. });
  71587. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  71588. /**
  71589. * Support test.
  71590. */
  71591. get: function () {
  71592. var engine = BABYLON.Engine.LastCreatedEngine;
  71593. if (!engine) {
  71594. return false;
  71595. }
  71596. return engine.getCaps().drawBuffersExtension;
  71597. },
  71598. enumerable: true,
  71599. configurable: true
  71600. });
  71601. // Public Methods
  71602. /**
  71603. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  71604. */
  71605. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  71606. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  71607. for (var i = 0; i < this._scene.cameras.length; i++) {
  71608. var camera = this._scene.cameras[i];
  71609. this._originalColorPostProcess.dispose(camera);
  71610. this._ssaoPostProcess.dispose(camera);
  71611. this._blurHPostProcess.dispose(camera);
  71612. this._blurVPostProcess.dispose(camera);
  71613. this._ssaoCombinePostProcess.dispose(camera);
  71614. }
  71615. this._randomTexture.dispose();
  71616. if (disableGeometryBufferRenderer)
  71617. this._scene.disableGeometryBufferRenderer();
  71618. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71619. _super.prototype.dispose.call(this);
  71620. };
  71621. // Private Methods
  71622. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  71623. var _this = this;
  71624. this._samplerOffsets = [];
  71625. var expensive = this.expensiveBlur;
  71626. for (var i = -8; i < 8; i++) {
  71627. this._samplerOffsets.push(i * 2 + 0.5);
  71628. }
  71629. 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");
  71630. this._blurHPostProcess.onApply = function (effect) {
  71631. if (!_this._scene.activeCamera) {
  71632. return;
  71633. }
  71634. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  71635. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71636. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71637. effect.setFloat("radius", _this.radius);
  71638. effect.setTexture("depthSampler", _this._depthTexture);
  71639. if (_this._firstUpdate) {
  71640. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71641. }
  71642. };
  71643. 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");
  71644. this._blurVPostProcess.onApply = function (effect) {
  71645. if (!_this._scene.activeCamera) {
  71646. return;
  71647. }
  71648. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  71649. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71650. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71651. effect.setFloat("radius", _this.radius);
  71652. effect.setTexture("depthSampler", _this._depthTexture);
  71653. if (_this._firstUpdate) {
  71654. effect.setArray("samplerOffsets", _this._samplerOffsets);
  71655. _this._firstUpdate = false;
  71656. }
  71657. };
  71658. };
  71659. SSAO2RenderingPipeline.prototype._rebuild = function () {
  71660. this._firstUpdate = true;
  71661. _super.prototype._rebuild.call(this);
  71662. };
  71663. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  71664. var numSamples = this.samples;
  71665. var result = [];
  71666. var vector, scale;
  71667. var rand = function (min, max) {
  71668. return Math.random() * (max - min) + min;
  71669. };
  71670. var i = 0;
  71671. while (i < numSamples) {
  71672. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  71673. vector.normalize();
  71674. scale = i / numSamples;
  71675. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  71676. vector.scaleInPlace(scale);
  71677. result.push(vector.x, vector.y, vector.z);
  71678. i++;
  71679. }
  71680. return result;
  71681. };
  71682. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  71683. var _this = this;
  71684. var numSamples = this.samples;
  71685. this._sampleSphere = this._generateHemisphere();
  71686. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  71687. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  71688. "base", "range", "projection", "near", "far", "texelSize",
  71689. "xViewport", "yViewport", "maxZ", "minZAspect"
  71690. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  71691. this._ssaoPostProcess.onApply = function (effect) {
  71692. if (_this._firstUpdate) {
  71693. effect.setArray3("sampleSphere", _this._sampleSphere);
  71694. effect.setFloat("randTextureTiles", 4.0);
  71695. }
  71696. if (!_this._scene.activeCamera) {
  71697. return;
  71698. }
  71699. effect.setFloat("samplesFactor", 1 / _this.samples);
  71700. effect.setFloat("totalStrength", _this.totalStrength);
  71701. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  71702. effect.setFloat("radius", _this.radius);
  71703. effect.setFloat("maxZ", _this.maxZ);
  71704. effect.setFloat("minZAspect", _this.minZAspect);
  71705. effect.setFloat("base", _this.base);
  71706. effect.setFloat("near", _this._scene.activeCamera.minZ);
  71707. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  71708. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  71709. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  71710. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  71711. effect.setTexture("textureSampler", _this._depthTexture);
  71712. effect.setTexture("normalSampler", _this._normalTexture);
  71713. effect.setTexture("randomSampler", _this._randomTexture);
  71714. };
  71715. };
  71716. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  71717. var _this = this;
  71718. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71719. this._ssaoCombinePostProcess.onApply = function (effect) {
  71720. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  71721. };
  71722. };
  71723. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  71724. var size = 512;
  71725. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71726. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71727. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71728. var context = this._randomTexture.getContext();
  71729. var rand = function (min, max) {
  71730. return Math.random() * (max - min) + min;
  71731. };
  71732. var randVector = BABYLON.Vector3.Zero();
  71733. for (var x = 0; x < size; x++) {
  71734. for (var y = 0; y < size; y++) {
  71735. randVector.x = rand(0.0, 1.0);
  71736. randVector.y = rand(0.0, 1.0);
  71737. randVector.z = 0.0;
  71738. randVector.normalize();
  71739. randVector.scaleInPlace(255);
  71740. randVector.x = Math.floor(randVector.x);
  71741. randVector.y = Math.floor(randVector.y);
  71742. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  71743. context.fillRect(x, y, 1, 1);
  71744. }
  71745. }
  71746. this._randomTexture.update(false);
  71747. };
  71748. __decorate([
  71749. BABYLON.serialize()
  71750. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  71751. __decorate([
  71752. BABYLON.serialize()
  71753. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  71754. __decorate([
  71755. BABYLON.serialize()
  71756. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  71757. __decorate([
  71758. BABYLON.serialize("samples")
  71759. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  71760. __decorate([
  71761. BABYLON.serialize("expensiveBlur")
  71762. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  71763. __decorate([
  71764. BABYLON.serialize()
  71765. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  71766. __decorate([
  71767. BABYLON.serialize()
  71768. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  71769. return SSAO2RenderingPipeline;
  71770. }(BABYLON.PostProcessRenderPipeline));
  71771. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  71772. })(BABYLON || (BABYLON = {}));
  71773. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  71774. "use strict";
  71775. // BABYLON.JS Chromatic Aberration GLSL Shader
  71776. // Author: Olivier Guyot
  71777. // Separates very slightly R, G and B colors on the edges of the screen
  71778. // Inspired by Francois Tarlier & Martins Upitis
  71779. var BABYLON;
  71780. (function (BABYLON) {
  71781. var LensRenderingPipeline = /** @class */ (function (_super) {
  71782. __extends(LensRenderingPipeline, _super);
  71783. /**
  71784. * @constructor
  71785. *
  71786. * Effect parameters are as follow:
  71787. * {
  71788. * chromatic_aberration: number; // from 0 to x (1 for realism)
  71789. * edge_blur: number; // from 0 to x (1 for realism)
  71790. * distortion: number; // from 0 to x (1 for realism)
  71791. * grain_amount: number; // from 0 to 1
  71792. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  71793. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  71794. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  71795. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  71796. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  71797. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  71798. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  71799. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  71800. * }
  71801. * Note: if an effect parameter is unset, effect is disabled
  71802. *
  71803. * @param {string} name - The rendering pipeline name
  71804. * @param {object} parameters - An object containing all parameters (see above)
  71805. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71806. * @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)
  71807. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71808. */
  71809. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  71810. if (ratio === void 0) { ratio = 1.0; }
  71811. var _this = _super.call(this, scene.getEngine(), name) || this;
  71812. // Lens effects can be of the following:
  71813. // - chromatic aberration (slight shift of RGB colors)
  71814. // - blur on the edge of the lens
  71815. // - lens distortion
  71816. // - depth-of-field blur & highlights enhancing
  71817. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  71818. // - grain effect (noise or custom texture)
  71819. // Two additional texture samplers are needed:
  71820. // - depth map (for depth-of-field)
  71821. // - grain texture
  71822. /**
  71823. * The chromatic aberration PostProcess id in the pipeline
  71824. */
  71825. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  71826. /**
  71827. * The highlights enhancing PostProcess id in the pipeline
  71828. */
  71829. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  71830. /**
  71831. * The depth-of-field PostProcess id in the pipeline
  71832. */
  71833. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  71834. _this._scene = scene;
  71835. // Fetch texture samplers
  71836. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  71837. if (parameters.grain_texture) {
  71838. _this._grainTexture = parameters.grain_texture;
  71839. }
  71840. else {
  71841. _this._createGrainTexture();
  71842. }
  71843. // save parameters
  71844. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  71845. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  71846. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  71847. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  71848. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  71849. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  71850. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  71851. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  71852. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  71853. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  71854. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  71855. // Create effects
  71856. _this._createChromaticAberrationPostProcess(ratio);
  71857. _this._createHighlightsPostProcess(ratio);
  71858. _this._createDepthOfFieldPostProcess(ratio / 4);
  71859. // Set up pipeline
  71860. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  71861. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  71862. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  71863. if (_this._highlightsGain === -1) {
  71864. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  71865. }
  71866. // Finish
  71867. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71868. if (cameras) {
  71869. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  71870. }
  71871. return _this;
  71872. }
  71873. // public methods (self explanatory)
  71874. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  71875. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  71876. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  71877. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  71878. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  71879. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  71880. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  71881. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  71882. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  71883. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  71884. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  71885. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  71886. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  71887. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  71888. };
  71889. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  71890. this._highlightsPostProcess.updateEffect();
  71891. };
  71892. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  71893. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  71894. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  71895. this._highlightsGain = amount;
  71896. };
  71897. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  71898. if (this._highlightsGain === -1) {
  71899. this._highlightsGain = 1.0;
  71900. }
  71901. this._highlightsThreshold = amount;
  71902. };
  71903. LensRenderingPipeline.prototype.disableHighlights = function () {
  71904. this._highlightsGain = -1;
  71905. };
  71906. /**
  71907. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  71908. */
  71909. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  71910. if (disableDepthRender === void 0) { disableDepthRender = false; }
  71911. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  71912. this._chromaticAberrationPostProcess = null;
  71913. this._highlightsPostProcess = null;
  71914. this._depthOfFieldPostProcess = null;
  71915. this._grainTexture.dispose();
  71916. if (disableDepthRender)
  71917. this._scene.disableDepthRenderer();
  71918. };
  71919. // colors shifting and distortion
  71920. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  71921. var _this = this;
  71922. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  71923. [], // samplers
  71924. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71925. this._chromaticAberrationPostProcess.onApply = function (effect) {
  71926. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  71927. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71928. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71929. effect.setFloat('radialIntensity', 1);
  71930. effect.setFloat2('direction', 17, 17);
  71931. effect.setFloat2('centerPosition', 0.5, 0.5);
  71932. };
  71933. };
  71934. // highlights enhancing
  71935. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  71936. var _this = this;
  71937. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  71938. [], // samplers
  71939. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  71940. this._highlightsPostProcess.onApply = function (effect) {
  71941. effect.setFloat('gain', _this._highlightsGain);
  71942. effect.setFloat('threshold', _this._highlightsThreshold);
  71943. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  71944. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71945. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71946. };
  71947. };
  71948. // colors shifting and distortion
  71949. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  71950. var _this = this;
  71951. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  71952. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  71953. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  71954. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  71955. this._depthOfFieldPostProcess.onApply = function (effect) {
  71956. effect.setTexture("depthSampler", _this._depthTexture);
  71957. effect.setTexture("grainSampler", _this._grainTexture);
  71958. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  71959. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  71960. effect.setFloat('grain_amount', _this._grainAmount);
  71961. effect.setBool('blur_noise', _this._blurNoise);
  71962. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  71963. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  71964. effect.setFloat('distortion', _this._distortion);
  71965. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  71966. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  71967. effect.setFloat('aperture', _this._dofAperture);
  71968. effect.setFloat('darken', _this._dofDarken);
  71969. effect.setFloat('edge_blur', _this._edgeBlur);
  71970. effect.setBool('highlights', (_this._highlightsGain !== -1));
  71971. if (_this._scene.activeCamera) {
  71972. effect.setFloat('near', _this._scene.activeCamera.minZ);
  71973. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  71974. }
  71975. };
  71976. };
  71977. // creates a black and white random noise texture, 512x512
  71978. LensRenderingPipeline.prototype._createGrainTexture = function () {
  71979. var size = 512;
  71980. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71981. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  71982. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  71983. var context = this._grainTexture.getContext();
  71984. var rand = function (min, max) {
  71985. return Math.random() * (max - min) + min;
  71986. };
  71987. var value;
  71988. for (var x = 0; x < size; x++) {
  71989. for (var y = 0; y < size; y++) {
  71990. value = Math.floor(rand(0.42, 0.58) * 255);
  71991. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  71992. context.fillRect(x, y, 1, 1);
  71993. }
  71994. }
  71995. this._grainTexture.update(false);
  71996. };
  71997. return LensRenderingPipeline;
  71998. }(BABYLON.PostProcessRenderPipeline));
  71999. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  72000. })(BABYLON || (BABYLON = {}));
  72001. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  72002. "use strict";
  72003. var BABYLON;
  72004. (function (BABYLON) {
  72005. var StandardRenderingPipeline = /** @class */ (function (_super) {
  72006. __extends(StandardRenderingPipeline, _super);
  72007. /**
  72008. * @constructor
  72009. * @param {string} name - The rendering pipeline name
  72010. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72011. * @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)
  72012. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  72013. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72014. */
  72015. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  72016. if (originalPostProcess === void 0) { originalPostProcess = null; }
  72017. var _this = _super.call(this, scene.getEngine(), name) || this;
  72018. _this.downSampleX4PostProcess = null;
  72019. _this.brightPassPostProcess = null;
  72020. _this.blurHPostProcesses = [];
  72021. _this.blurVPostProcesses = [];
  72022. _this.textureAdderPostProcess = null;
  72023. _this.volumetricLightPostProcess = null;
  72024. _this.volumetricLightSmoothXPostProcess = null;
  72025. _this.volumetricLightSmoothYPostProcess = null;
  72026. _this.volumetricLightMergePostProces = null;
  72027. _this.volumetricLightFinalPostProcess = null;
  72028. _this.luminancePostProcess = null;
  72029. _this.luminanceDownSamplePostProcesses = [];
  72030. _this.hdrPostProcess = null;
  72031. _this.textureAdderFinalPostProcess = null;
  72032. _this.lensFlareFinalPostProcess = null;
  72033. _this.hdrFinalPostProcess = null;
  72034. _this.lensFlarePostProcess = null;
  72035. _this.lensFlareComposePostProcess = null;
  72036. _this.motionBlurPostProcess = null;
  72037. _this.depthOfFieldPostProcess = null;
  72038. // Values
  72039. _this.brightThreshold = 1.0;
  72040. _this.blurWidth = 512.0;
  72041. _this.horizontalBlur = false;
  72042. _this.exposure = 1.0;
  72043. _this.lensTexture = null;
  72044. _this.volumetricLightCoefficient = 0.2;
  72045. _this.volumetricLightPower = 4.0;
  72046. _this.volumetricLightBlurScale = 64.0;
  72047. _this.sourceLight = null;
  72048. _this.hdrMinimumLuminance = 1.0;
  72049. _this.hdrDecreaseRate = 0.5;
  72050. _this.hdrIncreaseRate = 0.5;
  72051. _this.lensColorTexture = null;
  72052. _this.lensFlareStrength = 20.0;
  72053. _this.lensFlareGhostDispersal = 1.4;
  72054. _this.lensFlareHaloWidth = 0.7;
  72055. _this.lensFlareDistortionStrength = 16.0;
  72056. _this.lensStarTexture = null;
  72057. _this.lensFlareDirtTexture = null;
  72058. _this.depthOfFieldDistance = 10.0;
  72059. _this.depthOfFieldBlurWidth = 64.0;
  72060. _this.motionStrength = 1.0;
  72061. // IAnimatable
  72062. _this.animations = [];
  72063. _this._currentDepthOfFieldSource = null;
  72064. _this._hdrCurrentLuminance = 1.0;
  72065. // Getters and setters
  72066. _this._bloomEnabled = true;
  72067. _this._depthOfFieldEnabled = false;
  72068. _this._vlsEnabled = false;
  72069. _this._lensFlareEnabled = false;
  72070. _this._hdrEnabled = false;
  72071. _this._motionBlurEnabled = false;
  72072. _this._motionBlurSamples = 64.0;
  72073. _this._volumetricLightStepsCount = 50.0;
  72074. _this._cameras = cameras || [];
  72075. // Initialize
  72076. _this._scene = scene;
  72077. _this._basePostProcess = originalPostProcess;
  72078. _this._ratio = ratio;
  72079. // Misc
  72080. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72081. // Finish
  72082. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72083. _this._buildPipeline();
  72084. return _this;
  72085. }
  72086. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  72087. get: function () {
  72088. return this._bloomEnabled;
  72089. },
  72090. set: function (enabled) {
  72091. if (this._bloomEnabled === enabled) {
  72092. return;
  72093. }
  72094. this._bloomEnabled = enabled;
  72095. this._buildPipeline();
  72096. },
  72097. enumerable: true,
  72098. configurable: true
  72099. });
  72100. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  72101. get: function () {
  72102. return this._depthOfFieldEnabled;
  72103. },
  72104. set: function (enabled) {
  72105. if (this._depthOfFieldEnabled === enabled) {
  72106. return;
  72107. }
  72108. this._depthOfFieldEnabled = enabled;
  72109. this._buildPipeline();
  72110. },
  72111. enumerable: true,
  72112. configurable: true
  72113. });
  72114. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  72115. get: function () {
  72116. return this._lensFlareEnabled;
  72117. },
  72118. set: function (enabled) {
  72119. if (this._lensFlareEnabled === enabled) {
  72120. return;
  72121. }
  72122. this._lensFlareEnabled = enabled;
  72123. this._buildPipeline();
  72124. },
  72125. enumerable: true,
  72126. configurable: true
  72127. });
  72128. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  72129. get: function () {
  72130. return this._hdrEnabled;
  72131. },
  72132. set: function (enabled) {
  72133. if (this._hdrEnabled === enabled) {
  72134. return;
  72135. }
  72136. this._hdrEnabled = enabled;
  72137. this._buildPipeline();
  72138. },
  72139. enumerable: true,
  72140. configurable: true
  72141. });
  72142. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  72143. get: function () {
  72144. return this._vlsEnabled;
  72145. },
  72146. set: function (enabled) {
  72147. if (this._vlsEnabled === enabled) {
  72148. return;
  72149. }
  72150. if (enabled) {
  72151. var geometry = this._scene.enableGeometryBufferRenderer();
  72152. if (!geometry) {
  72153. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  72154. return;
  72155. }
  72156. }
  72157. this._vlsEnabled = enabled;
  72158. this._buildPipeline();
  72159. },
  72160. enumerable: true,
  72161. configurable: true
  72162. });
  72163. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  72164. get: function () {
  72165. return this._motionBlurEnabled;
  72166. },
  72167. set: function (enabled) {
  72168. if (this._motionBlurEnabled === enabled) {
  72169. return;
  72170. }
  72171. this._motionBlurEnabled = enabled;
  72172. this._buildPipeline();
  72173. },
  72174. enumerable: true,
  72175. configurable: true
  72176. });
  72177. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  72178. get: function () {
  72179. return this._volumetricLightStepsCount;
  72180. },
  72181. set: function (count) {
  72182. if (this.volumetricLightPostProcess) {
  72183. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  72184. }
  72185. this._volumetricLightStepsCount = count;
  72186. },
  72187. enumerable: true,
  72188. configurable: true
  72189. });
  72190. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  72191. get: function () {
  72192. return this._motionBlurSamples;
  72193. },
  72194. set: function (samples) {
  72195. if (this.motionBlurPostProcess) {
  72196. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  72197. }
  72198. this._motionBlurSamples = samples;
  72199. },
  72200. enumerable: true,
  72201. configurable: true
  72202. });
  72203. StandardRenderingPipeline.prototype._buildPipeline = function () {
  72204. var _this = this;
  72205. var ratio = this._ratio;
  72206. var scene = this._scene;
  72207. this._disposePostProcesses();
  72208. this._reset();
  72209. // Create pass post-process
  72210. if (!this._basePostProcess) {
  72211. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  72212. this.originalPostProcess.onApply = function (effect) {
  72213. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  72214. };
  72215. }
  72216. else {
  72217. this.originalPostProcess = this._basePostProcess;
  72218. }
  72219. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  72220. this._currentDepthOfFieldSource = this.originalPostProcess;
  72221. if (this._vlsEnabled) {
  72222. // Create volumetric light
  72223. this._createVolumetricLightPostProcess(scene, ratio);
  72224. // Create volumetric light final post-process
  72225. 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);
  72226. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  72227. }
  72228. if (this._bloomEnabled) {
  72229. // Create down sample X4 post-process
  72230. this._createDownSampleX4PostProcess(scene, ratio / 2);
  72231. // Create bright pass post-process
  72232. this._createBrightPassPostProcess(scene, ratio / 2);
  72233. // Create gaussian blur post-processes (down sampling blurs)
  72234. this._createBlurPostProcesses(scene, ratio / 4, 1);
  72235. // Create texture adder post-process
  72236. this._createTextureAdderPostProcess(scene, ratio);
  72237. // Create depth-of-field source post-process
  72238. 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);
  72239. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  72240. }
  72241. if (this._lensFlareEnabled) {
  72242. // Create lens flare post-process
  72243. this._createLensFlarePostProcess(scene, ratio);
  72244. // Create depth-of-field source post-process post lens-flare and disable it now
  72245. 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);
  72246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  72247. }
  72248. if (this._hdrEnabled) {
  72249. // Create luminance
  72250. this._createLuminancePostProcesses(scene, this._floatTextureType);
  72251. // Create HDR
  72252. this._createHdrPostProcess(scene, ratio);
  72253. // Create depth-of-field source post-process post hdr and disable it now
  72254. 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);
  72255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  72256. }
  72257. if (this._depthOfFieldEnabled) {
  72258. // Create gaussian blur used by depth-of-field
  72259. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  72260. // Create depth-of-field post-process
  72261. this._createDepthOfFieldPostProcess(scene, ratio);
  72262. }
  72263. if (this._motionBlurEnabled) {
  72264. // Create motion blur post-process
  72265. this._createMotionBlurPostProcess(scene, ratio);
  72266. }
  72267. if (this._cameras !== null) {
  72268. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  72269. }
  72270. };
  72271. // Down Sample X4 Post-Processs
  72272. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  72273. var _this = this;
  72274. var downSampleX4Offsets = new Array(32);
  72275. 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);
  72276. this.downSampleX4PostProcess.onApply = function (effect) {
  72277. var id = 0;
  72278. var width = _this.downSampleX4PostProcess.width;
  72279. var height = _this.downSampleX4PostProcess.height;
  72280. for (var i = -2; i < 2; i++) {
  72281. for (var j = -2; j < 2; j++) {
  72282. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  72283. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  72284. id += 2;
  72285. }
  72286. }
  72287. effect.setArray2("dsOffsets", downSampleX4Offsets);
  72288. };
  72289. // Add to pipeline
  72290. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  72291. };
  72292. // Brightpass Post-Process
  72293. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  72294. var _this = this;
  72295. var brightOffsets = new Array(8);
  72296. 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);
  72297. this.brightPassPostProcess.onApply = function (effect) {
  72298. var sU = (1.0 / _this.brightPassPostProcess.width);
  72299. var sV = (1.0 / _this.brightPassPostProcess.height);
  72300. brightOffsets[0] = -0.5 * sU;
  72301. brightOffsets[1] = 0.5 * sV;
  72302. brightOffsets[2] = 0.5 * sU;
  72303. brightOffsets[3] = 0.5 * sV;
  72304. brightOffsets[4] = -0.5 * sU;
  72305. brightOffsets[5] = -0.5 * sV;
  72306. brightOffsets[6] = 0.5 * sU;
  72307. brightOffsets[7] = -0.5 * sV;
  72308. effect.setArray2("dsOffsets", brightOffsets);
  72309. effect.setFloat("brightThreshold", _this.brightThreshold);
  72310. };
  72311. // Add to pipeline
  72312. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  72313. };
  72314. // Create blur H&V post-processes
  72315. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  72316. var _this = this;
  72317. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  72318. var engine = scene.getEngine();
  72319. 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);
  72320. 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);
  72321. blurX.onActivateObservable.add(function () {
  72322. var dw = blurX.width / engine.getRenderWidth();
  72323. blurX.kernel = _this[blurWidthKey] * dw;
  72324. });
  72325. blurY.onActivateObservable.add(function () {
  72326. var dw = blurY.height / engine.getRenderHeight();
  72327. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  72328. });
  72329. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  72330. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  72331. this.blurHPostProcesses.push(blurX);
  72332. this.blurVPostProcesses.push(blurY);
  72333. };
  72334. // Create texture adder post-process
  72335. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  72336. var _this = this;
  72337. 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);
  72338. this.textureAdderPostProcess.onApply = function (effect) {
  72339. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  72340. effect.setTexture("lensSampler", _this.lensTexture);
  72341. effect.setFloat("exposure", _this.exposure);
  72342. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  72343. };
  72344. // Add to pipeline
  72345. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  72346. };
  72347. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  72348. var _this = this;
  72349. var geometryRenderer = scene.enableGeometryBufferRenderer();
  72350. geometryRenderer.enablePosition = true;
  72351. var geometry = geometryRenderer.getGBuffer();
  72352. // Base post-process
  72353. 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));
  72354. var depthValues = BABYLON.Vector2.Zero();
  72355. this.volumetricLightPostProcess.onApply = function (effect) {
  72356. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  72357. var generator = _this.sourceLight.getShadowGenerator();
  72358. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  72359. effect.setTexture("positionSampler", geometry.textures[2]);
  72360. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  72361. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  72362. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  72363. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  72364. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  72365. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  72366. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  72367. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  72368. effect.setVector2("depthValues", depthValues);
  72369. }
  72370. };
  72371. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  72372. // Smooth
  72373. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  72374. // Merge
  72375. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  72376. this.volumetricLightMergePostProces.onApply = function (effect) {
  72377. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  72378. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  72379. };
  72380. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  72381. };
  72382. // Create luminance
  72383. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  72384. var _this = this;
  72385. // Create luminance
  72386. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  72387. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  72388. var offsets = [];
  72389. this.luminancePostProcess.onApply = function (effect) {
  72390. var sU = (1.0 / _this.luminancePostProcess.width);
  72391. var sV = (1.0 / _this.luminancePostProcess.height);
  72392. offsets[0] = -0.5 * sU;
  72393. offsets[1] = 0.5 * sV;
  72394. offsets[2] = 0.5 * sU;
  72395. offsets[3] = 0.5 * sV;
  72396. offsets[4] = -0.5 * sU;
  72397. offsets[5] = -0.5 * sV;
  72398. offsets[6] = 0.5 * sU;
  72399. offsets[7] = -0.5 * sV;
  72400. effect.setArray2("lumOffsets", offsets);
  72401. };
  72402. // Add to pipeline
  72403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  72404. // Create down sample luminance
  72405. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  72406. var size = Math.pow(3, i);
  72407. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  72408. if (i === 0) {
  72409. defines += "#define FINAL_DOWN_SAMPLER";
  72410. }
  72411. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  72412. this.luminanceDownSamplePostProcesses.push(postProcess);
  72413. }
  72414. // Create callbacks and add effects
  72415. var lastLuminance = this.luminancePostProcess;
  72416. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  72417. var downSampleOffsets = new Array(18);
  72418. pp.onApply = function (effect) {
  72419. if (!lastLuminance) {
  72420. return;
  72421. }
  72422. var id = 0;
  72423. for (var x = -1; x < 2; x++) {
  72424. for (var y = -1; y < 2; y++) {
  72425. downSampleOffsets[id] = x / lastLuminance.width;
  72426. downSampleOffsets[id + 1] = y / lastLuminance.height;
  72427. id += 2;
  72428. }
  72429. }
  72430. effect.setArray2("dsOffsets", downSampleOffsets);
  72431. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  72432. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72433. lastLuminance = _this.luminancePostProcess;
  72434. }
  72435. else {
  72436. lastLuminance = pp;
  72437. }
  72438. };
  72439. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  72440. pp.onAfterRender = function (effect) {
  72441. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  72442. 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);
  72443. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  72444. };
  72445. }
  72446. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  72447. });
  72448. };
  72449. // Create HDR post-process
  72450. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  72451. var _this = this;
  72452. 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);
  72453. var outputLiminance = 1;
  72454. var time = 0;
  72455. var lastTime = 0;
  72456. this.hdrPostProcess.onApply = function (effect) {
  72457. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  72458. time += scene.getEngine().getDeltaTime();
  72459. if (outputLiminance < 0) {
  72460. outputLiminance = _this._hdrCurrentLuminance;
  72461. }
  72462. else {
  72463. var dt = (lastTime - time) / 1000.0;
  72464. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  72465. outputLiminance += _this.hdrDecreaseRate * dt;
  72466. }
  72467. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  72468. outputLiminance -= _this.hdrIncreaseRate * dt;
  72469. }
  72470. else {
  72471. outputLiminance = _this._hdrCurrentLuminance;
  72472. }
  72473. }
  72474. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  72475. effect.setFloat("averageLuminance", outputLiminance);
  72476. lastTime = time;
  72477. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  72478. };
  72479. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  72480. };
  72481. // Create lens flare post-process
  72482. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  72483. var _this = this;
  72484. 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);
  72485. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  72486. this._createBlurPostProcesses(scene, ratio / 4, 2);
  72487. 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);
  72488. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  72489. var resolution = new BABYLON.Vector2(0, 0);
  72490. // Lens flare
  72491. this.lensFlarePostProcess.onApply = function (effect) {
  72492. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  72493. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  72494. effect.setFloat("strength", _this.lensFlareStrength);
  72495. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  72496. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  72497. // Shift
  72498. resolution.x = _this.lensFlarePostProcess.width;
  72499. resolution.y = _this.lensFlarePostProcess.height;
  72500. effect.setVector2("resolution", resolution);
  72501. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  72502. };
  72503. // Compose
  72504. 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);
  72505. 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);
  72506. this.lensFlareComposePostProcess.onApply = function (effect) {
  72507. if (!_this._scene.activeCamera) {
  72508. return;
  72509. }
  72510. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72511. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  72512. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  72513. // Lens start rotation matrix
  72514. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  72515. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  72516. 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));
  72517. camRot *= 4.0;
  72518. 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);
  72519. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  72520. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  72521. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  72522. };
  72523. };
  72524. // Create depth-of-field post-process
  72525. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  72526. var _this = this;
  72527. 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);
  72528. this.depthOfFieldPostProcess.onApply = function (effect) {
  72529. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  72530. effect.setTexture("depthSampler", _this._getDepthTexture());
  72531. effect.setFloat("distance", _this.depthOfFieldDistance);
  72532. };
  72533. // Add to pipeline
  72534. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  72535. };
  72536. // Create motion blur post-process
  72537. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  72538. var _this = this;
  72539. 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);
  72540. var motionScale = 0;
  72541. var prevViewProjection = BABYLON.Matrix.Identity();
  72542. var invViewProjection = BABYLON.Matrix.Identity();
  72543. var viewProjection = BABYLON.Matrix.Identity();
  72544. var screenSize = BABYLON.Vector2.Zero();
  72545. this.motionBlurPostProcess.onApply = function (effect) {
  72546. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  72547. viewProjection.invertToRef(invViewProjection);
  72548. effect.setMatrix("inverseViewProjection", invViewProjection);
  72549. effect.setMatrix("prevViewProjection", prevViewProjection);
  72550. prevViewProjection = viewProjection;
  72551. screenSize.x = _this.motionBlurPostProcess.width;
  72552. screenSize.y = _this.motionBlurPostProcess.height;
  72553. effect.setVector2("screenSize", screenSize);
  72554. motionScale = scene.getEngine().getFps() / 60.0;
  72555. effect.setFloat("motionScale", motionScale);
  72556. effect.setFloat("motionStrength", _this.motionStrength);
  72557. effect.setTexture("depthSampler", _this._getDepthTexture());
  72558. };
  72559. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  72560. };
  72561. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  72562. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  72563. var renderer = this._scene.enableGeometryBufferRenderer();
  72564. return renderer.getGBuffer().textures[0];
  72565. }
  72566. return this._scene.enableDepthRenderer().getDepthMap();
  72567. };
  72568. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  72569. for (var i = 0; i < this._cameras.length; i++) {
  72570. var camera = this._cameras[i];
  72571. if (this.originalPostProcess) {
  72572. this.originalPostProcess.dispose(camera);
  72573. }
  72574. if (this.downSampleX4PostProcess) {
  72575. this.downSampleX4PostProcess.dispose(camera);
  72576. }
  72577. if (this.brightPassPostProcess) {
  72578. this.brightPassPostProcess.dispose(camera);
  72579. }
  72580. if (this.textureAdderPostProcess) {
  72581. this.textureAdderPostProcess.dispose(camera);
  72582. }
  72583. if (this.textureAdderFinalPostProcess) {
  72584. this.textureAdderFinalPostProcess.dispose(camera);
  72585. }
  72586. if (this.volumetricLightPostProcess) {
  72587. this.volumetricLightPostProcess.dispose(camera);
  72588. }
  72589. if (this.volumetricLightSmoothXPostProcess) {
  72590. this.volumetricLightSmoothXPostProcess.dispose(camera);
  72591. }
  72592. if (this.volumetricLightSmoothYPostProcess) {
  72593. this.volumetricLightSmoothYPostProcess.dispose(camera);
  72594. }
  72595. if (this.volumetricLightMergePostProces) {
  72596. this.volumetricLightMergePostProces.dispose(camera);
  72597. }
  72598. if (this.volumetricLightFinalPostProcess) {
  72599. this.volumetricLightFinalPostProcess.dispose(camera);
  72600. }
  72601. if (this.lensFlarePostProcess) {
  72602. this.lensFlarePostProcess.dispose(camera);
  72603. }
  72604. if (this.lensFlareComposePostProcess) {
  72605. this.lensFlareComposePostProcess.dispose(camera);
  72606. }
  72607. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  72608. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  72609. }
  72610. if (this.luminancePostProcess) {
  72611. this.luminancePostProcess.dispose(camera);
  72612. }
  72613. if (this.hdrPostProcess) {
  72614. this.hdrPostProcess.dispose(camera);
  72615. }
  72616. if (this.hdrFinalPostProcess) {
  72617. this.hdrFinalPostProcess.dispose(camera);
  72618. }
  72619. if (this.depthOfFieldPostProcess) {
  72620. this.depthOfFieldPostProcess.dispose(camera);
  72621. }
  72622. if (this.motionBlurPostProcess) {
  72623. this.motionBlurPostProcess.dispose(camera);
  72624. }
  72625. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  72626. this.blurHPostProcesses[j].dispose(camera);
  72627. }
  72628. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  72629. this.blurVPostProcesses[j].dispose(camera);
  72630. }
  72631. }
  72632. this.originalPostProcess = null;
  72633. this.downSampleX4PostProcess = null;
  72634. this.brightPassPostProcess = null;
  72635. this.textureAdderPostProcess = null;
  72636. this.textureAdderFinalPostProcess = null;
  72637. this.volumetricLightPostProcess = null;
  72638. this.volumetricLightSmoothXPostProcess = null;
  72639. this.volumetricLightSmoothYPostProcess = null;
  72640. this.volumetricLightMergePostProces = null;
  72641. this.volumetricLightFinalPostProcess = null;
  72642. this.lensFlarePostProcess = null;
  72643. this.lensFlareComposePostProcess = null;
  72644. this.luminancePostProcess = null;
  72645. this.hdrPostProcess = null;
  72646. this.hdrFinalPostProcess = null;
  72647. this.depthOfFieldPostProcess = null;
  72648. this.motionBlurPostProcess = null;
  72649. this.luminanceDownSamplePostProcesses = [];
  72650. this.blurHPostProcesses = [];
  72651. this.blurVPostProcesses = [];
  72652. };
  72653. // Dispose
  72654. StandardRenderingPipeline.prototype.dispose = function () {
  72655. this._disposePostProcesses();
  72656. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  72657. _super.prototype.dispose.call(this);
  72658. };
  72659. // Serialize rendering pipeline
  72660. StandardRenderingPipeline.prototype.serialize = function () {
  72661. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72662. serializationObject.customType = "StandardRenderingPipeline";
  72663. return serializationObject;
  72664. };
  72665. /**
  72666. * Static members
  72667. */
  72668. // Parse serialized pipeline
  72669. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  72670. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  72671. };
  72672. // Luminance steps
  72673. StandardRenderingPipeline.LuminanceSteps = 6;
  72674. __decorate([
  72675. BABYLON.serialize()
  72676. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  72677. __decorate([
  72678. BABYLON.serialize()
  72679. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  72680. __decorate([
  72681. BABYLON.serialize()
  72682. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  72683. __decorate([
  72684. BABYLON.serialize()
  72685. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  72686. __decorate([
  72687. BABYLON.serializeAsTexture("lensTexture")
  72688. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  72689. __decorate([
  72690. BABYLON.serialize()
  72691. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  72692. __decorate([
  72693. BABYLON.serialize()
  72694. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  72695. __decorate([
  72696. BABYLON.serialize()
  72697. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  72698. __decorate([
  72699. BABYLON.serialize()
  72700. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  72701. __decorate([
  72702. BABYLON.serialize()
  72703. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  72704. __decorate([
  72705. BABYLON.serialize()
  72706. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  72707. __decorate([
  72708. BABYLON.serializeAsTexture("lensColorTexture")
  72709. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  72710. __decorate([
  72711. BABYLON.serialize()
  72712. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  72713. __decorate([
  72714. BABYLON.serialize()
  72715. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  72716. __decorate([
  72717. BABYLON.serialize()
  72718. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  72719. __decorate([
  72720. BABYLON.serialize()
  72721. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  72722. __decorate([
  72723. BABYLON.serializeAsTexture("lensStarTexture")
  72724. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  72725. __decorate([
  72726. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  72727. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  72728. __decorate([
  72729. BABYLON.serialize()
  72730. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  72731. __decorate([
  72732. BABYLON.serialize()
  72733. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  72734. __decorate([
  72735. BABYLON.serialize()
  72736. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  72737. __decorate([
  72738. BABYLON.serialize()
  72739. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  72740. __decorate([
  72741. BABYLON.serialize()
  72742. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  72743. __decorate([
  72744. BABYLON.serialize()
  72745. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  72746. __decorate([
  72747. BABYLON.serialize()
  72748. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  72749. __decorate([
  72750. BABYLON.serialize()
  72751. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  72752. __decorate([
  72753. BABYLON.serialize()
  72754. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  72755. __decorate([
  72756. BABYLON.serialize()
  72757. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  72758. __decorate([
  72759. BABYLON.serialize()
  72760. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  72761. __decorate([
  72762. BABYLON.serialize()
  72763. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  72764. return StandardRenderingPipeline;
  72765. }(BABYLON.PostProcessRenderPipeline));
  72766. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  72767. })(BABYLON || (BABYLON = {}));
  72768. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  72769. "use strict";
  72770. var BABYLON;
  72771. (function (BABYLON) {
  72772. var FxaaPostProcess = /** @class */ (function (_super) {
  72773. __extends(FxaaPostProcess, _super);
  72774. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72775. if (camera === void 0) { camera = null; }
  72776. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72777. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  72778. _this.onApplyObservable.add(function (effect) {
  72779. var texelSize = _this.texelSize;
  72780. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  72781. });
  72782. return _this;
  72783. }
  72784. return FxaaPostProcess;
  72785. }(BABYLON.PostProcess));
  72786. BABYLON.FxaaPostProcess = FxaaPostProcess;
  72787. })(BABYLON || (BABYLON = {}));
  72788. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  72789. "use strict";
  72790. var BABYLON;
  72791. (function (BABYLON) {
  72792. /**
  72793. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  72794. */
  72795. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  72796. __extends(ChromaticAberrationPostProcess, _super);
  72797. /**
  72798. * Creates a new instance ChromaticAberrationPostProcess
  72799. * @param name The name of the effect.
  72800. * @param screenWidth The width of the screen to apply the effect on.
  72801. * @param screenHeight The height of the screen to apply the effect on.
  72802. * @param options The required width/height ratio to downsize to before computing the render pass.
  72803. * @param camera The camera to apply the render pass to.
  72804. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72805. * @param engine The engine which the post process will be applied. (default: current engine)
  72806. * @param reusable If the post process can be reused on the same frame. (default: false)
  72807. * @param textureType Type of textures used when performing the post process. (default: 0)
  72808. * @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)
  72809. */
  72810. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72811. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72812. if (blockCompilation === void 0) { blockCompilation = false; }
  72813. 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;
  72814. /**
  72815. * The amount of seperation of rgb channels (default: 30)
  72816. */
  72817. _this.aberrationAmount = 30;
  72818. /**
  72819. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  72820. */
  72821. _this.radialIntensity = 0;
  72822. /**
  72823. * 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))
  72824. */
  72825. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  72826. /**
  72827. * 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))
  72828. */
  72829. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  72830. _this.onApplyObservable.add(function (effect) {
  72831. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  72832. effect.setFloat('screen_width', screenWidth);
  72833. effect.setFloat('screen_height', screenHeight);
  72834. effect.setFloat('radialIntensity', _this.radialIntensity);
  72835. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  72836. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  72837. });
  72838. return _this;
  72839. }
  72840. return ChromaticAberrationPostProcess;
  72841. }(BABYLON.PostProcess));
  72842. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  72843. })(BABYLON || (BABYLON = {}));
  72844. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  72845. "use strict";
  72846. var BABYLON;
  72847. (function (BABYLON) {
  72848. /**
  72849. * The GrainPostProcess adds noise to the image at mid luminance levels
  72850. */
  72851. var GrainPostProcess = /** @class */ (function (_super) {
  72852. __extends(GrainPostProcess, _super);
  72853. /**
  72854. * Creates a new instance of @see GrainPostProcess
  72855. * @param name The name of the effect.
  72856. * @param options The required width/height ratio to downsize to before computing the render pass.
  72857. * @param camera The camera to apply the render pass to.
  72858. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72859. * @param engine The engine which the post process will be applied. (default: current engine)
  72860. * @param reusable If the post process can be reused on the same frame. (default: false)
  72861. * @param textureType Type of textures used when performing the post process. (default: 0)
  72862. * @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)
  72863. */
  72864. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72865. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72866. if (blockCompilation === void 0) { blockCompilation = false; }
  72867. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72868. /**
  72869. * The intensity of the grain added (default: 30)
  72870. */
  72871. _this.intensity = 30;
  72872. /**
  72873. * If the grain should be randomized on every frame
  72874. */
  72875. _this.animated = false;
  72876. _this.onApplyObservable.add(function (effect) {
  72877. effect.setFloat('intensity', _this.intensity);
  72878. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  72879. });
  72880. return _this;
  72881. }
  72882. return GrainPostProcess;
  72883. }(BABYLON.PostProcess));
  72884. BABYLON.GrainPostProcess = GrainPostProcess;
  72885. })(BABYLON || (BABYLON = {}));
  72886. //# sourceMappingURL=babylon.grainPostProcess.js.map
  72887. "use strict";
  72888. var BABYLON;
  72889. (function (BABYLON) {
  72890. /**
  72891. * The SharpenPostProcess applies a sharpen kernel to every pixel
  72892. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  72893. */
  72894. var SharpenPostProcess = /** @class */ (function (_super) {
  72895. __extends(SharpenPostProcess, _super);
  72896. /**
  72897. * Creates a new instance ConvolutionPostProcess
  72898. * @param name The name of the effect.
  72899. * @param options The required width/height ratio to downsize to before computing the render pass.
  72900. * @param camera The camera to apply the render pass to.
  72901. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72902. * @param engine The engine which the post process will be applied. (default: current engine)
  72903. * @param reusable If the post process can be reused on the same frame. (default: false)
  72904. * @param textureType Type of textures used when performing the post process. (default: 0)
  72905. * @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)
  72906. */
  72907. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  72908. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72909. if (blockCompilation === void 0) { blockCompilation = false; }
  72910. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  72911. /**
  72912. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  72913. */
  72914. _this.colorAmount = 1.0;
  72915. /**
  72916. * How much sharpness should be applied (default: 0.3)
  72917. */
  72918. _this.edgeAmount = 0.3;
  72919. _this.onApply = function (effect) {
  72920. effect.setFloat2("screenSize", _this.width, _this.height);
  72921. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  72922. };
  72923. return _this;
  72924. }
  72925. return SharpenPostProcess;
  72926. }(BABYLON.PostProcess));
  72927. BABYLON.SharpenPostProcess = SharpenPostProcess;
  72928. })(BABYLON || (BABYLON = {}));
  72929. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  72930. "use strict";
  72931. var BABYLON;
  72932. (function (BABYLON) {
  72933. /**
  72934. * The Blur Post Process which blurs an image based on a kernel and direction.
  72935. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  72936. */
  72937. var BlurPostProcess = /** @class */ (function (_super) {
  72938. __extends(BlurPostProcess, _super);
  72939. /**
  72940. * Creates a new instance BlurPostProcess
  72941. * @param name The name of the effect.
  72942. * @param direction The direction in which to blur the image.
  72943. * @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.
  72944. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  72945. * @param camera The camera to apply the render pass to.
  72946. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72947. * @param engine The engine which the post process will be applied. (default: current engine)
  72948. * @param reusable If the post process can be reused on the same frame. (default: false)
  72949. * @param textureType Type of textures used when performing the post process. (default: 0)
  72950. * @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)
  72951. */
  72952. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  72953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72954. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72955. if (defines === void 0) { defines = ""; }
  72956. if (blockCompilation === void 0) { blockCompilation = false; }
  72957. 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;
  72958. _this.direction = direction;
  72959. _this.blockCompilation = blockCompilation;
  72960. _this._packedFloat = false;
  72961. _this._staticDefines = "";
  72962. _this._staticDefines = defines;
  72963. _this.onApplyObservable.add(function (effect) {
  72964. if (_this._outputTexture) {
  72965. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  72966. }
  72967. else {
  72968. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  72969. }
  72970. });
  72971. _this.kernel = kernel;
  72972. return _this;
  72973. }
  72974. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  72975. /**
  72976. * Gets the length in pixels of the blur sample region
  72977. */
  72978. get: function () {
  72979. return this._idealKernel;
  72980. },
  72981. /**
  72982. * Sets the length in pixels of the blur sample region
  72983. */
  72984. set: function (v) {
  72985. if (this._idealKernel === v) {
  72986. return;
  72987. }
  72988. v = Math.max(v, 1);
  72989. this._idealKernel = v;
  72990. this._kernel = this._nearestBestKernel(v);
  72991. if (!this.blockCompilation) {
  72992. this._updateParameters();
  72993. }
  72994. },
  72995. enumerable: true,
  72996. configurable: true
  72997. });
  72998. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  72999. /**
  73000. * Gets wether or not the blur is unpacking/repacking floats
  73001. */
  73002. get: function () {
  73003. return this._packedFloat;
  73004. },
  73005. /**
  73006. * Sets wether or not the blur needs to unpack/repack floats
  73007. */
  73008. set: function (v) {
  73009. if (this._packedFloat === v) {
  73010. return;
  73011. }
  73012. this._packedFloat = v;
  73013. if (!this.blockCompilation) {
  73014. this._updateParameters();
  73015. }
  73016. },
  73017. enumerable: true,
  73018. configurable: true
  73019. });
  73020. /**
  73021. * Updates the effect with the current post process compile time values and recompiles the shader.
  73022. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73023. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73024. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73025. * @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
  73026. * @param onCompiled Called when the shader has been compiled.
  73027. * @param onError Called if there is an error when compiling a shader.
  73028. */
  73029. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73030. if (defines === void 0) { defines = null; }
  73031. if (uniforms === void 0) { uniforms = null; }
  73032. if (samplers === void 0) { samplers = null; }
  73033. this._updateParameters(onCompiled, onError);
  73034. };
  73035. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  73036. // Generate sampling offsets and weights
  73037. var N = this._kernel;
  73038. var centerIndex = (N - 1) / 2;
  73039. // Generate Gaussian sampling weights over kernel
  73040. var offsets = [];
  73041. var weights = [];
  73042. var totalWeight = 0;
  73043. for (var i = 0; i < N; i++) {
  73044. var u = i / (N - 1);
  73045. var w = this._gaussianWeight(u * 2.0 - 1);
  73046. offsets[i] = (i - centerIndex);
  73047. weights[i] = w;
  73048. totalWeight += w;
  73049. }
  73050. // Normalize weights
  73051. for (var i = 0; i < weights.length; i++) {
  73052. weights[i] /= totalWeight;
  73053. }
  73054. // Optimize: combine samples to take advantage of hardware linear sampling
  73055. // Walk from left to center, combining pairs (symmetrically)
  73056. var linearSamplingWeights = [];
  73057. var linearSamplingOffsets = [];
  73058. var linearSamplingMap = [];
  73059. for (var i = 0; i <= centerIndex; i += 2) {
  73060. var j = Math.min(i + 1, Math.floor(centerIndex));
  73061. var singleCenterSample = i === j;
  73062. if (singleCenterSample) {
  73063. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73064. }
  73065. else {
  73066. var sharedCell = j === centerIndex;
  73067. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  73068. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  73069. if (offsetLinear === 0) {
  73070. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73071. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  73072. }
  73073. else {
  73074. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  73075. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  73076. }
  73077. }
  73078. }
  73079. for (var i = 0; i < linearSamplingMap.length; i++) {
  73080. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  73081. linearSamplingWeights[i] = linearSamplingMap[i].w;
  73082. }
  73083. // Replace with optimized
  73084. offsets = linearSamplingOffsets;
  73085. weights = linearSamplingWeights;
  73086. // Generate shaders
  73087. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  73088. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  73089. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  73090. var defines = "";
  73091. defines += this._staticDefines;
  73092. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  73093. if (this._staticDefines.indexOf("DOF") != -1) {
  73094. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  73095. varyingCount--;
  73096. }
  73097. for (var i = 0; i < varyingCount; i++) {
  73098. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  73099. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  73100. }
  73101. var depCount = 0;
  73102. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  73103. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  73104. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  73105. depCount++;
  73106. }
  73107. if (this.packedFloat) {
  73108. defines += "#define PACKEDFLOAT 1";
  73109. }
  73110. this.blockCompilation = false;
  73111. _super.prototype.updateEffect.call(this, defines, null, null, {
  73112. varyingCount: varyingCount,
  73113. depCount: depCount
  73114. }, onCompiled, onError);
  73115. };
  73116. /**
  73117. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  73118. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  73119. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  73120. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  73121. * The gaps between physical kernels are compensated for in the weighting of the samples
  73122. * @param idealKernel Ideal blur kernel.
  73123. * @return Nearest best kernel.
  73124. */
  73125. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  73126. var v = Math.round(idealKernel);
  73127. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  73128. var k = _a[_i];
  73129. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  73130. return Math.max(k, 3);
  73131. }
  73132. }
  73133. return Math.max(v, 3);
  73134. };
  73135. /**
  73136. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  73137. * @param x The point on the Gaussian distribution to sample.
  73138. * @return the value of the Gaussian function at x.
  73139. */
  73140. BlurPostProcess.prototype._gaussianWeight = function (x) {
  73141. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  73142. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  73143. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  73144. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  73145. // truncated at around 1.3% of peak strength.
  73146. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  73147. var sigma = (1 / 3);
  73148. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  73149. var exponent = -((x * x) / (2.0 * sigma * sigma));
  73150. var weight = (1.0 / denominator) * Math.exp(exponent);
  73151. return weight;
  73152. };
  73153. /**
  73154. * Generates a string that can be used as a floating point number in GLSL.
  73155. * @param x Value to print.
  73156. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  73157. * @return GLSL float string.
  73158. */
  73159. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  73160. if (decimalFigures === void 0) { decimalFigures = 8; }
  73161. return x.toFixed(decimalFigures).replace(/0+$/, '');
  73162. };
  73163. return BlurPostProcess;
  73164. }(BABYLON.PostProcess));
  73165. BABYLON.BlurPostProcess = BlurPostProcess;
  73166. })(BABYLON || (BABYLON = {}));
  73167. //# sourceMappingURL=babylon.blurPostProcess.js.map
  73168. "use strict";
  73169. var BABYLON;
  73170. (function (BABYLON) {
  73171. /**
  73172. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  73173. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  73174. * based on samples that have a large difference in distance than the center pixel.
  73175. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73176. */
  73177. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  73178. __extends(DepthOfFieldBlurPostProcess, _super);
  73179. /**
  73180. * Creates a new instance CircleOfConfusionPostProcess
  73181. * @param name The name of the effect.
  73182. * @param scene The scene the effect belongs to.
  73183. * @param direction The direction the blur should be applied.
  73184. * @param kernel The size of the kernel used to blur.
  73185. * @param options The required width/height ratio to downsize to before computing the render pass.
  73186. * @param camera The camera to apply the render pass to.
  73187. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  73188. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  73189. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73190. * @param engine The engine which the post process will be applied. (default: current engine)
  73191. * @param reusable If the post process can be reused on the same frame. (default: false)
  73192. * @param textureType Type of textures used when performing the post process. (default: 0)
  73193. * @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)
  73194. */
  73195. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  73196. if (imageToBlur === void 0) { imageToBlur = null; }
  73197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73198. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73199. if (blockCompilation === void 0) { blockCompilation = false; }
  73200. 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;
  73201. _this.direction = direction;
  73202. _this.onApplyObservable.add(function (effect) {
  73203. if (imageToBlur != null) {
  73204. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  73205. }
  73206. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73207. if (scene.activeCamera) {
  73208. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73209. }
  73210. });
  73211. return _this;
  73212. }
  73213. return DepthOfFieldBlurPostProcess;
  73214. }(BABYLON.BlurPostProcess));
  73215. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  73216. })(BABYLON || (BABYLON = {}));
  73217. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  73218. "use strict";
  73219. var BABYLON;
  73220. (function (BABYLON) {
  73221. /**
  73222. * Options to be set when merging outputs from the default pipeline.
  73223. */
  73224. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  73225. function DepthOfFieldMergePostProcessOptions() {
  73226. }
  73227. return DepthOfFieldMergePostProcessOptions;
  73228. }());
  73229. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  73230. /**
  73231. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73232. */
  73233. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  73234. __extends(DepthOfFieldMergePostProcess, _super);
  73235. /**
  73236. * Creates a new instance of DepthOfFieldMergePostProcess
  73237. * @param name The name of the effect.
  73238. * @param originalFromInput Post process which's input will be used for the merge.
  73239. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  73240. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  73241. * @param options The required width/height ratio to downsize to before computing the render pass.
  73242. * @param camera The camera to apply the render pass to.
  73243. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73244. * @param engine The engine which the post process will be applied. (default: current engine)
  73245. * @param reusable If the post process can be reused on the same frame. (default: false)
  73246. * @param textureType Type of textures used when performing the post process. (default: 0)
  73247. * @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)
  73248. */
  73249. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73250. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73251. if (blockCompilation === void 0) { blockCompilation = false; }
  73252. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73253. _this.blurSteps = blurSteps;
  73254. _this.onApplyObservable.add(function (effect) {
  73255. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73256. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  73257. blurSteps.forEach(function (step, index) {
  73258. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  73259. });
  73260. });
  73261. if (!blockCompilation) {
  73262. _this.updateEffect();
  73263. }
  73264. return _this;
  73265. }
  73266. /**
  73267. * Updates the effect with the current post process compile time values and recompiles the shader.
  73268. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73269. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73270. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73271. * @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
  73272. * @param onCompiled Called when the shader has been compiled.
  73273. * @param onError Called if there is an error when compiling a shader.
  73274. */
  73275. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73276. if (defines === void 0) { defines = null; }
  73277. if (uniforms === void 0) { uniforms = null; }
  73278. if (samplers === void 0) { samplers = null; }
  73279. if (!defines) {
  73280. defines = "";
  73281. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  73282. }
  73283. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  73284. };
  73285. return DepthOfFieldMergePostProcess;
  73286. }(BABYLON.PostProcess));
  73287. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  73288. })(BABYLON || (BABYLON = {}));
  73289. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  73290. "use strict";
  73291. var BABYLON;
  73292. (function (BABYLON) {
  73293. /**
  73294. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  73295. */
  73296. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  73297. __extends(CircleOfConfusionPostProcess, _super);
  73298. /**
  73299. * Creates a new instance CircleOfConfusionPostProcess
  73300. * @param name The name of the effect.
  73301. * @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.
  73302. * @param options The required width/height ratio to downsize to before computing the render pass.
  73303. * @param camera The camera to apply the render pass to.
  73304. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73305. * @param engine The engine which the post process will be applied. (default: current engine)
  73306. * @param reusable If the post process can be reused on the same frame. (default: false)
  73307. * @param textureType Type of textures used when performing the post process. (default: 0)
  73308. * @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)
  73309. */
  73310. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73311. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73312. if (blockCompilation === void 0) { blockCompilation = false; }
  73313. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73314. /**
  73315. * 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.
  73316. */
  73317. _this.lensSize = 50;
  73318. /**
  73319. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73320. */
  73321. _this.fStop = 1.4;
  73322. /**
  73323. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73324. */
  73325. _this.focusDistance = 2000;
  73326. /**
  73327. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  73328. */
  73329. _this.focalLength = 50;
  73330. _this._depthTexture = null;
  73331. _this._depthTexture = depthTexture;
  73332. _this.onApplyObservable.add(function (effect) {
  73333. if (!_this._depthTexture) {
  73334. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  73335. return;
  73336. }
  73337. effect.setTexture("depthSampler", _this._depthTexture);
  73338. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  73339. var aperture = _this.lensSize / _this.fStop;
  73340. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  73341. effect.setFloat('focusDistance', _this.focusDistance);
  73342. effect.setFloat('cocPrecalculation', cocPrecalculation);
  73343. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  73344. });
  73345. return _this;
  73346. }
  73347. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  73348. /**
  73349. * 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.
  73350. */
  73351. set: function (value) {
  73352. this._depthTexture = value;
  73353. },
  73354. enumerable: true,
  73355. configurable: true
  73356. });
  73357. return CircleOfConfusionPostProcess;
  73358. }(BABYLON.PostProcess));
  73359. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  73360. })(BABYLON || (BABYLON = {}));
  73361. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  73362. "use strict";
  73363. var BABYLON;
  73364. (function (BABYLON) {
  73365. /**
  73366. * Specifies the level of max blur that should be applied when using the depth of field effect
  73367. */
  73368. var DepthOfFieldEffectBlurLevel;
  73369. (function (DepthOfFieldEffectBlurLevel) {
  73370. /**
  73371. * Subtle blur
  73372. */
  73373. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  73374. /**
  73375. * Medium blur
  73376. */
  73377. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  73378. /**
  73379. * Large blur
  73380. */
  73381. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  73382. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  73383. ;
  73384. /**
  73385. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  73386. */
  73387. var DepthOfFieldEffect = /** @class */ (function (_super) {
  73388. __extends(DepthOfFieldEffect, _super);
  73389. /**
  73390. * Creates a new instance DepthOfFieldEffect
  73391. * @param scene The scene the effect belongs to.
  73392. * @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.
  73393. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73394. * @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)
  73395. */
  73396. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  73397. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  73398. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73399. if (blockCompilation === void 0) { blockCompilation = false; }
  73400. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  73401. return _this._effects;
  73402. }, true) || this;
  73403. /**
  73404. * Internal post processes in depth of field effect
  73405. */
  73406. _this._effects = [];
  73407. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  73408. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73409. // 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)
  73410. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  73411. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  73412. _this._depthOfFieldBlurY = [];
  73413. _this._depthOfFieldBlurX = [];
  73414. var blurCount = 1;
  73415. var kernelSize = 15;
  73416. switch (blurLevel) {
  73417. case DepthOfFieldEffectBlurLevel.High: {
  73418. blurCount = 3;
  73419. kernelSize = 51;
  73420. break;
  73421. }
  73422. case DepthOfFieldEffectBlurLevel.Medium: {
  73423. blurCount = 2;
  73424. kernelSize = 31;
  73425. break;
  73426. }
  73427. default: {
  73428. kernelSize = 15;
  73429. blurCount = 1;
  73430. break;
  73431. }
  73432. }
  73433. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  73434. var ratio = 1.0;
  73435. for (var i = 0; i < blurCount; i++) {
  73436. 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);
  73437. blurY.autoClear = false;
  73438. ratio = 0.75 / Math.pow(2, i);
  73439. 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);
  73440. blurX.autoClear = false;
  73441. _this._depthOfFieldBlurY.push(blurY);
  73442. _this._depthOfFieldBlurX.push(blurX);
  73443. }
  73444. // Set all post processes on the effect.
  73445. _this._effects = [_this._circleOfConfusion];
  73446. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  73447. _this._effects.push(_this._depthOfFieldBlurY[i]);
  73448. _this._effects.push(_this._depthOfFieldBlurX[i]);
  73449. }
  73450. // Merge blurred images with original image based on circleOfConfusion
  73451. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73452. _this._dofMerge.autoClear = false;
  73453. _this._effects.push(_this._dofMerge);
  73454. return _this;
  73455. }
  73456. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  73457. get: function () {
  73458. return this._circleOfConfusion.focalLength;
  73459. },
  73460. /**
  73461. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  73462. */
  73463. set: function (value) {
  73464. this._circleOfConfusion.focalLength = value;
  73465. },
  73466. enumerable: true,
  73467. configurable: true
  73468. });
  73469. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  73470. get: function () {
  73471. return this._circleOfConfusion.fStop;
  73472. },
  73473. /**
  73474. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  73475. */
  73476. set: function (value) {
  73477. this._circleOfConfusion.fStop = value;
  73478. },
  73479. enumerable: true,
  73480. configurable: true
  73481. });
  73482. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  73483. get: function () {
  73484. return this._circleOfConfusion.focusDistance;
  73485. },
  73486. /**
  73487. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  73488. */
  73489. set: function (value) {
  73490. this._circleOfConfusion.focusDistance = value;
  73491. },
  73492. enumerable: true,
  73493. configurable: true
  73494. });
  73495. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  73496. get: function () {
  73497. return this._circleOfConfusion.lensSize;
  73498. },
  73499. /**
  73500. * 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.
  73501. */
  73502. set: function (value) {
  73503. this._circleOfConfusion.lensSize = value;
  73504. },
  73505. enumerable: true,
  73506. configurable: true
  73507. });
  73508. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  73509. /**
  73510. * 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.
  73511. */
  73512. set: function (value) {
  73513. this._circleOfConfusion.depthTexture = value;
  73514. },
  73515. enumerable: true,
  73516. configurable: true
  73517. });
  73518. /**
  73519. * Disposes each of the internal effects for a given camera.
  73520. * @param camera The camera to dispose the effect on.
  73521. */
  73522. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  73523. for (var effect in this._effects) {
  73524. this._effects[effect].dispose(camera);
  73525. }
  73526. };
  73527. /**
  73528. * Internal
  73529. */
  73530. DepthOfFieldEffect.prototype._updateEffects = function () {
  73531. for (var effect in this._effects) {
  73532. this._effects[effect].updateEffect();
  73533. }
  73534. };
  73535. /**
  73536. * Internal
  73537. * @returns if all the contained post processes are ready.
  73538. */
  73539. DepthOfFieldEffect.prototype._isReady = function () {
  73540. for (var effect in this._effects) {
  73541. if (!this._effects[effect].isReady()) {
  73542. return false;
  73543. }
  73544. }
  73545. return true;
  73546. };
  73547. return DepthOfFieldEffect;
  73548. }(BABYLON.PostProcessRenderEffect));
  73549. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  73550. })(BABYLON || (BABYLON = {}));
  73551. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  73552. "use strict";
  73553. var BABYLON;
  73554. (function (BABYLON) {
  73555. /**
  73556. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  73557. */
  73558. var BloomMergePostProcess = /** @class */ (function (_super) {
  73559. __extends(BloomMergePostProcess, _super);
  73560. /**
  73561. * Creates a new instance of @see BloomMergePostProcess
  73562. * @param name The name of the effect.
  73563. * @param originalFromInput Post process which's input will be used for the merge.
  73564. * @param blurred Blurred highlights post process which's output will be used.
  73565. * @param weight Weight of the bloom to be added to the original input.
  73566. * @param options The required width/height ratio to downsize to before computing the render pass.
  73567. * @param camera The camera to apply the render pass to.
  73568. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73569. * @param engine The engine which the post process will be applied. (default: current engine)
  73570. * @param reusable If the post process can be reused on the same frame. (default: false)
  73571. * @param textureType Type of textures used when performing the post process. (default: 0)
  73572. * @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)
  73573. */
  73574. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73575. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73576. if (blockCompilation === void 0) { blockCompilation = false; }
  73577. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  73578. _this.weight = weight;
  73579. _this.onApplyObservable.add(function (effect) {
  73580. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  73581. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  73582. effect.setFloat("bloomWeight", _this.weight);
  73583. });
  73584. if (!blockCompilation) {
  73585. _this.updateEffect();
  73586. }
  73587. return _this;
  73588. }
  73589. return BloomMergePostProcess;
  73590. }(BABYLON.PostProcess));
  73591. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  73592. })(BABYLON || (BABYLON = {}));
  73593. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  73594. "use strict";
  73595. var BABYLON;
  73596. (function (BABYLON) {
  73597. /**
  73598. * 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.
  73599. */
  73600. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  73601. __extends(ExtractHighlightsPostProcess, _super);
  73602. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73603. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73604. if (blockCompilation === void 0) { blockCompilation = false; }
  73605. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73606. /**
  73607. * The luminance threshold, pixels below this value will be set to black.
  73608. */
  73609. _this.threshold = 0.9;
  73610. /**
  73611. * Internal
  73612. */
  73613. _this._exposure = 1;
  73614. /**
  73615. * Post process which has the input texture to be used when performing highlight extraction
  73616. */
  73617. _this._inputPostProcess = null;
  73618. _this.onApplyObservable.add(function (effect) {
  73619. if (_this._inputPostProcess) {
  73620. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  73621. }
  73622. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  73623. effect.setFloat('exposure', _this._exposure);
  73624. });
  73625. return _this;
  73626. }
  73627. return ExtractHighlightsPostProcess;
  73628. }(BABYLON.PostProcess));
  73629. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  73630. })(BABYLON || (BABYLON = {}));
  73631. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  73632. "use strict";
  73633. var BABYLON;
  73634. (function (BABYLON) {
  73635. /**
  73636. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  73637. */
  73638. var BloomEffect = /** @class */ (function (_super) {
  73639. __extends(BloomEffect, _super);
  73640. /**
  73641. * Creates a new instance of @see BloomEffect
  73642. * @param scene The scene the effect belongs to.
  73643. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  73644. * @param bloomKernel The size of the kernel to be used when applying the blur.
  73645. * @param bloomWeight The the strength of bloom.
  73646. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  73647. * @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)
  73648. */
  73649. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  73650. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  73651. if (blockCompilation === void 0) { blockCompilation = false; }
  73652. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  73653. return _this._effects;
  73654. }, true) || this;
  73655. _this.bloomScale = bloomScale;
  73656. /**
  73657. * Internal
  73658. */
  73659. _this._effects = [];
  73660. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73661. _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);
  73662. _this._blurX.alwaysForcePOT = true;
  73663. _this._blurX.autoClear = false;
  73664. _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);
  73665. _this._blurY.alwaysForcePOT = true;
  73666. _this._blurY.autoClear = false;
  73667. _this.kernel = bloomKernel;
  73668. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  73669. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  73670. _this._merge.autoClear = false;
  73671. _this._effects.push(_this._merge);
  73672. return _this;
  73673. }
  73674. Object.defineProperty(BloomEffect.prototype, "threshold", {
  73675. /**
  73676. * The luminance threshold to find bright areas of the image to bloom.
  73677. */
  73678. get: function () {
  73679. return this._downscale.threshold;
  73680. },
  73681. set: function (value) {
  73682. this._downscale.threshold = value;
  73683. },
  73684. enumerable: true,
  73685. configurable: true
  73686. });
  73687. Object.defineProperty(BloomEffect.prototype, "weight", {
  73688. /**
  73689. * The strength of the bloom.
  73690. */
  73691. get: function () {
  73692. return this._merge.weight;
  73693. },
  73694. set: function (value) {
  73695. this._merge.weight = value;
  73696. },
  73697. enumerable: true,
  73698. configurable: true
  73699. });
  73700. Object.defineProperty(BloomEffect.prototype, "kernel", {
  73701. /**
  73702. * Specifies the size of the bloom blur kernel, relative to the final output size
  73703. */
  73704. get: function () {
  73705. return this._blurX.kernel / this.bloomScale;
  73706. },
  73707. set: function (value) {
  73708. this._blurX.kernel = value * this.bloomScale;
  73709. this._blurY.kernel = value * this.bloomScale;
  73710. },
  73711. enumerable: true,
  73712. configurable: true
  73713. });
  73714. /**
  73715. * Disposes each of the internal effects for a given camera.
  73716. * @param camera The camera to dispose the effect on.
  73717. */
  73718. BloomEffect.prototype.disposeEffects = function (camera) {
  73719. for (var effect in this._effects) {
  73720. this._effects[effect].dispose(camera);
  73721. }
  73722. };
  73723. /**
  73724. * Internal
  73725. */
  73726. BloomEffect.prototype._updateEffects = function () {
  73727. for (var effect in this._effects) {
  73728. this._effects[effect].updateEffect();
  73729. }
  73730. };
  73731. /**
  73732. * Internal
  73733. * @returns if all the contained post processes are ready.
  73734. */
  73735. BloomEffect.prototype._isReady = function () {
  73736. for (var effect in this._effects) {
  73737. if (!this._effects[effect].isReady()) {
  73738. return false;
  73739. }
  73740. }
  73741. return true;
  73742. };
  73743. return BloomEffect;
  73744. }(BABYLON.PostProcessRenderEffect));
  73745. BABYLON.BloomEffect = BloomEffect;
  73746. })(BABYLON || (BABYLON = {}));
  73747. //# sourceMappingURL=babylon.bloomEffect.js.map
  73748. "use strict";
  73749. var BABYLON;
  73750. (function (BABYLON) {
  73751. /**
  73752. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  73753. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  73754. */
  73755. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  73756. __extends(DefaultRenderingPipeline, _super);
  73757. /**
  73758. * @constructor
  73759. * @param {string} name - The rendering pipeline name
  73760. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73761. * @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)
  73762. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73763. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  73764. */
  73765. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  73766. if (automaticBuild === void 0) { automaticBuild = true; }
  73767. var _this = _super.call(this, scene.getEngine(), name) || this;
  73768. _this._originalCameras = [];
  73769. /**
  73770. * ID of the sharpen post process,
  73771. */
  73772. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  73773. /**
  73774. * ID of the image processing post process;
  73775. */
  73776. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  73777. /**
  73778. * ID of the Fast Approximate Anti-Aliasing post process;
  73779. */
  73780. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  73781. /**
  73782. * ID of the chromatic aberration post process,
  73783. */
  73784. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  73785. /**
  73786. * ID of the grain post process
  73787. */
  73788. _this.GrainPostProcessId = "GrainPostProcessEffect";
  73789. /**
  73790. * Animations which can be used to tweak settings over a period of time
  73791. */
  73792. _this.animations = [];
  73793. _this._imageProcessingConfigurationObserver = null;
  73794. // Values
  73795. _this._sharpenEnabled = false;
  73796. _this._bloomEnabled = false;
  73797. _this._depthOfFieldEnabled = false;
  73798. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  73799. _this._fxaaEnabled = false;
  73800. _this._imageProcessingEnabled = true;
  73801. _this._bloomScale = 0.5;
  73802. _this._chromaticAberrationEnabled = false;
  73803. _this._grainEnabled = false;
  73804. _this._buildAllowed = true;
  73805. _this._resizeObserver = null;
  73806. _this._hardwareScaleLevel = 1.0;
  73807. _this._bloomKernel = 64;
  73808. /**
  73809. * Specifies the weight of the bloom in the final rendering
  73810. */
  73811. _this._bloomWeight = 0.15;
  73812. /**
  73813. * Specifies the luma threshold for the area that will be blurred by the bloom
  73814. */
  73815. _this._bloomThreshold = 0.9;
  73816. _this._samples = 1;
  73817. _this._hasCleared = false;
  73818. _this._prevPostProcess = null;
  73819. _this._prevPrevPostProcess = null;
  73820. _this._cameras = cameras || [];
  73821. _this._originalCameras = _this._cameras.slice();
  73822. _this._buildAllowed = automaticBuild;
  73823. // Initialize
  73824. _this._scene = scene;
  73825. var caps = _this._scene.getEngine().getCaps();
  73826. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  73827. // Misc
  73828. if (_this._hdr) {
  73829. if (caps.textureHalfFloatRender) {
  73830. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73831. }
  73832. else if (caps.textureFloatRender) {
  73833. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73834. }
  73835. }
  73836. else {
  73837. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73838. }
  73839. // Attach
  73840. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73841. var engine = _this._scene.getEngine();
  73842. // Create post processes before hand so they can be modified before enabled.
  73843. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  73844. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73845. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  73846. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  73847. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  73848. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73849. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  73850. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  73851. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  73852. _this._resizeObserver = engine.onResizeObservable.add(function () {
  73853. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  73854. _this.bloomKernel = _this.bloomKernel;
  73855. });
  73856. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  73857. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  73858. });
  73859. _this._buildPipeline();
  73860. return _this;
  73861. }
  73862. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  73863. get: function () {
  73864. return this._sharpenEnabled;
  73865. },
  73866. /**
  73867. * Enable or disable the sharpen process from the pipeline
  73868. */
  73869. set: function (enabled) {
  73870. if (this._sharpenEnabled === enabled) {
  73871. return;
  73872. }
  73873. this._sharpenEnabled = enabled;
  73874. this._buildPipeline();
  73875. },
  73876. enumerable: true,
  73877. configurable: true
  73878. });
  73879. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  73880. /**
  73881. * Specifies the size of the bloom blur kernel, relative to the final output size
  73882. */
  73883. get: function () {
  73884. return this._bloomKernel;
  73885. },
  73886. set: function (value) {
  73887. this._bloomKernel = value;
  73888. this.bloom.kernel = value / this._hardwareScaleLevel;
  73889. },
  73890. enumerable: true,
  73891. configurable: true
  73892. });
  73893. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  73894. get: function () {
  73895. return this._bloomWeight;
  73896. },
  73897. /**
  73898. * The strength of the bloom.
  73899. */
  73900. set: function (value) {
  73901. if (this._bloomWeight === value) {
  73902. return;
  73903. }
  73904. this.bloom.weight = value;
  73905. this._bloomWeight = value;
  73906. },
  73907. enumerable: true,
  73908. configurable: true
  73909. });
  73910. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  73911. get: function () {
  73912. return this._bloomThreshold;
  73913. },
  73914. /**
  73915. * The strength of the bloom.
  73916. */
  73917. set: function (value) {
  73918. if (this._bloomThreshold === value) {
  73919. return;
  73920. }
  73921. this.bloom.threshold = value;
  73922. this._bloomThreshold = value;
  73923. },
  73924. enumerable: true,
  73925. configurable: true
  73926. });
  73927. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  73928. get: function () {
  73929. return this._bloomScale;
  73930. },
  73931. /**
  73932. * The scale of the bloom, lower value will provide better performance.
  73933. */
  73934. set: function (value) {
  73935. if (this._bloomScale === value) {
  73936. return;
  73937. }
  73938. this._bloomScale = value;
  73939. // recreate bloom and dispose old as this setting is not dynamic
  73940. this._rebuildBloom();
  73941. this._buildPipeline();
  73942. },
  73943. enumerable: true,
  73944. configurable: true
  73945. });
  73946. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  73947. get: function () {
  73948. return this._bloomEnabled;
  73949. },
  73950. /**
  73951. * Enable or disable the bloom from the pipeline
  73952. */
  73953. set: function (enabled) {
  73954. if (this._bloomEnabled === enabled) {
  73955. return;
  73956. }
  73957. this._bloomEnabled = enabled;
  73958. this._buildPipeline();
  73959. },
  73960. enumerable: true,
  73961. configurable: true
  73962. });
  73963. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  73964. // recreate bloom and dispose old as this setting is not dynamic
  73965. var oldBloom = this.bloom;
  73966. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  73967. this.bloom.threshold = oldBloom.threshold;
  73968. for (var i = 0; i < this._cameras.length; i++) {
  73969. oldBloom.disposeEffects(this._cameras[i]);
  73970. }
  73971. };
  73972. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  73973. /**
  73974. * If the depth of field is enabled.
  73975. */
  73976. get: function () {
  73977. return this._depthOfFieldEnabled;
  73978. },
  73979. set: function (enabled) {
  73980. if (this._depthOfFieldEnabled === enabled) {
  73981. return;
  73982. }
  73983. this._depthOfFieldEnabled = enabled;
  73984. this._buildPipeline();
  73985. },
  73986. enumerable: true,
  73987. configurable: true
  73988. });
  73989. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  73990. /**
  73991. * Blur level of the depth of field effect. (Higher blur will effect performance)
  73992. */
  73993. get: function () {
  73994. return this._depthOfFieldBlurLevel;
  73995. },
  73996. set: function (value) {
  73997. if (this._depthOfFieldBlurLevel === value) {
  73998. return;
  73999. }
  74000. this._depthOfFieldBlurLevel = value;
  74001. // recreate dof and dispose old as this setting is not dynamic
  74002. var oldDof = this.depthOfField;
  74003. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  74004. this.depthOfField.focalLength = oldDof.focalLength;
  74005. this.depthOfField.focusDistance = oldDof.focusDistance;
  74006. this.depthOfField.fStop = oldDof.fStop;
  74007. this.depthOfField.lensSize = oldDof.lensSize;
  74008. for (var i = 0; i < this._cameras.length; i++) {
  74009. oldDof.disposeEffects(this._cameras[i]);
  74010. }
  74011. this._buildPipeline();
  74012. },
  74013. enumerable: true,
  74014. configurable: true
  74015. });
  74016. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  74017. get: function () {
  74018. return this._fxaaEnabled;
  74019. },
  74020. /**
  74021. * If the anti aliasing is enabled.
  74022. */
  74023. set: function (enabled) {
  74024. if (this._fxaaEnabled === enabled) {
  74025. return;
  74026. }
  74027. this._fxaaEnabled = enabled;
  74028. this._buildPipeline();
  74029. },
  74030. enumerable: true,
  74031. configurable: true
  74032. });
  74033. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  74034. get: function () {
  74035. return this._samples;
  74036. },
  74037. /**
  74038. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  74039. */
  74040. set: function (sampleCount) {
  74041. if (this._samples === sampleCount) {
  74042. return;
  74043. }
  74044. this._samples = sampleCount;
  74045. this._buildPipeline();
  74046. },
  74047. enumerable: true,
  74048. configurable: true
  74049. });
  74050. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  74051. get: function () {
  74052. return this._imageProcessingEnabled;
  74053. },
  74054. /**
  74055. * If image processing is enabled.
  74056. */
  74057. set: function (enabled) {
  74058. if (this._imageProcessingEnabled === enabled) {
  74059. return;
  74060. }
  74061. this._imageProcessingEnabled = enabled;
  74062. this._buildPipeline();
  74063. },
  74064. enumerable: true,
  74065. configurable: true
  74066. });
  74067. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  74068. get: function () {
  74069. return this._chromaticAberrationEnabled;
  74070. },
  74071. /**
  74072. * Enable or disable the chromaticAberration process from the pipeline
  74073. */
  74074. set: function (enabled) {
  74075. if (this._chromaticAberrationEnabled === enabled) {
  74076. return;
  74077. }
  74078. this._chromaticAberrationEnabled = enabled;
  74079. this._buildPipeline();
  74080. },
  74081. enumerable: true,
  74082. configurable: true
  74083. });
  74084. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  74085. get: function () {
  74086. return this._grainEnabled;
  74087. },
  74088. /**
  74089. * Enable or disable the grain process from the pipeline
  74090. */
  74091. set: function (enabled) {
  74092. if (this._grainEnabled === enabled) {
  74093. return;
  74094. }
  74095. this._grainEnabled = enabled;
  74096. this._buildPipeline();
  74097. },
  74098. enumerable: true,
  74099. configurable: true
  74100. });
  74101. /**
  74102. * Force the compilation of the entire pipeline.
  74103. */
  74104. DefaultRenderingPipeline.prototype.prepare = function () {
  74105. var previousState = this._buildAllowed;
  74106. this._buildAllowed = true;
  74107. this._buildPipeline();
  74108. this._buildAllowed = previousState;
  74109. };
  74110. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  74111. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  74112. if (this._hasCleared) {
  74113. postProcess.autoClear = false;
  74114. }
  74115. else {
  74116. postProcess.autoClear = true;
  74117. this._scene.autoClear = false;
  74118. this._hasCleared = true;
  74119. }
  74120. if (!skipTextureSharing) {
  74121. if (this._prevPrevPostProcess) {
  74122. postProcess.shareOutputWith(this._prevPrevPostProcess);
  74123. }
  74124. else {
  74125. postProcess.useOwnOutput();
  74126. }
  74127. if (this._prevPostProcess) {
  74128. this._prevPrevPostProcess = this._prevPostProcess;
  74129. }
  74130. this._prevPostProcess = postProcess;
  74131. }
  74132. };
  74133. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  74134. var _this = this;
  74135. if (!this._buildAllowed) {
  74136. return;
  74137. }
  74138. this._scene.autoClear = true;
  74139. var engine = this._scene.getEngine();
  74140. this._disposePostProcesses();
  74141. if (this._cameras !== null) {
  74142. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74143. // get back cameras to be used to reattach pipeline
  74144. this._cameras = this._originalCameras.slice();
  74145. }
  74146. this._reset();
  74147. this._prevPostProcess = null;
  74148. this._prevPrevPostProcess = null;
  74149. this._hasCleared = false;
  74150. if (this.depthOfFieldEnabled) {
  74151. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  74152. this.depthOfField.depthTexture = depthTexture;
  74153. if (!this.depthOfField._isReady()) {
  74154. this.depthOfField._updateEffects();
  74155. }
  74156. this.addEffect(this.depthOfField);
  74157. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  74158. }
  74159. if (this.bloomEnabled) {
  74160. if (!this.bloom._isReady()) {
  74161. this.bloom._updateEffects();
  74162. }
  74163. this.addEffect(this.bloom);
  74164. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  74165. }
  74166. if (this._imageProcessingEnabled) {
  74167. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74168. if (this._hdr) {
  74169. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  74170. this._setAutoClearAndTextureSharing(this.imageProcessing);
  74171. }
  74172. else {
  74173. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  74174. }
  74175. }
  74176. if (this.sharpenEnabled) {
  74177. if (!this.sharpen.isReady()) {
  74178. this.sharpen.updateEffect();
  74179. }
  74180. this.addEffect(this._sharpenEffect);
  74181. this._setAutoClearAndTextureSharing(this.sharpen);
  74182. }
  74183. if (this.grainEnabled) {
  74184. if (!this.grain.isReady()) {
  74185. this.grain.updateEffect();
  74186. }
  74187. this.addEffect(this._grainEffect);
  74188. this._setAutoClearAndTextureSharing(this.grain);
  74189. }
  74190. if (this.chromaticAberrationEnabled) {
  74191. if (!this.chromaticAberration.isReady()) {
  74192. this.chromaticAberration.updateEffect();
  74193. }
  74194. this.addEffect(this._chromaticAberrationEffect);
  74195. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  74196. }
  74197. if (this.fxaaEnabled) {
  74198. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  74199. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  74200. this._setAutoClearAndTextureSharing(this.fxaa, true);
  74201. }
  74202. if (this._cameras !== null) {
  74203. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74204. }
  74205. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  74206. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  74207. }
  74208. };
  74209. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  74210. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  74211. for (var i = 0; i < this._cameras.length; i++) {
  74212. var camera = this._cameras[i];
  74213. if (this.imageProcessing) {
  74214. this.imageProcessing.dispose(camera);
  74215. }
  74216. if (this.fxaa) {
  74217. this.fxaa.dispose(camera);
  74218. }
  74219. // These are created in the constructor and should not be disposed on every pipeline change
  74220. if (disposeNonRecreated) {
  74221. if (this.sharpen) {
  74222. this.sharpen.dispose(camera);
  74223. }
  74224. if (this.depthOfField) {
  74225. this.depthOfField.disposeEffects(camera);
  74226. }
  74227. if (this.bloom) {
  74228. this.bloom.disposeEffects(camera);
  74229. }
  74230. if (this.chromaticAberration) {
  74231. this.chromaticAberration.dispose(camera);
  74232. }
  74233. if (this.grain) {
  74234. this.grain.dispose(camera);
  74235. }
  74236. }
  74237. }
  74238. this.imageProcessing = null;
  74239. this.fxaa = null;
  74240. if (disposeNonRecreated) {
  74241. this.sharpen = null;
  74242. this._sharpenEffect = null;
  74243. this.depthOfField = null;
  74244. this.bloom = null;
  74245. this.chromaticAberration = null;
  74246. this._chromaticAberrationEffect = null;
  74247. this.grain = null;
  74248. this._grainEffect = null;
  74249. }
  74250. };
  74251. /**
  74252. * Dispose of the pipeline and stop all post processes
  74253. */
  74254. DefaultRenderingPipeline.prototype.dispose = function () {
  74255. this._disposePostProcesses(true);
  74256. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74257. this._scene.autoClear = true;
  74258. if (this._resizeObserver) {
  74259. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  74260. this._resizeObserver = null;
  74261. }
  74262. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  74263. _super.prototype.dispose.call(this);
  74264. };
  74265. /**
  74266. * Serialize the rendering pipeline (Used when exporting)
  74267. * @returns the serialized object
  74268. */
  74269. DefaultRenderingPipeline.prototype.serialize = function () {
  74270. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74271. serializationObject.customType = "DefaultRenderingPipeline";
  74272. return serializationObject;
  74273. };
  74274. /**
  74275. * Parse the serialized pipeline
  74276. * @param source Source pipeline.
  74277. * @param scene The scene to load the pipeline to.
  74278. * @param rootUrl The URL of the serialized pipeline.
  74279. * @returns An instantiated pipeline from the serialized object.
  74280. */
  74281. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74282. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  74283. };
  74284. __decorate([
  74285. BABYLON.serialize()
  74286. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  74287. __decorate([
  74288. BABYLON.serialize()
  74289. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  74290. __decorate([
  74291. BABYLON.serialize()
  74292. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  74293. __decorate([
  74294. BABYLON.serialize()
  74295. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  74296. __decorate([
  74297. BABYLON.serialize()
  74298. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  74299. __decorate([
  74300. BABYLON.serialize()
  74301. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  74302. __decorate([
  74303. BABYLON.serialize()
  74304. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  74305. __decorate([
  74306. BABYLON.serialize()
  74307. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  74308. __decorate([
  74309. BABYLON.serialize()
  74310. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  74311. __decorate([
  74312. BABYLON.serialize()
  74313. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  74314. __decorate([
  74315. BABYLON.serialize()
  74316. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  74317. __decorate([
  74318. BABYLON.serialize()
  74319. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  74320. __decorate([
  74321. BABYLON.serialize()
  74322. ], DefaultRenderingPipeline.prototype, "samples", null);
  74323. __decorate([
  74324. BABYLON.serialize()
  74325. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  74326. __decorate([
  74327. BABYLON.serialize()
  74328. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  74329. __decorate([
  74330. BABYLON.serialize()
  74331. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  74332. return DefaultRenderingPipeline;
  74333. }(BABYLON.PostProcessRenderPipeline));
  74334. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  74335. })(BABYLON || (BABYLON = {}));
  74336. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  74337. "use strict";
  74338. var BABYLON;
  74339. (function (BABYLON) {
  74340. /**
  74341. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  74342. */
  74343. var GeometryBufferRenderer = /** @class */ (function () {
  74344. /**
  74345. * Creates a new G Buffer for the scene
  74346. * @param scene The scene the buffer belongs to
  74347. * @param ratio How big is the buffer related to the main canvas.
  74348. */
  74349. function GeometryBufferRenderer(scene, ratio) {
  74350. if (ratio === void 0) { ratio = 1; }
  74351. this._enablePosition = false;
  74352. this._scene = scene;
  74353. this._ratio = ratio;
  74354. // Render target
  74355. this._createRenderTargets();
  74356. }
  74357. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  74358. /**
  74359. * Set the render list (meshes to be rendered) used in the G buffer.
  74360. */
  74361. set: function (meshes) {
  74362. this._multiRenderTarget.renderList = meshes;
  74363. },
  74364. enumerable: true,
  74365. configurable: true
  74366. });
  74367. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  74368. /**
  74369. * Gets wether or not G buffer are supported by the running hardware.
  74370. * This requires draw buffer supports
  74371. */
  74372. get: function () {
  74373. return this._multiRenderTarget.isSupported;
  74374. },
  74375. enumerable: true,
  74376. configurable: true
  74377. });
  74378. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  74379. /**
  74380. * Gets wether or not position are enabled for the G buffer.
  74381. */
  74382. get: function () {
  74383. return this._enablePosition;
  74384. },
  74385. /**
  74386. * Sets wether or not position are enabled for the G buffer.
  74387. */
  74388. set: function (enable) {
  74389. this._enablePosition = enable;
  74390. this.dispose();
  74391. this._createRenderTargets();
  74392. },
  74393. enumerable: true,
  74394. configurable: true
  74395. });
  74396. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  74397. /**
  74398. * Gets the scene associated with the buffer.
  74399. */
  74400. get: function () {
  74401. return this._scene;
  74402. },
  74403. enumerable: true,
  74404. configurable: true
  74405. });
  74406. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  74407. /**
  74408. * Gets the ratio used by the buffer during its creation.
  74409. * How big is the buffer related to the main canvas.
  74410. */
  74411. get: function () {
  74412. return this._ratio;
  74413. },
  74414. enumerable: true,
  74415. configurable: true
  74416. });
  74417. /**
  74418. * Checks wether everything is ready to render a submesh to the G buffer.
  74419. * @param subMesh the submesh to check readiness for
  74420. * @param useInstances is the mesh drawn using instance or not
  74421. * @returns true if ready otherwise false
  74422. */
  74423. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  74424. var material = subMesh.getMaterial();
  74425. if (material && material.disableDepthWrite) {
  74426. return false;
  74427. }
  74428. var defines = [];
  74429. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  74430. var mesh = subMesh.getMesh();
  74431. // Alpha test
  74432. if (material && material.needAlphaTesting()) {
  74433. defines.push("#define ALPHATEST");
  74434. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74435. attribs.push(BABYLON.VertexBuffer.UVKind);
  74436. defines.push("#define UV1");
  74437. }
  74438. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74439. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74440. defines.push("#define UV2");
  74441. }
  74442. }
  74443. // Buffers
  74444. if (this._enablePosition) {
  74445. defines.push("#define POSITION");
  74446. }
  74447. // Bones
  74448. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74449. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74450. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74451. if (mesh.numBoneInfluencers > 4) {
  74452. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74453. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74454. }
  74455. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74456. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  74457. }
  74458. else {
  74459. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74460. }
  74461. // Instances
  74462. if (useInstances) {
  74463. defines.push("#define INSTANCES");
  74464. attribs.push("world0");
  74465. attribs.push("world1");
  74466. attribs.push("world2");
  74467. attribs.push("world3");
  74468. }
  74469. // Get correct effect
  74470. var join = defines.join("\n");
  74471. if (this._cachedDefines !== join) {
  74472. this._cachedDefines = join;
  74473. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  74474. }
  74475. return this._effect.isReady();
  74476. };
  74477. /**
  74478. * Gets the current underlying G Buffer.
  74479. * @returns the buffer
  74480. */
  74481. GeometryBufferRenderer.prototype.getGBuffer = function () {
  74482. return this._multiRenderTarget;
  74483. };
  74484. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  74485. /**
  74486. * Gets the number of samples used to render the buffer (anti aliasing).
  74487. */
  74488. get: function () {
  74489. return this._multiRenderTarget.samples;
  74490. },
  74491. /**
  74492. * Sets the number of samples used to render the buffer (anti aliasing).
  74493. */
  74494. set: function (value) {
  74495. this._multiRenderTarget.samples = value;
  74496. },
  74497. enumerable: true,
  74498. configurable: true
  74499. });
  74500. /**
  74501. * Disposes the renderer and frees up associated resources.
  74502. */
  74503. GeometryBufferRenderer.prototype.dispose = function () {
  74504. this.getGBuffer().dispose();
  74505. };
  74506. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  74507. var _this = this;
  74508. var engine = this._scene.getEngine();
  74509. var count = this._enablePosition ? 3 : 2;
  74510. 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 });
  74511. if (!this.isSupported) {
  74512. return;
  74513. }
  74514. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74515. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74516. this._multiRenderTarget.refreshRate = 1;
  74517. this._multiRenderTarget.renderParticles = false;
  74518. this._multiRenderTarget.renderList = null;
  74519. // set default depth value to 1.0 (far away)
  74520. this._multiRenderTarget.onClearObservable.add(function (engine) {
  74521. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  74522. });
  74523. // Custom render function
  74524. var renderSubMesh = function (subMesh) {
  74525. var mesh = subMesh.getRenderingMesh();
  74526. var scene = _this._scene;
  74527. var engine = scene.getEngine();
  74528. var material = subMesh.getMaterial();
  74529. if (!material) {
  74530. return;
  74531. }
  74532. // Culling
  74533. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74534. // Managing instances
  74535. var batch = mesh._getInstancesRenderList(subMesh._id);
  74536. if (batch.mustReturn) {
  74537. return;
  74538. }
  74539. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74540. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  74541. engine.enableEffect(_this._effect);
  74542. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74543. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74544. _this._effect.setMatrix("view", scene.getViewMatrix());
  74545. // Alpha test
  74546. if (material && material.needAlphaTesting()) {
  74547. var alphaTexture = material.getAlphaTestTexture();
  74548. if (alphaTexture) {
  74549. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74550. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74551. }
  74552. }
  74553. // Bones
  74554. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74555. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74556. }
  74557. // Draw
  74558. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74559. }
  74560. };
  74561. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74562. var index;
  74563. if (depthOnlySubMeshes.length) {
  74564. engine.setColorWrite(false);
  74565. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74566. renderSubMesh(depthOnlySubMeshes.data[index]);
  74567. }
  74568. engine.setColorWrite(true);
  74569. }
  74570. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74571. renderSubMesh(opaqueSubMeshes.data[index]);
  74572. }
  74573. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74574. renderSubMesh(alphaTestSubMeshes.data[index]);
  74575. }
  74576. };
  74577. };
  74578. return GeometryBufferRenderer;
  74579. }());
  74580. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  74581. })(BABYLON || (BABYLON = {}));
  74582. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  74583. "use strict";
  74584. var BABYLON;
  74585. (function (BABYLON) {
  74586. var RefractionPostProcess = /** @class */ (function (_super) {
  74587. __extends(RefractionPostProcess, _super);
  74588. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  74589. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  74590. _this.color = color;
  74591. _this.depth = depth;
  74592. _this.colorLevel = colorLevel;
  74593. _this._ownRefractionTexture = true;
  74594. _this.onActivateObservable.add(function (cam) {
  74595. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  74596. });
  74597. _this.onApplyObservable.add(function (effect) {
  74598. effect.setColor3("baseColor", _this.color);
  74599. effect.setFloat("depth", _this.depth);
  74600. effect.setFloat("colorLevel", _this.colorLevel);
  74601. effect.setTexture("refractionSampler", _this._refTexture);
  74602. });
  74603. return _this;
  74604. }
  74605. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  74606. /**
  74607. * Gets or sets the refraction texture
  74608. * Please note that you are responsible for disposing the texture if you set it manually
  74609. */
  74610. get: function () {
  74611. return this._refTexture;
  74612. },
  74613. set: function (value) {
  74614. if (this._refTexture && this._ownRefractionTexture) {
  74615. this._refTexture.dispose();
  74616. }
  74617. this._refTexture = value;
  74618. this._ownRefractionTexture = false;
  74619. },
  74620. enumerable: true,
  74621. configurable: true
  74622. });
  74623. // Methods
  74624. RefractionPostProcess.prototype.dispose = function (camera) {
  74625. if (this._refTexture && this._ownRefractionTexture) {
  74626. this._refTexture.dispose();
  74627. this._refTexture = null;
  74628. }
  74629. _super.prototype.dispose.call(this, camera);
  74630. };
  74631. return RefractionPostProcess;
  74632. }(BABYLON.PostProcess));
  74633. BABYLON.RefractionPostProcess = RefractionPostProcess;
  74634. })(BABYLON || (BABYLON = {}));
  74635. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  74636. "use strict";
  74637. var BABYLON;
  74638. (function (BABYLON) {
  74639. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  74640. __extends(BlackAndWhitePostProcess, _super);
  74641. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  74642. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  74643. _this.degree = 1;
  74644. _this.onApplyObservable.add(function (effect) {
  74645. effect.setFloat("degree", _this.degree);
  74646. });
  74647. return _this;
  74648. }
  74649. return BlackAndWhitePostProcess;
  74650. }(BABYLON.PostProcess));
  74651. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  74652. })(BABYLON || (BABYLON = {}));
  74653. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  74654. "use strict";
  74655. var BABYLON;
  74656. (function (BABYLON) {
  74657. /**
  74658. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  74659. * input texture to perform effects such as edge detection or sharpening
  74660. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74661. */
  74662. var ConvolutionPostProcess = /** @class */ (function (_super) {
  74663. __extends(ConvolutionPostProcess, _super);
  74664. /**
  74665. * Creates a new instance ConvolutionPostProcess
  74666. * @param name The name of the effect.
  74667. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  74668. * @param options The required width/height ratio to downsize to before computing the render pass.
  74669. * @param camera The camera to apply the render pass to.
  74670. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74671. * @param engine The engine which the post process will be applied. (default: current engine)
  74672. * @param reusable If the post process can be reused on the same frame. (default: false)
  74673. * @param textureType Type of textures used when performing the post process. (default: 0)
  74674. */
  74675. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  74676. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74677. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  74678. _this.kernel = kernel;
  74679. _this.onApply = function (effect) {
  74680. effect.setFloat2("screenSize", _this.width, _this.height);
  74681. effect.setArray("kernel", _this.kernel);
  74682. };
  74683. return _this;
  74684. }
  74685. // Statics
  74686. /**
  74687. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74688. */
  74689. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  74690. /**
  74691. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74692. */
  74693. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  74694. /**
  74695. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74696. */
  74697. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  74698. /**
  74699. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74700. */
  74701. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  74702. /**
  74703. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74704. */
  74705. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  74706. /**
  74707. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  74708. */
  74709. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  74710. return ConvolutionPostProcess;
  74711. }(BABYLON.PostProcess));
  74712. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  74713. })(BABYLON || (BABYLON = {}));
  74714. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  74715. "use strict";
  74716. var BABYLON;
  74717. (function (BABYLON) {
  74718. var FilterPostProcess = /** @class */ (function (_super) {
  74719. __extends(FilterPostProcess, _super);
  74720. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  74721. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  74722. _this.kernelMatrix = kernelMatrix;
  74723. _this.onApply = function (effect) {
  74724. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  74725. };
  74726. return _this;
  74727. }
  74728. return FilterPostProcess;
  74729. }(BABYLON.PostProcess));
  74730. BABYLON.FilterPostProcess = FilterPostProcess;
  74731. })(BABYLON || (BABYLON = {}));
  74732. //# sourceMappingURL=babylon.filterPostProcess.js.map
  74733. "use strict";
  74734. var BABYLON;
  74735. (function (BABYLON) {
  74736. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  74737. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  74738. __extends(VolumetricLightScatteringPostProcess, _super);
  74739. /**
  74740. * @constructor
  74741. * @param {string} name - The post-process name
  74742. * @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)
  74743. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  74744. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  74745. * @param {number} samples - The post-process quality, default 100
  74746. * @param {number} samplingMode - The post-process filtering mode
  74747. * @param {BABYLON.Engine} engine - The babylon engine
  74748. * @param {boolean} reusable - If the post-process is reusable
  74749. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  74750. */
  74751. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  74752. if (samples === void 0) { samples = 100; }
  74753. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74754. 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;
  74755. _this._screenCoordinates = BABYLON.Vector2.Zero();
  74756. /**
  74757. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  74758. */
  74759. _this.customMeshPosition = BABYLON.Vector3.Zero();
  74760. /**
  74761. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  74762. */
  74763. _this.useCustomMeshPosition = false;
  74764. /**
  74765. * If the post-process should inverse the light scattering direction
  74766. */
  74767. _this.invert = true;
  74768. /**
  74769. * Array containing the excluded meshes not rendered in the internal pass
  74770. */
  74771. _this.excludedMeshes = new Array();
  74772. /**
  74773. * Controls the overall intensity of the post-process
  74774. */
  74775. _this.exposure = 0.3;
  74776. /**
  74777. * Dissipates each sample's contribution in range [0, 1]
  74778. */
  74779. _this.decay = 0.96815;
  74780. /**
  74781. * Controls the overall intensity of each sample
  74782. */
  74783. _this.weight = 0.58767;
  74784. /**
  74785. * Controls the density of each sample
  74786. */
  74787. _this.density = 0.926;
  74788. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  74789. engine = scene.getEngine();
  74790. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  74791. // Configure mesh
  74792. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  74793. // Configure
  74794. _this._createPass(scene, ratio.passRatio || ratio);
  74795. _this.onActivate = function (camera) {
  74796. if (!_this.isSupported) {
  74797. _this.dispose(camera);
  74798. }
  74799. _this.onActivate = null;
  74800. };
  74801. _this.onApplyObservable.add(function (effect) {
  74802. _this._updateMeshScreenCoordinates(scene);
  74803. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  74804. effect.setFloat("exposure", _this.exposure);
  74805. effect.setFloat("decay", _this.decay);
  74806. effect.setFloat("weight", _this.weight);
  74807. effect.setFloat("density", _this.density);
  74808. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  74809. });
  74810. return _this;
  74811. }
  74812. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  74813. get: function () {
  74814. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  74815. return false;
  74816. },
  74817. set: function (useDiffuseColor) {
  74818. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  74819. },
  74820. enumerable: true,
  74821. configurable: true
  74822. });
  74823. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  74824. return "VolumetricLightScatteringPostProcess";
  74825. };
  74826. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  74827. var mesh = subMesh.getMesh();
  74828. // Render this.mesh as default
  74829. if (mesh === this.mesh && mesh.material) {
  74830. return mesh.material.isReady(mesh);
  74831. }
  74832. var defines = [];
  74833. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74834. var material = subMesh.getMaterial();
  74835. // Alpha test
  74836. if (material) {
  74837. if (material.needAlphaTesting()) {
  74838. defines.push("#define ALPHATEST");
  74839. }
  74840. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74841. attribs.push(BABYLON.VertexBuffer.UVKind);
  74842. defines.push("#define UV1");
  74843. }
  74844. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74845. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74846. defines.push("#define UV2");
  74847. }
  74848. }
  74849. // Bones
  74850. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74851. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74852. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74853. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74854. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  74855. }
  74856. else {
  74857. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74858. }
  74859. // Instances
  74860. if (useInstances) {
  74861. defines.push("#define INSTANCES");
  74862. attribs.push("world0");
  74863. attribs.push("world1");
  74864. attribs.push("world2");
  74865. attribs.push("world3");
  74866. }
  74867. // Get correct effect
  74868. var join = defines.join("\n");
  74869. if (this._cachedDefines !== join) {
  74870. this._cachedDefines = join;
  74871. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  74872. }
  74873. return this._volumetricLightScatteringPass.isReady();
  74874. };
  74875. /**
  74876. * Sets the new light position for light scattering effect
  74877. * @param {BABYLON.Vector3} The new custom light position
  74878. */
  74879. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  74880. this.customMeshPosition = position;
  74881. };
  74882. /**
  74883. * Returns the light position for light scattering effect
  74884. * @return {BABYLON.Vector3} The custom light position
  74885. */
  74886. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  74887. return this.customMeshPosition;
  74888. };
  74889. /**
  74890. * Disposes the internal assets and detaches the post-process from the camera
  74891. */
  74892. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  74893. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  74894. if (rttIndex !== -1) {
  74895. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  74896. }
  74897. this._volumetricLightScatteringRTT.dispose();
  74898. _super.prototype.dispose.call(this, camera);
  74899. };
  74900. /**
  74901. * Returns the render target texture used by the post-process
  74902. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  74903. */
  74904. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  74905. return this._volumetricLightScatteringRTT;
  74906. };
  74907. // Private methods
  74908. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  74909. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  74910. return true;
  74911. }
  74912. return false;
  74913. };
  74914. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  74915. var _this = this;
  74916. var engine = scene.getEngine();
  74917. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74918. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74919. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74920. this._volumetricLightScatteringRTT.renderList = null;
  74921. this._volumetricLightScatteringRTT.renderParticles = false;
  74922. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  74923. var camera = this.getCamera();
  74924. if (camera) {
  74925. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  74926. }
  74927. else {
  74928. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  74929. }
  74930. // Custom render function for submeshes
  74931. var renderSubMesh = function (subMesh) {
  74932. var mesh = subMesh.getRenderingMesh();
  74933. if (_this._meshExcluded(mesh)) {
  74934. return;
  74935. }
  74936. var material = subMesh.getMaterial();
  74937. if (!material) {
  74938. return;
  74939. }
  74940. var scene = mesh.getScene();
  74941. var engine = scene.getEngine();
  74942. // Culling
  74943. engine.setState(material.backFaceCulling);
  74944. // Managing instances
  74945. var batch = mesh._getInstancesRenderList(subMesh._id);
  74946. if (batch.mustReturn) {
  74947. return;
  74948. }
  74949. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74950. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  74951. var effect = _this._volumetricLightScatteringPass;
  74952. if (mesh === _this.mesh) {
  74953. if (subMesh.effect) {
  74954. effect = subMesh.effect;
  74955. }
  74956. else {
  74957. effect = material.getEffect();
  74958. }
  74959. }
  74960. engine.enableEffect(effect);
  74961. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  74962. if (mesh === _this.mesh) {
  74963. material.bind(mesh.getWorldMatrix(), mesh);
  74964. }
  74965. else {
  74966. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  74967. // Alpha test
  74968. if (material && material.needAlphaTesting()) {
  74969. var alphaTexture = material.getAlphaTestTexture();
  74970. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  74971. if (alphaTexture) {
  74972. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74973. }
  74974. }
  74975. // Bones
  74976. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74977. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74978. }
  74979. }
  74980. // Draw
  74981. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  74982. }
  74983. };
  74984. // Render target texture callbacks
  74985. var savedSceneClearColor;
  74986. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  74987. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  74988. savedSceneClearColor = scene.clearColor;
  74989. scene.clearColor = sceneClearColor;
  74990. });
  74991. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  74992. scene.clearColor = savedSceneClearColor;
  74993. });
  74994. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74995. var engine = scene.getEngine();
  74996. var index;
  74997. if (depthOnlySubMeshes.length) {
  74998. engine.setColorWrite(false);
  74999. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75000. renderSubMesh(depthOnlySubMeshes.data[index]);
  75001. }
  75002. engine.setColorWrite(true);
  75003. }
  75004. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75005. renderSubMesh(opaqueSubMeshes.data[index]);
  75006. }
  75007. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75008. renderSubMesh(alphaTestSubMeshes.data[index]);
  75009. }
  75010. if (transparentSubMeshes.length) {
  75011. // Sort sub meshes
  75012. for (index = 0; index < transparentSubMeshes.length; index++) {
  75013. var submesh = transparentSubMeshes.data[index];
  75014. var boundingInfo = submesh.getBoundingInfo();
  75015. if (boundingInfo && scene.activeCamera) {
  75016. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  75017. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  75018. }
  75019. }
  75020. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  75021. sortedArray.sort(function (a, b) {
  75022. // Alpha index first
  75023. if (a._alphaIndex > b._alphaIndex) {
  75024. return 1;
  75025. }
  75026. if (a._alphaIndex < b._alphaIndex) {
  75027. return -1;
  75028. }
  75029. // Then distance to camera
  75030. if (a._distanceToCamera < b._distanceToCamera) {
  75031. return 1;
  75032. }
  75033. if (a._distanceToCamera > b._distanceToCamera) {
  75034. return -1;
  75035. }
  75036. return 0;
  75037. });
  75038. // Render sub meshes
  75039. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  75040. for (index = 0; index < sortedArray.length; index++) {
  75041. renderSubMesh(sortedArray[index]);
  75042. }
  75043. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75044. }
  75045. };
  75046. };
  75047. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  75048. var transform = scene.getTransformMatrix();
  75049. var meshPosition;
  75050. if (this.useCustomMeshPosition) {
  75051. meshPosition = this.customMeshPosition;
  75052. }
  75053. else if (this.attachedNode) {
  75054. meshPosition = this.attachedNode.position;
  75055. }
  75056. else {
  75057. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  75058. }
  75059. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  75060. this._screenCoordinates.x = pos.x / this._viewPort.width;
  75061. this._screenCoordinates.y = pos.y / this._viewPort.height;
  75062. if (this.invert)
  75063. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  75064. };
  75065. // Static methods
  75066. /**
  75067. * Creates a default mesh for the Volumeric Light Scattering post-process
  75068. * @param {string} The mesh name
  75069. * @param {BABYLON.Scene} The scene where to create the mesh
  75070. * @return {BABYLON.Mesh} the default mesh
  75071. */
  75072. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  75073. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  75074. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  75075. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  75076. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  75077. mesh.material = material;
  75078. return mesh;
  75079. };
  75080. __decorate([
  75081. BABYLON.serializeAsVector3()
  75082. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  75083. __decorate([
  75084. BABYLON.serialize()
  75085. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  75086. __decorate([
  75087. BABYLON.serialize()
  75088. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  75089. __decorate([
  75090. BABYLON.serializeAsMeshReference()
  75091. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  75092. __decorate([
  75093. BABYLON.serialize()
  75094. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  75095. __decorate([
  75096. BABYLON.serialize()
  75097. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  75098. __decorate([
  75099. BABYLON.serialize()
  75100. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  75101. __decorate([
  75102. BABYLON.serialize()
  75103. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  75104. __decorate([
  75105. BABYLON.serialize()
  75106. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  75107. return VolumetricLightScatteringPostProcess;
  75108. }(BABYLON.PostProcess));
  75109. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  75110. })(BABYLON || (BABYLON = {}));
  75111. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  75112. "use strict";
  75113. //
  75114. // This post-process allows the modification of rendered colors by using
  75115. // a 'look-up table' (LUT). This effect is also called Color Grading.
  75116. //
  75117. // The object needs to be provided an url to a texture containing the color
  75118. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  75119. // Use an image editing software to tweak the LUT to match your needs.
  75120. //
  75121. // For an example of a color LUT, see here:
  75122. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  75123. // For explanations on color grading, see here:
  75124. // http://udn.epicgames.com/Three/ColorGrading.html
  75125. //
  75126. var BABYLON;
  75127. (function (BABYLON) {
  75128. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  75129. __extends(ColorCorrectionPostProcess, _super);
  75130. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  75131. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  75132. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75133. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  75134. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75135. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75136. _this.onApply = function (effect) {
  75137. effect.setTexture("colorTable", _this._colorTableTexture);
  75138. };
  75139. return _this;
  75140. }
  75141. return ColorCorrectionPostProcess;
  75142. }(BABYLON.PostProcess));
  75143. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  75144. })(BABYLON || (BABYLON = {}));
  75145. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  75146. "use strict";
  75147. var BABYLON;
  75148. (function (BABYLON) {
  75149. var TonemappingOperator;
  75150. (function (TonemappingOperator) {
  75151. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  75152. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  75153. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  75154. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  75155. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  75156. ;
  75157. var TonemapPostProcess = /** @class */ (function (_super) {
  75158. __extends(TonemapPostProcess, _super);
  75159. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  75160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75161. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75162. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  75163. _this._operator = _operator;
  75164. _this.exposureAdjustment = exposureAdjustment;
  75165. var defines = "#define ";
  75166. if (_this._operator === TonemappingOperator.Hable)
  75167. defines += "HABLE_TONEMAPPING";
  75168. else if (_this._operator === TonemappingOperator.Reinhard)
  75169. defines += "REINHARD_TONEMAPPING";
  75170. else if (_this._operator === TonemappingOperator.HejiDawson)
  75171. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  75172. else if (_this._operator === TonemappingOperator.Photographic)
  75173. defines += "PHOTOGRAPHIC_TONEMAPPING";
  75174. //sadly a second call to create the effect.
  75175. _this.updateEffect(defines);
  75176. _this.onApply = function (effect) {
  75177. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  75178. };
  75179. return _this;
  75180. }
  75181. return TonemapPostProcess;
  75182. }(BABYLON.PostProcess));
  75183. BABYLON.TonemapPostProcess = TonemapPostProcess;
  75184. })(BABYLON || (BABYLON = {}));
  75185. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  75186. "use strict";
  75187. var BABYLON;
  75188. (function (BABYLON) {
  75189. var DisplayPassPostProcess = /** @class */ (function (_super) {
  75190. __extends(DisplayPassPostProcess, _super);
  75191. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  75192. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  75193. }
  75194. return DisplayPassPostProcess;
  75195. }(BABYLON.PostProcess));
  75196. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  75197. })(BABYLON || (BABYLON = {}));
  75198. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  75199. "use strict";
  75200. var BABYLON;
  75201. (function (BABYLON) {
  75202. var HighlightsPostProcess = /** @class */ (function (_super) {
  75203. __extends(HighlightsPostProcess, _super);
  75204. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75205. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75206. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75207. }
  75208. return HighlightsPostProcess;
  75209. }(BABYLON.PostProcess));
  75210. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  75211. })(BABYLON || (BABYLON = {}));
  75212. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  75213. "use strict";
  75214. var BABYLON;
  75215. (function (BABYLON) {
  75216. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  75217. __extends(ImageProcessingPostProcess, _super);
  75218. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  75219. if (camera === void 0) { camera = null; }
  75220. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75221. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  75222. _this._fromLinearSpace = true;
  75223. /**
  75224. * Defines cache preventing GC.
  75225. */
  75226. _this._defines = {
  75227. IMAGEPROCESSING: false,
  75228. VIGNETTE: false,
  75229. VIGNETTEBLENDMODEMULTIPLY: false,
  75230. VIGNETTEBLENDMODEOPAQUE: false,
  75231. TONEMAPPING: false,
  75232. CONTRAST: false,
  75233. COLORCURVES: false,
  75234. COLORGRADING: false,
  75235. COLORGRADING3D: false,
  75236. FROMLINEARSPACE: false,
  75237. SAMPLER3DGREENDEPTH: false,
  75238. SAMPLER3DBGRMAP: false,
  75239. IMAGEPROCESSINGPOSTPROCESS: false,
  75240. EXPOSURE: false,
  75241. };
  75242. // Setup the configuration as forced by the constructor. This would then not force the
  75243. // scene materials output in linear space and let untouched the default forward pass.
  75244. if (imageProcessingConfiguration) {
  75245. imageProcessingConfiguration.applyByPostProcess = true;
  75246. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  75247. // This will cause the shader to be compiled
  75248. _this.fromLinearSpace = false;
  75249. }
  75250. else {
  75251. _this._attachImageProcessingConfiguration(null, true);
  75252. _this.imageProcessingConfiguration.applyByPostProcess = true;
  75253. }
  75254. _this.onApply = function (effect) {
  75255. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  75256. };
  75257. return _this;
  75258. }
  75259. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  75260. /**
  75261. * Gets the image processing configuration used either in this material.
  75262. */
  75263. get: function () {
  75264. return this._imageProcessingConfiguration;
  75265. },
  75266. /**
  75267. * Sets the Default image processing configuration used either in the this material.
  75268. *
  75269. * If sets to null, the scene one is in use.
  75270. */
  75271. set: function (value) {
  75272. this._attachImageProcessingConfiguration(value);
  75273. },
  75274. enumerable: true,
  75275. configurable: true
  75276. });
  75277. /**
  75278. * Attaches a new image processing configuration to the PBR Material.
  75279. * @param configuration
  75280. */
  75281. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  75282. var _this = this;
  75283. if (doNotBuild === void 0) { doNotBuild = false; }
  75284. if (configuration === this._imageProcessingConfiguration) {
  75285. return;
  75286. }
  75287. // Detaches observer.
  75288. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75289. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75290. }
  75291. // Pick the scene configuration if needed.
  75292. if (!configuration) {
  75293. var scene = null;
  75294. var engine = this.getEngine();
  75295. var camera = this.getCamera();
  75296. if (camera) {
  75297. scene = camera.getScene();
  75298. }
  75299. else if (engine && engine.scenes) {
  75300. var scenes = engine.scenes;
  75301. scene = scenes[scenes.length - 1];
  75302. }
  75303. else {
  75304. scene = BABYLON.Engine.LastCreatedScene;
  75305. }
  75306. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  75307. }
  75308. else {
  75309. this._imageProcessingConfiguration = configuration;
  75310. }
  75311. // Attaches observer.
  75312. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  75313. _this._updateParameters();
  75314. });
  75315. // Ensure the effect will be rebuilt.
  75316. if (!doNotBuild) {
  75317. this._updateParameters();
  75318. }
  75319. };
  75320. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  75321. /**
  75322. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75323. */
  75324. get: function () {
  75325. return this.imageProcessingConfiguration.colorCurves;
  75326. },
  75327. /**
  75328. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  75329. */
  75330. set: function (value) {
  75331. this.imageProcessingConfiguration.colorCurves = value;
  75332. },
  75333. enumerable: true,
  75334. configurable: true
  75335. });
  75336. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  75337. /**
  75338. * Gets wether the color curves effect is enabled.
  75339. */
  75340. get: function () {
  75341. return this.imageProcessingConfiguration.colorCurvesEnabled;
  75342. },
  75343. /**
  75344. * Sets wether the color curves effect is enabled.
  75345. */
  75346. set: function (value) {
  75347. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  75348. },
  75349. enumerable: true,
  75350. configurable: true
  75351. });
  75352. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  75353. /**
  75354. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75355. */
  75356. get: function () {
  75357. return this.imageProcessingConfiguration.colorGradingTexture;
  75358. },
  75359. /**
  75360. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  75361. */
  75362. set: function (value) {
  75363. this.imageProcessingConfiguration.colorGradingTexture = value;
  75364. },
  75365. enumerable: true,
  75366. configurable: true
  75367. });
  75368. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  75369. /**
  75370. * Gets wether the color grading effect is enabled.
  75371. */
  75372. get: function () {
  75373. return this.imageProcessingConfiguration.colorGradingEnabled;
  75374. },
  75375. /**
  75376. * Gets wether the color grading effect is enabled.
  75377. */
  75378. set: function (value) {
  75379. this.imageProcessingConfiguration.colorGradingEnabled = value;
  75380. },
  75381. enumerable: true,
  75382. configurable: true
  75383. });
  75384. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  75385. /**
  75386. * Gets exposure used in the effect.
  75387. */
  75388. get: function () {
  75389. return this.imageProcessingConfiguration.exposure;
  75390. },
  75391. /**
  75392. * Sets exposure used in the effect.
  75393. */
  75394. set: function (value) {
  75395. this.imageProcessingConfiguration.exposure = value;
  75396. },
  75397. enumerable: true,
  75398. configurable: true
  75399. });
  75400. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  75401. /**
  75402. * Gets wether tonemapping is enabled or not.
  75403. */
  75404. get: function () {
  75405. return this._imageProcessingConfiguration.toneMappingEnabled;
  75406. },
  75407. /**
  75408. * Sets wether tonemapping is enabled or not
  75409. */
  75410. set: function (value) {
  75411. this._imageProcessingConfiguration.toneMappingEnabled = value;
  75412. },
  75413. enumerable: true,
  75414. configurable: true
  75415. });
  75416. ;
  75417. ;
  75418. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  75419. /**
  75420. * Gets contrast used in the effect.
  75421. */
  75422. get: function () {
  75423. return this.imageProcessingConfiguration.contrast;
  75424. },
  75425. /**
  75426. * Sets contrast used in the effect.
  75427. */
  75428. set: function (value) {
  75429. this.imageProcessingConfiguration.contrast = value;
  75430. },
  75431. enumerable: true,
  75432. configurable: true
  75433. });
  75434. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  75435. /**
  75436. * Gets Vignette stretch size.
  75437. */
  75438. get: function () {
  75439. return this.imageProcessingConfiguration.vignetteStretch;
  75440. },
  75441. /**
  75442. * Sets Vignette stretch size.
  75443. */
  75444. set: function (value) {
  75445. this.imageProcessingConfiguration.vignetteStretch = value;
  75446. },
  75447. enumerable: true,
  75448. configurable: true
  75449. });
  75450. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  75451. /**
  75452. * Gets Vignette centre X Offset.
  75453. */
  75454. get: function () {
  75455. return this.imageProcessingConfiguration.vignetteCentreX;
  75456. },
  75457. /**
  75458. * Sets Vignette centre X Offset.
  75459. */
  75460. set: function (value) {
  75461. this.imageProcessingConfiguration.vignetteCentreX = value;
  75462. },
  75463. enumerable: true,
  75464. configurable: true
  75465. });
  75466. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  75467. /**
  75468. * Gets Vignette centre Y Offset.
  75469. */
  75470. get: function () {
  75471. return this.imageProcessingConfiguration.vignetteCentreY;
  75472. },
  75473. /**
  75474. * Sets Vignette centre Y Offset.
  75475. */
  75476. set: function (value) {
  75477. this.imageProcessingConfiguration.vignetteCentreY = value;
  75478. },
  75479. enumerable: true,
  75480. configurable: true
  75481. });
  75482. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  75483. /**
  75484. * Gets Vignette weight or intensity of the vignette effect.
  75485. */
  75486. get: function () {
  75487. return this.imageProcessingConfiguration.vignetteWeight;
  75488. },
  75489. /**
  75490. * Sets Vignette weight or intensity of the vignette effect.
  75491. */
  75492. set: function (value) {
  75493. this.imageProcessingConfiguration.vignetteWeight = value;
  75494. },
  75495. enumerable: true,
  75496. configurable: true
  75497. });
  75498. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  75499. /**
  75500. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75501. * if vignetteEnabled is set to true.
  75502. */
  75503. get: function () {
  75504. return this.imageProcessingConfiguration.vignetteColor;
  75505. },
  75506. /**
  75507. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  75508. * if vignetteEnabled is set to true.
  75509. */
  75510. set: function (value) {
  75511. this.imageProcessingConfiguration.vignetteColor = value;
  75512. },
  75513. enumerable: true,
  75514. configurable: true
  75515. });
  75516. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  75517. /**
  75518. * Gets Camera field of view used by the Vignette effect.
  75519. */
  75520. get: function () {
  75521. return this.imageProcessingConfiguration.vignetteCameraFov;
  75522. },
  75523. /**
  75524. * Sets Camera field of view used by the Vignette effect.
  75525. */
  75526. set: function (value) {
  75527. this.imageProcessingConfiguration.vignetteCameraFov = value;
  75528. },
  75529. enumerable: true,
  75530. configurable: true
  75531. });
  75532. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  75533. /**
  75534. * Gets the vignette blend mode allowing different kind of effect.
  75535. */
  75536. get: function () {
  75537. return this.imageProcessingConfiguration.vignetteBlendMode;
  75538. },
  75539. /**
  75540. * Sets the vignette blend mode allowing different kind of effect.
  75541. */
  75542. set: function (value) {
  75543. this.imageProcessingConfiguration.vignetteBlendMode = value;
  75544. },
  75545. enumerable: true,
  75546. configurable: true
  75547. });
  75548. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  75549. /**
  75550. * Gets wether the vignette effect is enabled.
  75551. */
  75552. get: function () {
  75553. return this.imageProcessingConfiguration.vignetteEnabled;
  75554. },
  75555. /**
  75556. * Sets wether the vignette effect is enabled.
  75557. */
  75558. set: function (value) {
  75559. this.imageProcessingConfiguration.vignetteEnabled = value;
  75560. },
  75561. enumerable: true,
  75562. configurable: true
  75563. });
  75564. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  75565. /**
  75566. * Gets wether the input of the processing is in Gamma or Linear Space.
  75567. */
  75568. get: function () {
  75569. return this._fromLinearSpace;
  75570. },
  75571. /**
  75572. * Sets wether the input of the processing is in Gamma or Linear Space.
  75573. */
  75574. set: function (value) {
  75575. if (this._fromLinearSpace === value) {
  75576. return;
  75577. }
  75578. this._fromLinearSpace = value;
  75579. this._updateParameters();
  75580. },
  75581. enumerable: true,
  75582. configurable: true
  75583. });
  75584. ImageProcessingPostProcess.prototype.getClassName = function () {
  75585. return "ImageProcessingPostProcess";
  75586. };
  75587. ImageProcessingPostProcess.prototype._updateParameters = function () {
  75588. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  75589. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  75590. var defines = "";
  75591. for (var define in this._defines) {
  75592. if (this._defines[define]) {
  75593. defines += "#define " + define + ";\r\n";
  75594. }
  75595. }
  75596. var samplers = ["textureSampler"];
  75597. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  75598. var uniforms = ["scale"];
  75599. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  75600. this.updateEffect(defines, uniforms, samplers);
  75601. };
  75602. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  75603. _super.prototype.dispose.call(this, camera);
  75604. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  75605. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  75606. }
  75607. this.imageProcessingConfiguration.applyByPostProcess = false;
  75608. };
  75609. __decorate([
  75610. BABYLON.serialize()
  75611. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  75612. return ImageProcessingPostProcess;
  75613. }(BABYLON.PostProcess));
  75614. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  75615. })(BABYLON || (BABYLON = {}));
  75616. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  75617. "use strict";
  75618. var BABYLON;
  75619. (function (BABYLON) {
  75620. var Bone = /** @class */ (function (_super) {
  75621. __extends(Bone, _super);
  75622. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  75623. if (parentBone === void 0) { parentBone = null; }
  75624. if (localMatrix === void 0) { localMatrix = null; }
  75625. if (restPose === void 0) { restPose = null; }
  75626. if (baseMatrix === void 0) { baseMatrix = null; }
  75627. if (index === void 0) { index = null; }
  75628. var _this = _super.call(this, name, skeleton.getScene()) || this;
  75629. _this.name = name;
  75630. _this.children = new Array();
  75631. _this.animations = new Array();
  75632. // Set this value to map this bone to a different index in the transform matrices.
  75633. // Set this value to -1 to exclude the bone from the transform matrices.
  75634. _this._index = null;
  75635. _this._worldTransform = new BABYLON.Matrix();
  75636. _this._absoluteTransform = new BABYLON.Matrix();
  75637. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  75638. _this._scaleMatrix = BABYLON.Matrix.Identity();
  75639. _this._scaleVector = BABYLON.Vector3.One();
  75640. _this._negateScaleChildren = BABYLON.Vector3.One();
  75641. _this._scalingDeterminant = 1;
  75642. _this._skeleton = skeleton;
  75643. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  75644. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  75645. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  75646. _this._index = index;
  75647. skeleton.bones.push(_this);
  75648. _this.setParent(parentBone, false);
  75649. _this._updateDifferenceMatrix();
  75650. return _this;
  75651. }
  75652. Object.defineProperty(Bone.prototype, "_matrix", {
  75653. get: function () {
  75654. return this._localMatrix;
  75655. },
  75656. set: function (val) {
  75657. if (this._localMatrix) {
  75658. this._localMatrix.copyFrom(val);
  75659. }
  75660. else {
  75661. this._localMatrix = val;
  75662. }
  75663. },
  75664. enumerable: true,
  75665. configurable: true
  75666. });
  75667. // Members
  75668. Bone.prototype.getSkeleton = function () {
  75669. return this._skeleton;
  75670. };
  75671. Bone.prototype.getParent = function () {
  75672. return this._parent;
  75673. };
  75674. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  75675. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75676. if (this._parent === parent) {
  75677. return;
  75678. }
  75679. if (this._parent) {
  75680. var index = this._parent.children.indexOf(this);
  75681. if (index !== -1) {
  75682. this._parent.children.splice(index, 1);
  75683. }
  75684. }
  75685. this._parent = parent;
  75686. if (this._parent) {
  75687. this._parent.children.push(this);
  75688. }
  75689. if (updateDifferenceMatrix) {
  75690. this._updateDifferenceMatrix();
  75691. }
  75692. };
  75693. Bone.prototype.getLocalMatrix = function () {
  75694. return this._localMatrix;
  75695. };
  75696. Bone.prototype.getBaseMatrix = function () {
  75697. return this._baseMatrix;
  75698. };
  75699. Bone.prototype.getRestPose = function () {
  75700. return this._restPose;
  75701. };
  75702. Bone.prototype.returnToRest = function () {
  75703. this.updateMatrix(this._restPose.clone());
  75704. };
  75705. Bone.prototype.getWorldMatrix = function () {
  75706. return this._worldTransform;
  75707. };
  75708. Bone.prototype.getInvertedAbsoluteTransform = function () {
  75709. return this._invertedAbsoluteTransform;
  75710. };
  75711. Bone.prototype.getAbsoluteTransform = function () {
  75712. return this._absoluteTransform;
  75713. };
  75714. Object.defineProperty(Bone.prototype, "position", {
  75715. // Properties (matches AbstractMesh properties)
  75716. get: function () {
  75717. return this.getPosition();
  75718. },
  75719. set: function (newPosition) {
  75720. this.setPosition(newPosition);
  75721. },
  75722. enumerable: true,
  75723. configurable: true
  75724. });
  75725. Object.defineProperty(Bone.prototype, "rotation", {
  75726. get: function () {
  75727. return this.getRotation();
  75728. },
  75729. set: function (newRotation) {
  75730. this.setRotation(newRotation);
  75731. },
  75732. enumerable: true,
  75733. configurable: true
  75734. });
  75735. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  75736. get: function () {
  75737. return this.getRotationQuaternion();
  75738. },
  75739. set: function (newRotation) {
  75740. this.setRotationQuaternion(newRotation);
  75741. },
  75742. enumerable: true,
  75743. configurable: true
  75744. });
  75745. Object.defineProperty(Bone.prototype, "scaling", {
  75746. get: function () {
  75747. return this.getScale();
  75748. },
  75749. set: function (newScaling) {
  75750. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  75751. },
  75752. enumerable: true,
  75753. configurable: true
  75754. });
  75755. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  75756. /**
  75757. * Gets the animation properties override
  75758. */
  75759. get: function () {
  75760. return this._skeleton.animationPropertiesOverride;
  75761. },
  75762. enumerable: true,
  75763. configurable: true
  75764. });
  75765. // Methods
  75766. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  75767. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  75768. this._baseMatrix = matrix.clone();
  75769. this._localMatrix = matrix.clone();
  75770. this._skeleton._markAsDirty();
  75771. if (updateDifferenceMatrix) {
  75772. this._updateDifferenceMatrix();
  75773. }
  75774. };
  75775. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  75776. if (!rootMatrix) {
  75777. rootMatrix = this._baseMatrix;
  75778. }
  75779. if (this._parent) {
  75780. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  75781. }
  75782. else {
  75783. this._absoluteTransform.copyFrom(rootMatrix);
  75784. }
  75785. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  75786. for (var index = 0; index < this.children.length; index++) {
  75787. this.children[index]._updateDifferenceMatrix();
  75788. }
  75789. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  75790. };
  75791. Bone.prototype.markAsDirty = function () {
  75792. this._currentRenderId++;
  75793. this._childRenderId++;
  75794. this._skeleton._markAsDirty();
  75795. };
  75796. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  75797. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  75798. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  75799. // all animation may be coming from a library skeleton, so may need to create animation
  75800. if (this.animations.length === 0) {
  75801. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  75802. this.animations[0].setKeys([]);
  75803. }
  75804. // get animation info / verify there is such a range from the source bone
  75805. var sourceRange = source.animations[0].getRange(rangeName);
  75806. if (!sourceRange) {
  75807. return false;
  75808. }
  75809. var from = sourceRange.from;
  75810. var to = sourceRange.to;
  75811. var sourceKeys = source.animations[0].getKeys();
  75812. // rescaling prep
  75813. var sourceBoneLength = source.length;
  75814. var sourceParent = source.getParent();
  75815. var parent = this.getParent();
  75816. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  75817. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  75818. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  75819. var destKeys = this.animations[0].getKeys();
  75820. // loop vars declaration
  75821. var orig;
  75822. var origTranslation;
  75823. var mat;
  75824. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  75825. orig = sourceKeys[key];
  75826. if (orig.frame >= from && orig.frame <= to) {
  75827. if (rescaleAsRequired) {
  75828. mat = orig.value.clone();
  75829. // scale based on parent ratio, when bone has parent
  75830. if (parentScalingReqd) {
  75831. origTranslation = mat.getTranslation();
  75832. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  75833. // scale based on skeleton dimension ratio when root bone, and value is passed
  75834. }
  75835. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  75836. origTranslation = mat.getTranslation();
  75837. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  75838. // use original when root bone, and no data for skelDimensionsRatio
  75839. }
  75840. else {
  75841. mat = orig.value;
  75842. }
  75843. }
  75844. else {
  75845. mat = orig.value;
  75846. }
  75847. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  75848. }
  75849. }
  75850. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  75851. return true;
  75852. };
  75853. /**
  75854. * Translate the bone in local or world space.
  75855. * @param vec The amount to translate the bone.
  75856. * @param space The space that the translation is in.
  75857. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75858. */
  75859. Bone.prototype.translate = function (vec, space, mesh) {
  75860. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75861. var lm = this.getLocalMatrix();
  75862. if (space == BABYLON.Space.LOCAL) {
  75863. lm.m[12] += vec.x;
  75864. lm.m[13] += vec.y;
  75865. lm.m[14] += vec.z;
  75866. }
  75867. else {
  75868. var wm = null;
  75869. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75870. if (mesh) {
  75871. wm = mesh.getWorldMatrix();
  75872. }
  75873. this._skeleton.computeAbsoluteTransforms();
  75874. var tmat = Bone._tmpMats[0];
  75875. var tvec = Bone._tmpVecs[0];
  75876. if (this._parent) {
  75877. if (mesh && wm) {
  75878. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75879. tmat.multiplyToRef(wm, tmat);
  75880. }
  75881. else {
  75882. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75883. }
  75884. }
  75885. tmat.m[12] = 0;
  75886. tmat.m[13] = 0;
  75887. tmat.m[14] = 0;
  75888. tmat.invert();
  75889. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  75890. lm.m[12] += tvec.x;
  75891. lm.m[13] += tvec.y;
  75892. lm.m[14] += tvec.z;
  75893. }
  75894. this.markAsDirty();
  75895. };
  75896. /**
  75897. * Set the postion of the bone in local or world space.
  75898. * @param position The position to set the bone.
  75899. * @param space The space that the position is in.
  75900. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  75901. */
  75902. Bone.prototype.setPosition = function (position, space, mesh) {
  75903. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  75904. var lm = this.getLocalMatrix();
  75905. if (space == BABYLON.Space.LOCAL) {
  75906. lm.m[12] = position.x;
  75907. lm.m[13] = position.y;
  75908. lm.m[14] = position.z;
  75909. }
  75910. else {
  75911. var wm = null;
  75912. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  75913. if (mesh) {
  75914. wm = mesh.getWorldMatrix();
  75915. }
  75916. this._skeleton.computeAbsoluteTransforms();
  75917. var tmat = Bone._tmpMats[0];
  75918. var vec = Bone._tmpVecs[0];
  75919. if (this._parent) {
  75920. if (mesh && wm) {
  75921. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75922. tmat.multiplyToRef(wm, tmat);
  75923. }
  75924. else {
  75925. tmat.copyFrom(this._parent.getAbsoluteTransform());
  75926. }
  75927. }
  75928. tmat.invert();
  75929. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  75930. lm.m[12] = vec.x;
  75931. lm.m[13] = vec.y;
  75932. lm.m[14] = vec.z;
  75933. }
  75934. this.markAsDirty();
  75935. };
  75936. /**
  75937. * Set the absolute postion of the bone (world space).
  75938. * @param position The position to set the bone.
  75939. * @param mesh The mesh that this bone is attached to.
  75940. */
  75941. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  75942. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  75943. };
  75944. /**
  75945. * Set the scale of the bone on the x, y and z axes.
  75946. * @param x The scale of the bone on the x axis.
  75947. * @param x The scale of the bone on the y axis.
  75948. * @param z The scale of the bone on the z axis.
  75949. * @param scaleChildren Set this to true if children of the bone should be scaled.
  75950. */
  75951. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  75952. if (scaleChildren === void 0) { scaleChildren = false; }
  75953. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  75954. if (!scaleChildren) {
  75955. this._negateScaleChildren.x = 1 / x;
  75956. this._negateScaleChildren.y = 1 / y;
  75957. this._negateScaleChildren.z = 1 / z;
  75958. }
  75959. this._syncScaleVector();
  75960. }
  75961. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  75962. };
  75963. /**
  75964. * Scale the bone on the x, y and z axes.
  75965. * @param x The amount to scale the bone on the x axis.
  75966. * @param x The amount to scale the bone on the y axis.
  75967. * @param z The amount to scale the bone on the z axis.
  75968. * @param scaleChildren Set this to true if children of the bone should be scaled.
  75969. */
  75970. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  75971. if (scaleChildren === void 0) { scaleChildren = false; }
  75972. var locMat = this.getLocalMatrix();
  75973. var origLocMat = Bone._tmpMats[0];
  75974. origLocMat.copyFrom(locMat);
  75975. var origLocMatInv = Bone._tmpMats[1];
  75976. origLocMatInv.copyFrom(origLocMat);
  75977. origLocMatInv.invert();
  75978. var scaleMat = Bone._tmpMats[2];
  75979. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  75980. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  75981. this._scaleVector.x *= x;
  75982. this._scaleVector.y *= y;
  75983. this._scaleVector.z *= z;
  75984. locMat.multiplyToRef(origLocMatInv, locMat);
  75985. locMat.multiplyToRef(scaleMat, locMat);
  75986. locMat.multiplyToRef(origLocMat, locMat);
  75987. var parent = this.getParent();
  75988. if (parent) {
  75989. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  75990. }
  75991. else {
  75992. this.getAbsoluteTransform().copyFrom(locMat);
  75993. }
  75994. var len = this.children.length;
  75995. scaleMat.invert();
  75996. for (var i = 0; i < len; i++) {
  75997. var child = this.children[i];
  75998. var cm = child.getLocalMatrix();
  75999. cm.multiplyToRef(scaleMat, cm);
  76000. var lm = child.getLocalMatrix();
  76001. lm.m[12] *= x;
  76002. lm.m[13] *= y;
  76003. lm.m[14] *= z;
  76004. }
  76005. this.computeAbsoluteTransforms();
  76006. if (scaleChildren) {
  76007. for (var i = 0; i < len; i++) {
  76008. this.children[i].scale(x, y, z, scaleChildren);
  76009. }
  76010. }
  76011. this.markAsDirty();
  76012. };
  76013. /**
  76014. * Set the yaw, pitch, and roll of the bone in local or world space.
  76015. * @param yaw The rotation of the bone on the y axis.
  76016. * @param pitch The rotation of the bone on the x axis.
  76017. * @param roll The rotation of the bone on the z axis.
  76018. * @param space The space that the axes of rotation are in.
  76019. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76020. */
  76021. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  76022. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76023. var rotMat = Bone._tmpMats[0];
  76024. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  76025. var rotMatInv = Bone._tmpMats[1];
  76026. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76027. rotMatInv.multiplyToRef(rotMat, rotMat);
  76028. this._rotateWithMatrix(rotMat, space, mesh);
  76029. };
  76030. /**
  76031. * Rotate the bone on an axis in local or world space.
  76032. * @param axis The axis to rotate the bone on.
  76033. * @param amount The amount to rotate the bone.
  76034. * @param space The space that the axis is in.
  76035. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76036. */
  76037. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  76038. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76039. var rmat = Bone._tmpMats[0];
  76040. rmat.m[12] = 0;
  76041. rmat.m[13] = 0;
  76042. rmat.m[14] = 0;
  76043. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  76044. this._rotateWithMatrix(rmat, space, mesh);
  76045. };
  76046. /**
  76047. * Set the rotation of the bone to a particular axis angle in local or world space.
  76048. * @param axis The axis to rotate the bone on.
  76049. * @param angle The angle that the bone should be rotated to.
  76050. * @param space The space that the axis is in.
  76051. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76052. */
  76053. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  76054. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76055. var rotMat = Bone._tmpMats[0];
  76056. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  76057. var rotMatInv = Bone._tmpMats[1];
  76058. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76059. rotMatInv.multiplyToRef(rotMat, rotMat);
  76060. this._rotateWithMatrix(rotMat, space, mesh);
  76061. };
  76062. /**
  76063. * Set the euler rotation of the bone in local of world space.
  76064. * @param rotation The euler rotation that the bone should be set to.
  76065. * @param space The space that the rotation is in.
  76066. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76067. */
  76068. Bone.prototype.setRotation = function (rotation, space, mesh) {
  76069. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76070. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  76071. };
  76072. /**
  76073. * Set the quaternion rotation of the bone in local of world space.
  76074. * @param quat The quaternion rotation that the bone should be set to.
  76075. * @param space The space that the rotation is in.
  76076. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76077. */
  76078. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  76079. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76080. var rotMatInv = Bone._tmpMats[0];
  76081. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76082. var rotMat = Bone._tmpMats[1];
  76083. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  76084. rotMatInv.multiplyToRef(rotMat, rotMat);
  76085. this._rotateWithMatrix(rotMat, space, mesh);
  76086. };
  76087. /**
  76088. * Set the rotation matrix of the bone in local of world space.
  76089. * @param rotMat The rotation matrix that the bone should be set to.
  76090. * @param space The space that the rotation is in.
  76091. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76092. */
  76093. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  76094. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76095. var rotMatInv = Bone._tmpMats[0];
  76096. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  76097. var rotMat2 = Bone._tmpMats[1];
  76098. rotMat2.copyFrom(rotMat);
  76099. rotMatInv.multiplyToRef(rotMat, rotMat2);
  76100. this._rotateWithMatrix(rotMat2, space, mesh);
  76101. };
  76102. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  76103. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76104. var lmat = this.getLocalMatrix();
  76105. var lx = lmat.m[12];
  76106. var ly = lmat.m[13];
  76107. var lz = lmat.m[14];
  76108. var parent = this.getParent();
  76109. var parentScale = Bone._tmpMats[3];
  76110. var parentScaleInv = Bone._tmpMats[4];
  76111. if (parent) {
  76112. if (space == BABYLON.Space.WORLD) {
  76113. if (mesh) {
  76114. parentScale.copyFrom(mesh.getWorldMatrix());
  76115. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  76116. }
  76117. else {
  76118. parentScale.copyFrom(parent.getAbsoluteTransform());
  76119. }
  76120. }
  76121. else {
  76122. parentScale = parent._scaleMatrix;
  76123. }
  76124. parentScaleInv.copyFrom(parentScale);
  76125. parentScaleInv.invert();
  76126. lmat.multiplyToRef(parentScale, lmat);
  76127. lmat.multiplyToRef(rmat, lmat);
  76128. lmat.multiplyToRef(parentScaleInv, lmat);
  76129. }
  76130. else {
  76131. if (space == BABYLON.Space.WORLD && mesh) {
  76132. parentScale.copyFrom(mesh.getWorldMatrix());
  76133. parentScaleInv.copyFrom(parentScale);
  76134. parentScaleInv.invert();
  76135. lmat.multiplyToRef(parentScale, lmat);
  76136. lmat.multiplyToRef(rmat, lmat);
  76137. lmat.multiplyToRef(parentScaleInv, lmat);
  76138. }
  76139. else {
  76140. lmat.multiplyToRef(rmat, lmat);
  76141. }
  76142. }
  76143. lmat.m[12] = lx;
  76144. lmat.m[13] = ly;
  76145. lmat.m[14] = lz;
  76146. this.computeAbsoluteTransforms();
  76147. this.markAsDirty();
  76148. };
  76149. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  76150. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76151. if (space == BABYLON.Space.WORLD) {
  76152. var scaleMatrix = Bone._tmpMats[2];
  76153. scaleMatrix.copyFrom(this._scaleMatrix);
  76154. rotMatInv.copyFrom(this.getAbsoluteTransform());
  76155. if (mesh) {
  76156. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  76157. var meshScale = Bone._tmpMats[3];
  76158. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  76159. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  76160. }
  76161. rotMatInv.invert();
  76162. scaleMatrix.m[0] *= this._scalingDeterminant;
  76163. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76164. }
  76165. else {
  76166. rotMatInv.copyFrom(this.getLocalMatrix());
  76167. rotMatInv.invert();
  76168. var scaleMatrix = Bone._tmpMats[2];
  76169. scaleMatrix.copyFrom(this._scaleMatrix);
  76170. if (this._parent) {
  76171. var pscaleMatrix = Bone._tmpMats[3];
  76172. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  76173. pscaleMatrix.invert();
  76174. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  76175. }
  76176. else {
  76177. scaleMatrix.m[0] *= this._scalingDeterminant;
  76178. }
  76179. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  76180. }
  76181. };
  76182. /**
  76183. * Get the scale of the bone
  76184. * @returns the scale of the bone
  76185. */
  76186. Bone.prototype.getScale = function () {
  76187. return this._scaleVector.clone();
  76188. };
  76189. /**
  76190. * Copy the scale of the bone to a vector3.
  76191. * @param result The vector3 to copy the scale to
  76192. */
  76193. Bone.prototype.getScaleToRef = function (result) {
  76194. result.copyFrom(this._scaleVector);
  76195. };
  76196. /**
  76197. * Get the position of the bone in local or world space.
  76198. * @param space The space that the returned position is in.
  76199. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76200. * @returns The position of the bone
  76201. */
  76202. Bone.prototype.getPosition = function (space, mesh) {
  76203. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76204. if (mesh === void 0) { mesh = null; }
  76205. var pos = BABYLON.Vector3.Zero();
  76206. this.getPositionToRef(space, mesh, pos);
  76207. return pos;
  76208. };
  76209. /**
  76210. * Copy the position of the bone to a vector3 in local or world space.
  76211. * @param space The space that the returned position is in.
  76212. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76213. * @param result The vector3 to copy the position to.
  76214. */
  76215. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  76216. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76217. if (space == BABYLON.Space.LOCAL) {
  76218. var lm = this.getLocalMatrix();
  76219. result.x = lm.m[12];
  76220. result.y = lm.m[13];
  76221. result.z = lm.m[14];
  76222. }
  76223. else {
  76224. var wm = null;
  76225. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76226. if (mesh) {
  76227. wm = mesh.getWorldMatrix();
  76228. }
  76229. this._skeleton.computeAbsoluteTransforms();
  76230. var tmat = Bone._tmpMats[0];
  76231. if (mesh && wm) {
  76232. tmat.copyFrom(this.getAbsoluteTransform());
  76233. tmat.multiplyToRef(wm, tmat);
  76234. }
  76235. else {
  76236. tmat = this.getAbsoluteTransform();
  76237. }
  76238. result.x = tmat.m[12];
  76239. result.y = tmat.m[13];
  76240. result.z = tmat.m[14];
  76241. }
  76242. };
  76243. /**
  76244. * Get the absolute position of the bone (world space).
  76245. * @param mesh The mesh that this bone is attached to.
  76246. * @returns The absolute position of the bone
  76247. */
  76248. Bone.prototype.getAbsolutePosition = function (mesh) {
  76249. if (mesh === void 0) { mesh = null; }
  76250. var pos = BABYLON.Vector3.Zero();
  76251. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  76252. return pos;
  76253. };
  76254. /**
  76255. * Copy the absolute position of the bone (world space) to the result param.
  76256. * @param mesh The mesh that this bone is attached to.
  76257. * @param result The vector3 to copy the absolute position to.
  76258. */
  76259. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  76260. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  76261. };
  76262. /**
  76263. * Compute the absolute transforms of this bone and its children.
  76264. */
  76265. Bone.prototype.computeAbsoluteTransforms = function () {
  76266. if (this._parent) {
  76267. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76268. }
  76269. else {
  76270. this._absoluteTransform.copyFrom(this._localMatrix);
  76271. var poseMatrix = this._skeleton.getPoseMatrix();
  76272. if (poseMatrix) {
  76273. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  76274. }
  76275. }
  76276. var children = this.children;
  76277. var len = children.length;
  76278. for (var i = 0; i < len; i++) {
  76279. children[i].computeAbsoluteTransforms();
  76280. }
  76281. };
  76282. Bone.prototype._syncScaleVector = function () {
  76283. var lm = this.getLocalMatrix();
  76284. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  76285. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  76286. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  76287. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  76288. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  76289. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  76290. this._scaleVector.x = xs * Math.sqrt(xsq);
  76291. this._scaleVector.y = ys * Math.sqrt(ysq);
  76292. this._scaleVector.z = zs * Math.sqrt(zsq);
  76293. if (this._parent) {
  76294. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  76295. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  76296. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  76297. }
  76298. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  76299. };
  76300. /**
  76301. * Get the world direction from an axis that is in the local space of the bone.
  76302. * @param localAxis The local direction that is used to compute the world direction.
  76303. * @param mesh The mesh that this bone is attached to.
  76304. * @returns The world direction
  76305. */
  76306. Bone.prototype.getDirection = function (localAxis, mesh) {
  76307. if (mesh === void 0) { mesh = null; }
  76308. var result = BABYLON.Vector3.Zero();
  76309. this.getDirectionToRef(localAxis, mesh, result);
  76310. return result;
  76311. };
  76312. /**
  76313. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  76314. * @param localAxis The local direction that is used to compute the world direction.
  76315. * @param mesh The mesh that this bone is attached to.
  76316. * @param result The vector3 that the world direction will be copied to.
  76317. */
  76318. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  76319. if (mesh === void 0) { mesh = null; }
  76320. var wm = null;
  76321. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76322. if (mesh) {
  76323. wm = mesh.getWorldMatrix();
  76324. }
  76325. this._skeleton.computeAbsoluteTransforms();
  76326. var mat = Bone._tmpMats[0];
  76327. mat.copyFrom(this.getAbsoluteTransform());
  76328. if (mesh && wm) {
  76329. mat.multiplyToRef(wm, mat);
  76330. }
  76331. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  76332. result.normalize();
  76333. };
  76334. /**
  76335. * Get the euler rotation of the bone in local or world space.
  76336. * @param space The space that the rotation should be in.
  76337. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76338. * @returns The euler rotation
  76339. */
  76340. Bone.prototype.getRotation = function (space, mesh) {
  76341. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76342. if (mesh === void 0) { mesh = null; }
  76343. var result = BABYLON.Vector3.Zero();
  76344. this.getRotationToRef(space, mesh, result);
  76345. return result;
  76346. };
  76347. /**
  76348. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  76349. * @param space The space that the rotation should be in.
  76350. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76351. * @param result The vector3 that the rotation should be copied to.
  76352. */
  76353. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  76354. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76355. if (mesh === void 0) { mesh = null; }
  76356. var quat = Bone._tmpQuat;
  76357. this.getRotationQuaternionToRef(space, mesh, quat);
  76358. quat.toEulerAnglesToRef(result);
  76359. };
  76360. /**
  76361. * Get the quaternion rotation of the bone in either local or world space.
  76362. * @param space The space that the rotation should be in.
  76363. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76364. * @returns The quaternion rotation
  76365. */
  76366. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  76367. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76368. if (mesh === void 0) { mesh = null; }
  76369. var result = BABYLON.Quaternion.Identity();
  76370. this.getRotationQuaternionToRef(space, mesh, result);
  76371. return result;
  76372. };
  76373. /**
  76374. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  76375. * @param space The space that the rotation should be in.
  76376. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76377. * @param result The quaternion that the rotation should be copied to.
  76378. */
  76379. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  76380. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76381. if (mesh === void 0) { mesh = null; }
  76382. if (space == BABYLON.Space.LOCAL) {
  76383. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  76384. }
  76385. else {
  76386. var mat = Bone._tmpMats[0];
  76387. var amat = this.getAbsoluteTransform();
  76388. if (mesh) {
  76389. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76390. }
  76391. else {
  76392. mat.copyFrom(amat);
  76393. }
  76394. mat.m[0] *= this._scalingDeterminant;
  76395. mat.m[1] *= this._scalingDeterminant;
  76396. mat.m[2] *= this._scalingDeterminant;
  76397. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  76398. }
  76399. };
  76400. /**
  76401. * Get the rotation matrix of the bone in local or world space.
  76402. * @param space The space that the rotation should be in.
  76403. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76404. * @returns The rotation matrix
  76405. */
  76406. Bone.prototype.getRotationMatrix = function (space, mesh) {
  76407. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76408. var result = BABYLON.Matrix.Identity();
  76409. this.getRotationMatrixToRef(space, mesh, result);
  76410. return result;
  76411. };
  76412. /**
  76413. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  76414. * @param space The space that the rotation should be in.
  76415. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  76416. * @param result The quaternion that the rotation should be copied to.
  76417. */
  76418. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  76419. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76420. if (space == BABYLON.Space.LOCAL) {
  76421. this.getLocalMatrix().getRotationMatrixToRef(result);
  76422. }
  76423. else {
  76424. var mat = Bone._tmpMats[0];
  76425. var amat = this.getAbsoluteTransform();
  76426. if (mesh) {
  76427. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  76428. }
  76429. else {
  76430. mat.copyFrom(amat);
  76431. }
  76432. mat.m[0] *= this._scalingDeterminant;
  76433. mat.m[1] *= this._scalingDeterminant;
  76434. mat.m[2] *= this._scalingDeterminant;
  76435. mat.getRotationMatrixToRef(result);
  76436. }
  76437. };
  76438. /**
  76439. * Get the world position of a point that is in the local space of the bone.
  76440. * @param position The local position
  76441. * @param mesh The mesh that this bone is attached to.
  76442. * @returns The world position
  76443. */
  76444. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  76445. if (mesh === void 0) { mesh = null; }
  76446. var result = BABYLON.Vector3.Zero();
  76447. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  76448. return result;
  76449. };
  76450. /**
  76451. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  76452. * @param position The local position
  76453. * @param mesh The mesh that this bone is attached to.
  76454. * @param result The vector3 that the world position should be copied to.
  76455. */
  76456. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  76457. if (mesh === void 0) { mesh = null; }
  76458. var wm = null;
  76459. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76460. if (mesh) {
  76461. wm = mesh.getWorldMatrix();
  76462. }
  76463. this._skeleton.computeAbsoluteTransforms();
  76464. var tmat = Bone._tmpMats[0];
  76465. if (mesh && wm) {
  76466. tmat.copyFrom(this.getAbsoluteTransform());
  76467. tmat.multiplyToRef(wm, tmat);
  76468. }
  76469. else {
  76470. tmat = this.getAbsoluteTransform();
  76471. }
  76472. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76473. };
  76474. /**
  76475. * Get the local position of a point that is in world space.
  76476. * @param position The world position
  76477. * @param mesh The mesh that this bone is attached to.
  76478. * @returns The local position
  76479. */
  76480. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  76481. if (mesh === void 0) { mesh = null; }
  76482. var result = BABYLON.Vector3.Zero();
  76483. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  76484. return result;
  76485. };
  76486. /**
  76487. * Get the local position of a point that is in world space and copy it to the result param.
  76488. * @param position The world position
  76489. * @param mesh The mesh that this bone is attached to.
  76490. * @param result The vector3 that the local position should be copied to.
  76491. */
  76492. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  76493. if (mesh === void 0) { mesh = null; }
  76494. var wm = null;
  76495. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76496. if (mesh) {
  76497. wm = mesh.getWorldMatrix();
  76498. }
  76499. this._skeleton.computeAbsoluteTransforms();
  76500. var tmat = Bone._tmpMats[0];
  76501. tmat.copyFrom(this.getAbsoluteTransform());
  76502. if (mesh && wm) {
  76503. tmat.multiplyToRef(wm, tmat);
  76504. }
  76505. tmat.invert();
  76506. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  76507. };
  76508. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76509. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  76510. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76511. return Bone;
  76512. }(BABYLON.Node));
  76513. BABYLON.Bone = Bone;
  76514. })(BABYLON || (BABYLON = {}));
  76515. //# sourceMappingURL=babylon.bone.js.map
  76516. "use strict";
  76517. var BABYLON;
  76518. (function (BABYLON) {
  76519. var BoneIKController = /** @class */ (function () {
  76520. function BoneIKController(mesh, bone, options) {
  76521. this.targetPosition = BABYLON.Vector3.Zero();
  76522. this.poleTargetPosition = BABYLON.Vector3.Zero();
  76523. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  76524. this.poleAngle = 0;
  76525. this.slerpAmount = 1;
  76526. this._bone1Quat = BABYLON.Quaternion.Identity();
  76527. this._bone1Mat = BABYLON.Matrix.Identity();
  76528. this._bone2Ang = Math.PI;
  76529. this._maxAngle = Math.PI;
  76530. this._rightHandedSystem = false;
  76531. this._bendAxis = BABYLON.Vector3.Right();
  76532. this._slerping = false;
  76533. this._adjustRoll = 0;
  76534. this._bone2 = bone;
  76535. this._bone1 = bone.getParent();
  76536. if (!this._bone1) {
  76537. return;
  76538. }
  76539. this.mesh = mesh;
  76540. var bonePos = bone.getPosition();
  76541. if (bone.getAbsoluteTransform().determinant() > 0) {
  76542. this._rightHandedSystem = true;
  76543. this._bendAxis.x = 0;
  76544. this._bendAxis.y = 0;
  76545. this._bendAxis.z = -1;
  76546. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  76547. this._adjustRoll = Math.PI * .5;
  76548. this._bendAxis.z = 1;
  76549. }
  76550. }
  76551. if (this._bone1.length) {
  76552. var boneScale1 = this._bone1.getScale();
  76553. var boneScale2 = this._bone2.getScale();
  76554. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  76555. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  76556. }
  76557. else if (this._bone1.children[0]) {
  76558. mesh.computeWorldMatrix(true);
  76559. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  76560. var pos2 = this._bone2.getAbsolutePosition(mesh);
  76561. var pos3 = this._bone1.getAbsolutePosition(mesh);
  76562. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  76563. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  76564. }
  76565. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  76566. this.maxAngle = Math.PI;
  76567. if (options) {
  76568. if (options.targetMesh) {
  76569. this.targetMesh = options.targetMesh;
  76570. this.targetMesh.computeWorldMatrix(true);
  76571. }
  76572. if (options.poleTargetMesh) {
  76573. this.poleTargetMesh = options.poleTargetMesh;
  76574. this.poleTargetMesh.computeWorldMatrix(true);
  76575. }
  76576. else if (options.poleTargetBone) {
  76577. this.poleTargetBone = options.poleTargetBone;
  76578. }
  76579. else if (this._bone1.getParent()) {
  76580. this.poleTargetBone = this._bone1.getParent();
  76581. }
  76582. if (options.poleTargetLocalOffset) {
  76583. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  76584. }
  76585. if (options.poleAngle) {
  76586. this.poleAngle = options.poleAngle;
  76587. }
  76588. if (options.bendAxis) {
  76589. this._bendAxis.copyFrom(options.bendAxis);
  76590. }
  76591. if (options.maxAngle) {
  76592. this.maxAngle = options.maxAngle;
  76593. }
  76594. if (options.slerpAmount) {
  76595. this.slerpAmount = options.slerpAmount;
  76596. }
  76597. }
  76598. }
  76599. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  76600. get: function () {
  76601. return this._maxAngle;
  76602. },
  76603. set: function (value) {
  76604. this._setMaxAngle(value);
  76605. },
  76606. enumerable: true,
  76607. configurable: true
  76608. });
  76609. BoneIKController.prototype._setMaxAngle = function (ang) {
  76610. if (ang < 0) {
  76611. ang = 0;
  76612. }
  76613. if (ang > Math.PI || ang == undefined) {
  76614. ang = Math.PI;
  76615. }
  76616. this._maxAngle = ang;
  76617. var a = this._bone1Length;
  76618. var b = this._bone2Length;
  76619. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  76620. };
  76621. BoneIKController.prototype.update = function () {
  76622. var bone1 = this._bone1;
  76623. if (!bone1) {
  76624. return;
  76625. }
  76626. var target = this.targetPosition;
  76627. var poleTarget = this.poleTargetPosition;
  76628. var mat1 = BoneIKController._tmpMats[0];
  76629. var mat2 = BoneIKController._tmpMats[1];
  76630. if (this.targetMesh) {
  76631. target.copyFrom(this.targetMesh.getAbsolutePosition());
  76632. }
  76633. if (this.poleTargetBone) {
  76634. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  76635. }
  76636. else if (this.poleTargetMesh) {
  76637. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  76638. }
  76639. var bonePos = BoneIKController._tmpVecs[0];
  76640. var zaxis = BoneIKController._tmpVecs[1];
  76641. var xaxis = BoneIKController._tmpVecs[2];
  76642. var yaxis = BoneIKController._tmpVecs[3];
  76643. var upAxis = BoneIKController._tmpVecs[4];
  76644. var _tmpQuat = BoneIKController._tmpQuat;
  76645. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  76646. poleTarget.subtractToRef(bonePos, upAxis);
  76647. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  76648. upAxis.y = 1;
  76649. }
  76650. else {
  76651. upAxis.normalize();
  76652. }
  76653. target.subtractToRef(bonePos, yaxis);
  76654. yaxis.normalize();
  76655. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  76656. zaxis.normalize();
  76657. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  76658. xaxis.normalize();
  76659. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  76660. var a = this._bone1Length;
  76661. var b = this._bone2Length;
  76662. var c = BABYLON.Vector3.Distance(bonePos, target);
  76663. if (this._maxReach > 0) {
  76664. c = Math.min(this._maxReach, c);
  76665. }
  76666. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  76667. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  76668. if (acosa > 1) {
  76669. acosa = 1;
  76670. }
  76671. if (acosb > 1) {
  76672. acosb = 1;
  76673. }
  76674. if (acosa < -1) {
  76675. acosa = -1;
  76676. }
  76677. if (acosb < -1) {
  76678. acosb = -1;
  76679. }
  76680. var angA = Math.acos(acosa);
  76681. var angB = Math.acos(acosb);
  76682. var angC = -angA - angB;
  76683. if (this._rightHandedSystem) {
  76684. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  76685. mat2.multiplyToRef(mat1, mat1);
  76686. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  76687. mat2.multiplyToRef(mat1, mat1);
  76688. }
  76689. else {
  76690. var _tmpVec = BoneIKController._tmpVecs[5];
  76691. _tmpVec.copyFrom(this._bendAxis);
  76692. _tmpVec.x *= -1;
  76693. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  76694. mat2.multiplyToRef(mat1, mat1);
  76695. }
  76696. if (this.poleAngle) {
  76697. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  76698. mat1.multiplyToRef(mat2, mat1);
  76699. }
  76700. if (this._bone1) {
  76701. if (this.slerpAmount < 1) {
  76702. if (!this._slerping) {
  76703. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  76704. }
  76705. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  76706. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  76707. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  76708. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  76709. this._slerping = true;
  76710. }
  76711. else {
  76712. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  76713. this._bone1Mat.copyFrom(mat1);
  76714. this._slerping = false;
  76715. }
  76716. }
  76717. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  76718. this._bone2Ang = angC;
  76719. };
  76720. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76721. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  76722. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  76723. return BoneIKController;
  76724. }());
  76725. BABYLON.BoneIKController = BoneIKController;
  76726. })(BABYLON || (BABYLON = {}));
  76727. //# sourceMappingURL=babylon.boneIKController.js.map
  76728. "use strict";
  76729. var BABYLON;
  76730. (function (BABYLON) {
  76731. var BoneLookController = /** @class */ (function () {
  76732. /**
  76733. * Create a BoneLookController
  76734. * @param mesh the mesh that the bone belongs to
  76735. * @param bone the bone that will be looking to the target
  76736. * @param target the target Vector3 to look at
  76737. * @param settings optional settings:
  76738. * - maxYaw: the maximum angle the bone will yaw to
  76739. * - minYaw: the minimum angle the bone will yaw to
  76740. * - maxPitch: the maximum angle the bone will pitch to
  76741. * - minPitch: the minimum angle the bone will yaw to
  76742. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  76743. * - upAxis: the up axis of the coordinate system
  76744. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  76745. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  76746. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  76747. * - adjustYaw: used to make an adjustment to the yaw of the bone
  76748. * - adjustPitch: used to make an adjustment to the pitch of the bone
  76749. * - adjustRoll: used to make an adjustment to the roll of the bone
  76750. **/
  76751. function BoneLookController(mesh, bone, target, options) {
  76752. /**
  76753. * The up axis of the coordinate system that is used when the bone is rotated.
  76754. */
  76755. this.upAxis = BABYLON.Vector3.Up();
  76756. /**
  76757. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  76758. */
  76759. this.upAxisSpace = BABYLON.Space.LOCAL;
  76760. /**
  76761. * Used to make an adjustment to the yaw of the bone.
  76762. */
  76763. this.adjustYaw = 0;
  76764. /**
  76765. * Used to make an adjustment to the pitch of the bone.
  76766. */
  76767. this.adjustPitch = 0;
  76768. /**
  76769. * Used to make an adjustment to the roll of the bone.
  76770. */
  76771. this.adjustRoll = 0;
  76772. /**
  76773. * 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).
  76774. */
  76775. this.slerpAmount = 1;
  76776. this._boneQuat = BABYLON.Quaternion.Identity();
  76777. this._slerping = false;
  76778. this._firstFrameSkipped = false;
  76779. this._fowardAxis = BABYLON.Vector3.Forward();
  76780. this.mesh = mesh;
  76781. this.bone = bone;
  76782. this.target = target;
  76783. if (options) {
  76784. if (options.adjustYaw) {
  76785. this.adjustYaw = options.adjustYaw;
  76786. }
  76787. if (options.adjustPitch) {
  76788. this.adjustPitch = options.adjustPitch;
  76789. }
  76790. if (options.adjustRoll) {
  76791. this.adjustRoll = options.adjustRoll;
  76792. }
  76793. if (options.maxYaw != null) {
  76794. this.maxYaw = options.maxYaw;
  76795. }
  76796. else {
  76797. this.maxYaw = Math.PI;
  76798. }
  76799. if (options.minYaw != null) {
  76800. this.minYaw = options.minYaw;
  76801. }
  76802. else {
  76803. this.minYaw = -Math.PI;
  76804. }
  76805. if (options.maxPitch != null) {
  76806. this.maxPitch = options.maxPitch;
  76807. }
  76808. else {
  76809. this.maxPitch = Math.PI;
  76810. }
  76811. if (options.minPitch != null) {
  76812. this.minPitch = options.minPitch;
  76813. }
  76814. else {
  76815. this.minPitch = -Math.PI;
  76816. }
  76817. if (options.slerpAmount != null) {
  76818. this.slerpAmount = options.slerpAmount;
  76819. }
  76820. if (options.upAxis != null) {
  76821. this.upAxis = options.upAxis;
  76822. }
  76823. if (options.upAxisSpace != null) {
  76824. this.upAxisSpace = options.upAxisSpace;
  76825. }
  76826. if (options.yawAxis != null || options.pitchAxis != null) {
  76827. var newYawAxis = BABYLON.Axis.Y;
  76828. var newPitchAxis = BABYLON.Axis.X;
  76829. if (options.yawAxis != null) {
  76830. newYawAxis = options.yawAxis.clone();
  76831. newYawAxis.normalize();
  76832. }
  76833. if (options.pitchAxis != null) {
  76834. newPitchAxis = options.pitchAxis.clone();
  76835. newPitchAxis.normalize();
  76836. }
  76837. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  76838. this._transformYawPitch = BABYLON.Matrix.Identity();
  76839. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  76840. this._transformYawPitchInv = this._transformYawPitch.clone();
  76841. this._transformYawPitch.invert();
  76842. }
  76843. }
  76844. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  76845. this.upAxisSpace = BABYLON.Space.LOCAL;
  76846. }
  76847. }
  76848. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  76849. /**
  76850. * Get/set the minimum yaw angle that the bone can look to.
  76851. */
  76852. get: function () {
  76853. return this._minYaw;
  76854. },
  76855. set: function (value) {
  76856. this._minYaw = value;
  76857. this._minYawSin = Math.sin(value);
  76858. this._minYawCos = Math.cos(value);
  76859. if (this._maxYaw != null) {
  76860. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  76861. this._yawRange = this._maxYaw - this._minYaw;
  76862. }
  76863. },
  76864. enumerable: true,
  76865. configurable: true
  76866. });
  76867. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  76868. /**
  76869. * Get/set the maximum yaw angle that the bone can look to.
  76870. */
  76871. get: function () {
  76872. return this._maxYaw;
  76873. },
  76874. set: function (value) {
  76875. this._maxYaw = value;
  76876. this._maxYawSin = Math.sin(value);
  76877. this._maxYawCos = Math.cos(value);
  76878. if (this._minYaw != null) {
  76879. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  76880. this._yawRange = this._maxYaw - this._minYaw;
  76881. }
  76882. },
  76883. enumerable: true,
  76884. configurable: true
  76885. });
  76886. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  76887. /**
  76888. * Get/set the minimum pitch angle that the bone can look to.
  76889. */
  76890. get: function () {
  76891. return this._minPitch;
  76892. },
  76893. set: function (value) {
  76894. this._minPitch = value;
  76895. this._minPitchTan = Math.tan(value);
  76896. },
  76897. enumerable: true,
  76898. configurable: true
  76899. });
  76900. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  76901. /**
  76902. * Get/set the maximum pitch angle that the bone can look to.
  76903. */
  76904. get: function () {
  76905. return this._maxPitch;
  76906. },
  76907. set: function (value) {
  76908. this._maxPitch = value;
  76909. this._maxPitchTan = Math.tan(value);
  76910. },
  76911. enumerable: true,
  76912. configurable: true
  76913. });
  76914. /**
  76915. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  76916. */
  76917. BoneLookController.prototype.update = function () {
  76918. //skip the first frame when slerping so that the mesh rotation is correct
  76919. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  76920. this._firstFrameSkipped = true;
  76921. return;
  76922. }
  76923. var bone = this.bone;
  76924. var bonePos = BoneLookController._tmpVecs[0];
  76925. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  76926. var target = this.target;
  76927. var _tmpMat1 = BoneLookController._tmpMats[0];
  76928. var _tmpMat2 = BoneLookController._tmpMats[1];
  76929. var mesh = this.mesh;
  76930. var parentBone = bone.getParent();
  76931. var upAxis = BoneLookController._tmpVecs[1];
  76932. upAxis.copyFrom(this.upAxis);
  76933. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  76934. if (this._transformYawPitch) {
  76935. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  76936. }
  76937. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  76938. }
  76939. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  76940. mesh.getDirectionToRef(upAxis, upAxis);
  76941. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  76942. upAxis.normalize();
  76943. }
  76944. }
  76945. var checkYaw = false;
  76946. var checkPitch = false;
  76947. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  76948. checkYaw = true;
  76949. }
  76950. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  76951. checkPitch = true;
  76952. }
  76953. if (checkYaw || checkPitch) {
  76954. var spaceMat = BoneLookController._tmpMats[2];
  76955. var spaceMatInv = BoneLookController._tmpMats[3];
  76956. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  76957. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  76958. }
  76959. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  76960. spaceMat.copyFrom(mesh.getWorldMatrix());
  76961. }
  76962. else {
  76963. var forwardAxis = BoneLookController._tmpVecs[2];
  76964. forwardAxis.copyFrom(this._fowardAxis);
  76965. if (this._transformYawPitch) {
  76966. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  76967. }
  76968. if (parentBone) {
  76969. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  76970. }
  76971. else {
  76972. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  76973. }
  76974. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  76975. rightAxis.normalize();
  76976. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  76977. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  76978. }
  76979. spaceMat.invertToRef(spaceMatInv);
  76980. var xzlen = null;
  76981. if (checkPitch) {
  76982. var localTarget = BoneLookController._tmpVecs[3];
  76983. target.subtractToRef(bonePos, localTarget);
  76984. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  76985. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  76986. var pitch = Math.atan2(localTarget.y, xzlen);
  76987. var newPitch = pitch;
  76988. if (pitch > this._maxPitch) {
  76989. localTarget.y = this._maxPitchTan * xzlen;
  76990. newPitch = this._maxPitch;
  76991. }
  76992. else if (pitch < this._minPitch) {
  76993. localTarget.y = this._minPitchTan * xzlen;
  76994. newPitch = this._minPitch;
  76995. }
  76996. if (pitch != newPitch) {
  76997. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  76998. localTarget.addInPlace(bonePos);
  76999. target = localTarget;
  77000. }
  77001. }
  77002. if (checkYaw) {
  77003. var localTarget = BoneLookController._tmpVecs[4];
  77004. target.subtractToRef(bonePos, localTarget);
  77005. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  77006. var yaw = Math.atan2(localTarget.x, localTarget.z);
  77007. var newYaw = yaw;
  77008. if (yaw > this._maxYaw || yaw < this._minYaw) {
  77009. if (xzlen == null) {
  77010. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77011. }
  77012. if (this._yawRange > Math.PI) {
  77013. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  77014. localTarget.z = this._maxYawCos * xzlen;
  77015. localTarget.x = this._maxYawSin * xzlen;
  77016. newYaw = this._maxYaw;
  77017. }
  77018. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  77019. localTarget.z = this._minYawCos * xzlen;
  77020. localTarget.x = this._minYawSin * xzlen;
  77021. newYaw = this._minYaw;
  77022. }
  77023. }
  77024. else {
  77025. if (yaw > this._maxYaw) {
  77026. localTarget.z = this._maxYawCos * xzlen;
  77027. localTarget.x = this._maxYawSin * xzlen;
  77028. newYaw = this._maxYaw;
  77029. }
  77030. else if (yaw < this._minYaw) {
  77031. localTarget.z = this._minYawCos * xzlen;
  77032. localTarget.x = this._minYawSin * xzlen;
  77033. newYaw = this._minYaw;
  77034. }
  77035. }
  77036. }
  77037. if (this._slerping && this._yawRange > Math.PI) {
  77038. //are we going to be crossing into the min/max region?
  77039. var boneFwd = BoneLookController._tmpVecs[8];
  77040. boneFwd.copyFrom(BABYLON.Axis.Z);
  77041. if (this._transformYawPitch) {
  77042. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  77043. }
  77044. var boneRotMat = BoneLookController._tmpMats[4];
  77045. this._boneQuat.toRotationMatrix(boneRotMat);
  77046. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  77047. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  77048. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  77049. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  77050. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  77051. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  77052. if (angBtwTar > angBtwMidYaw) {
  77053. if (xzlen == null) {
  77054. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  77055. }
  77056. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  77057. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  77058. if (angBtwMin < angBtwMax) {
  77059. newYaw = boneYaw + Math.PI * .75;
  77060. localTarget.z = Math.cos(newYaw) * xzlen;
  77061. localTarget.x = Math.sin(newYaw) * xzlen;
  77062. }
  77063. else {
  77064. newYaw = boneYaw - Math.PI * .75;
  77065. localTarget.z = Math.cos(newYaw) * xzlen;
  77066. localTarget.x = Math.sin(newYaw) * xzlen;
  77067. }
  77068. }
  77069. }
  77070. if (yaw != newYaw) {
  77071. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  77072. localTarget.addInPlace(bonePos);
  77073. target = localTarget;
  77074. }
  77075. }
  77076. }
  77077. var zaxis = BoneLookController._tmpVecs[5];
  77078. var xaxis = BoneLookController._tmpVecs[6];
  77079. var yaxis = BoneLookController._tmpVecs[7];
  77080. var _tmpQuat = BoneLookController._tmpQuat;
  77081. target.subtractToRef(bonePos, zaxis);
  77082. zaxis.normalize();
  77083. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  77084. xaxis.normalize();
  77085. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  77086. yaxis.normalize();
  77087. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  77088. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  77089. return;
  77090. }
  77091. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  77092. return;
  77093. }
  77094. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  77095. return;
  77096. }
  77097. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  77098. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  77099. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  77100. }
  77101. if (this.slerpAmount < 1) {
  77102. if (!this._slerping) {
  77103. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  77104. }
  77105. if (this._transformYawPitch) {
  77106. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77107. }
  77108. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  77109. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  77110. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  77111. this._slerping = true;
  77112. }
  77113. else {
  77114. if (this._transformYawPitch) {
  77115. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  77116. }
  77117. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  77118. this._slerping = false;
  77119. }
  77120. };
  77121. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  77122. var angDiff = ang2 - ang1;
  77123. angDiff %= Math.PI * 2;
  77124. if (angDiff > Math.PI) {
  77125. angDiff -= Math.PI * 2;
  77126. }
  77127. else if (angDiff < -Math.PI) {
  77128. angDiff += Math.PI * 2;
  77129. }
  77130. return angDiff;
  77131. };
  77132. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  77133. ang1 %= (2 * Math.PI);
  77134. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77135. ang2 %= (2 * Math.PI);
  77136. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77137. var ab = 0;
  77138. if (ang1 < ang2) {
  77139. ab = ang2 - ang1;
  77140. }
  77141. else {
  77142. ab = ang1 - ang2;
  77143. }
  77144. if (ab > Math.PI) {
  77145. ab = Math.PI * 2 - ab;
  77146. }
  77147. return ab;
  77148. };
  77149. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  77150. ang %= (2 * Math.PI);
  77151. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  77152. ang1 %= (2 * Math.PI);
  77153. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  77154. ang2 %= (2 * Math.PI);
  77155. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  77156. if (ang1 < ang2) {
  77157. if (ang > ang1 && ang < ang2) {
  77158. return true;
  77159. }
  77160. }
  77161. else {
  77162. if (ang > ang2 && ang < ang1) {
  77163. return true;
  77164. }
  77165. }
  77166. return false;
  77167. };
  77168. 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()];
  77169. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  77170. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77171. return BoneLookController;
  77172. }());
  77173. BABYLON.BoneLookController = BoneLookController;
  77174. })(BABYLON || (BABYLON = {}));
  77175. //# sourceMappingURL=babylon.boneLookController.js.map
  77176. "use strict";
  77177. var BABYLON;
  77178. (function (BABYLON) {
  77179. var Skeleton = /** @class */ (function () {
  77180. function Skeleton(name, id, scene) {
  77181. this.name = name;
  77182. this.id = id;
  77183. this.bones = new Array();
  77184. this.needInitialSkinMatrix = false;
  77185. this._isDirty = true;
  77186. this._meshesWithPoseMatrix = new Array();
  77187. this._identity = BABYLON.Matrix.Identity();
  77188. this._ranges = {};
  77189. this._lastAbsoluteTransformsUpdateId = -1;
  77190. /**
  77191. * Specifies if the skeleton should be serialized.
  77192. */
  77193. this.doNotSerialize = false;
  77194. // Events
  77195. /**
  77196. * An event triggered before computing the skeleton's matrices
  77197. */
  77198. this.onBeforeComputeObservable = new BABYLON.Observable();
  77199. this.bones = [];
  77200. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77201. scene.skeletons.push(this);
  77202. //make sure it will recalculate the matrix next time prepare is called.
  77203. this._isDirty = true;
  77204. }
  77205. // Members
  77206. Skeleton.prototype.getTransformMatrices = function (mesh) {
  77207. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  77208. return mesh._bonesTransformMatrices;
  77209. }
  77210. if (!this._transformMatrices) {
  77211. this.prepare();
  77212. }
  77213. return this._transformMatrices;
  77214. };
  77215. Skeleton.prototype.getScene = function () {
  77216. return this._scene;
  77217. };
  77218. // Methods
  77219. /**
  77220. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  77221. */
  77222. Skeleton.prototype.toString = function (fullDetails) {
  77223. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  77224. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  77225. if (fullDetails) {
  77226. ret += ", Ranges: {";
  77227. var first = true;
  77228. for (var name_1 in this._ranges) {
  77229. if (first) {
  77230. ret += ", ";
  77231. first = false;
  77232. }
  77233. ret += name_1;
  77234. }
  77235. ret += "}";
  77236. }
  77237. return ret;
  77238. };
  77239. /**
  77240. * Get bone's index searching by name
  77241. * @param {string} name is bone's name to search for
  77242. * @return {number} Indice of the bone. Returns -1 if not found
  77243. */
  77244. Skeleton.prototype.getBoneIndexByName = function (name) {
  77245. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  77246. if (this.bones[boneIndex].name === name) {
  77247. return boneIndex;
  77248. }
  77249. }
  77250. return -1;
  77251. };
  77252. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  77253. // check name not already in use
  77254. if (!this._ranges[name]) {
  77255. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  77256. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77257. if (this.bones[i].animations[0]) {
  77258. this.bones[i].animations[0].createRange(name, from, to);
  77259. }
  77260. }
  77261. }
  77262. };
  77263. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  77264. if (deleteFrames === void 0) { deleteFrames = true; }
  77265. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77266. if (this.bones[i].animations[0]) {
  77267. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  77268. }
  77269. }
  77270. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  77271. };
  77272. Skeleton.prototype.getAnimationRange = function (name) {
  77273. return this._ranges[name];
  77274. };
  77275. /**
  77276. * Returns as an Array, all AnimationRanges defined on this skeleton
  77277. */
  77278. Skeleton.prototype.getAnimationRanges = function () {
  77279. var animationRanges = [];
  77280. var name;
  77281. var i = 0;
  77282. for (name in this._ranges) {
  77283. animationRanges[i] = this._ranges[name];
  77284. i++;
  77285. }
  77286. return animationRanges;
  77287. };
  77288. /**
  77289. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  77290. */
  77291. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  77292. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77293. if (this._ranges[name] || !source.getAnimationRange(name)) {
  77294. return false;
  77295. }
  77296. var ret = true;
  77297. var frameOffset = this._getHighestAnimationFrame() + 1;
  77298. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  77299. var boneDict = {};
  77300. var sourceBones = source.bones;
  77301. var nBones;
  77302. var i;
  77303. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  77304. boneDict[sourceBones[i].name] = sourceBones[i];
  77305. }
  77306. if (this.bones.length !== sourceBones.length) {
  77307. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  77308. ret = false;
  77309. }
  77310. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  77311. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  77312. var boneName = this.bones[i].name;
  77313. var sourceBone = boneDict[boneName];
  77314. if (sourceBone) {
  77315. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  77316. }
  77317. else {
  77318. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  77319. ret = false;
  77320. }
  77321. }
  77322. // do not call createAnimationRange(), since it also is done to bones, which was already done
  77323. var range = source.getAnimationRange(name);
  77324. if (range) {
  77325. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  77326. }
  77327. return ret;
  77328. };
  77329. Skeleton.prototype.returnToRest = function () {
  77330. for (var index = 0; index < this.bones.length; index++) {
  77331. this.bones[index].returnToRest();
  77332. }
  77333. };
  77334. Skeleton.prototype._getHighestAnimationFrame = function () {
  77335. var ret = 0;
  77336. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  77337. if (this.bones[i].animations[0]) {
  77338. var highest = this.bones[i].animations[0].getHighestFrame();
  77339. if (ret < highest) {
  77340. ret = highest;
  77341. }
  77342. }
  77343. }
  77344. return ret;
  77345. };
  77346. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  77347. var range = this.getAnimationRange(name);
  77348. if (!range) {
  77349. return null;
  77350. }
  77351. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  77352. };
  77353. Skeleton.prototype._markAsDirty = function () {
  77354. this._isDirty = true;
  77355. };
  77356. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  77357. this._meshesWithPoseMatrix.push(mesh);
  77358. };
  77359. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  77360. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  77361. if (index > -1) {
  77362. this._meshesWithPoseMatrix.splice(index, 1);
  77363. }
  77364. };
  77365. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  77366. this.onBeforeComputeObservable.notifyObservers(this);
  77367. for (var index = 0; index < this.bones.length; index++) {
  77368. var bone = this.bones[index];
  77369. var parentBone = bone.getParent();
  77370. if (parentBone) {
  77371. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  77372. }
  77373. else {
  77374. if (initialSkinMatrix) {
  77375. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  77376. }
  77377. else {
  77378. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  77379. }
  77380. }
  77381. if (bone._index !== -1) {
  77382. var mappedIndex = bone._index === null ? index : bone._index;
  77383. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  77384. }
  77385. }
  77386. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  77387. };
  77388. Skeleton.prototype.prepare = function () {
  77389. if (!this._isDirty) {
  77390. return;
  77391. }
  77392. if (this.needInitialSkinMatrix) {
  77393. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  77394. var mesh = this._meshesWithPoseMatrix[index];
  77395. var poseMatrix = mesh.getPoseMatrix();
  77396. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  77397. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77398. }
  77399. if (this._synchronizedWithMesh !== mesh) {
  77400. this._synchronizedWithMesh = mesh;
  77401. // Prepare bones
  77402. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  77403. var bone = this.bones[boneIndex];
  77404. if (!bone.getParent()) {
  77405. var matrix = bone.getBaseMatrix();
  77406. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  77407. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  77408. }
  77409. }
  77410. }
  77411. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  77412. }
  77413. }
  77414. else {
  77415. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  77416. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  77417. }
  77418. this._computeTransformMatrices(this._transformMatrices, null);
  77419. }
  77420. this._isDirty = false;
  77421. this._scene._activeBones.addCount(this.bones.length, false);
  77422. };
  77423. Skeleton.prototype.getAnimatables = function () {
  77424. if (!this._animatables || this._animatables.length !== this.bones.length) {
  77425. this._animatables = [];
  77426. for (var index = 0; index < this.bones.length; index++) {
  77427. this._animatables.push(this.bones[index]);
  77428. }
  77429. }
  77430. return this._animatables;
  77431. };
  77432. Skeleton.prototype.clone = function (name, id) {
  77433. var result = new Skeleton(name, id || name, this._scene);
  77434. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77435. for (var index = 0; index < this.bones.length; index++) {
  77436. var source = this.bones[index];
  77437. var parentBone = null;
  77438. var parent_1 = source.getParent();
  77439. if (parent_1) {
  77440. var parentIndex = this.bones.indexOf(parent_1);
  77441. parentBone = result.bones[parentIndex];
  77442. }
  77443. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  77444. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  77445. }
  77446. if (this._ranges) {
  77447. result._ranges = {};
  77448. for (var rangeName in this._ranges) {
  77449. var range = this._ranges[rangeName];
  77450. if (range) {
  77451. result._ranges[rangeName] = range.clone();
  77452. }
  77453. }
  77454. }
  77455. this._isDirty = true;
  77456. return result;
  77457. };
  77458. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  77459. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  77460. this.bones.forEach(function (bone) {
  77461. bone.animations.forEach(function (animation) {
  77462. animation.enableBlending = true;
  77463. animation.blendingSpeed = blendingSpeed;
  77464. });
  77465. });
  77466. };
  77467. Skeleton.prototype.dispose = function () {
  77468. this._meshesWithPoseMatrix = [];
  77469. // Animations
  77470. this.getScene().stopAnimation(this);
  77471. // Remove from scene
  77472. this.getScene().removeSkeleton(this);
  77473. };
  77474. Skeleton.prototype.serialize = function () {
  77475. var serializationObject = {};
  77476. serializationObject.name = this.name;
  77477. serializationObject.id = this.id;
  77478. if (this.dimensionsAtRest) {
  77479. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  77480. }
  77481. serializationObject.bones = [];
  77482. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  77483. for (var index = 0; index < this.bones.length; index++) {
  77484. var bone = this.bones[index];
  77485. var parent_2 = bone.getParent();
  77486. var serializedBone = {
  77487. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  77488. name: bone.name,
  77489. matrix: bone.getBaseMatrix().toArray(),
  77490. rest: bone.getRestPose().toArray()
  77491. };
  77492. serializationObject.bones.push(serializedBone);
  77493. if (bone.length) {
  77494. serializedBone.length = bone.length;
  77495. }
  77496. if (bone.animations && bone.animations.length > 0) {
  77497. serializedBone.animation = bone.animations[0].serialize();
  77498. }
  77499. serializationObject.ranges = [];
  77500. for (var name in this._ranges) {
  77501. var source = this._ranges[name];
  77502. if (!source) {
  77503. continue;
  77504. }
  77505. var range = {};
  77506. range.name = name;
  77507. range.from = source.from;
  77508. range.to = source.to;
  77509. serializationObject.ranges.push(range);
  77510. }
  77511. }
  77512. return serializationObject;
  77513. };
  77514. Skeleton.Parse = function (parsedSkeleton, scene) {
  77515. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  77516. if (parsedSkeleton.dimensionsAtRest) {
  77517. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  77518. }
  77519. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  77520. var index;
  77521. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  77522. var parsedBone = parsedSkeleton.bones[index];
  77523. var parentBone = null;
  77524. if (parsedBone.parentBoneIndex > -1) {
  77525. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  77526. }
  77527. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  77528. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  77529. if (parsedBone.length) {
  77530. bone.length = parsedBone.length;
  77531. }
  77532. if (parsedBone.animation) {
  77533. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  77534. }
  77535. }
  77536. // placed after bones, so createAnimationRange can cascade down
  77537. if (parsedSkeleton.ranges) {
  77538. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  77539. var data = parsedSkeleton.ranges[index];
  77540. skeleton.createAnimationRange(data.name, data.from, data.to);
  77541. }
  77542. }
  77543. return skeleton;
  77544. };
  77545. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  77546. if (forceUpdate === void 0) { forceUpdate = false; }
  77547. var renderId = this._scene.getRenderId();
  77548. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  77549. this.bones[0].computeAbsoluteTransforms();
  77550. this._lastAbsoluteTransformsUpdateId = renderId;
  77551. }
  77552. };
  77553. Skeleton.prototype.getPoseMatrix = function () {
  77554. var poseMatrix = null;
  77555. if (this._meshesWithPoseMatrix.length > 0) {
  77556. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  77557. }
  77558. return poseMatrix;
  77559. };
  77560. Skeleton.prototype.sortBones = function () {
  77561. var bones = new Array();
  77562. var visited = new Array(this.bones.length);
  77563. for (var index = 0; index < this.bones.length; index++) {
  77564. this._sortBones(index, bones, visited);
  77565. }
  77566. this.bones = bones;
  77567. };
  77568. Skeleton.prototype._sortBones = function (index, bones, visited) {
  77569. if (visited[index]) {
  77570. return;
  77571. }
  77572. visited[index] = true;
  77573. var bone = this.bones[index];
  77574. if (bone._index === undefined) {
  77575. bone._index = index;
  77576. }
  77577. var parentBone = bone.getParent();
  77578. if (parentBone) {
  77579. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  77580. }
  77581. bones.push(bone);
  77582. };
  77583. return Skeleton;
  77584. }());
  77585. BABYLON.Skeleton = Skeleton;
  77586. })(BABYLON || (BABYLON = {}));
  77587. //# sourceMappingURL=babylon.skeleton.js.map
  77588. "use strict";
  77589. var BABYLON;
  77590. (function (BABYLON) {
  77591. var SphericalPolynomial = /** @class */ (function () {
  77592. function SphericalPolynomial() {
  77593. this.x = BABYLON.Vector3.Zero();
  77594. this.y = BABYLON.Vector3.Zero();
  77595. this.z = BABYLON.Vector3.Zero();
  77596. this.xx = BABYLON.Vector3.Zero();
  77597. this.yy = BABYLON.Vector3.Zero();
  77598. this.zz = BABYLON.Vector3.Zero();
  77599. this.xy = BABYLON.Vector3.Zero();
  77600. this.yz = BABYLON.Vector3.Zero();
  77601. this.zx = BABYLON.Vector3.Zero();
  77602. }
  77603. SphericalPolynomial.prototype.addAmbient = function (color) {
  77604. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77605. this.xx = this.xx.add(colorVector);
  77606. this.yy = this.yy.add(colorVector);
  77607. this.zz = this.zz.add(colorVector);
  77608. };
  77609. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  77610. var result = new SphericalPolynomial();
  77611. result.x = harmonics.L11.scale(1.02333);
  77612. result.y = harmonics.L1_1.scale(1.02333);
  77613. result.z = harmonics.L10.scale(1.02333);
  77614. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  77615. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  77616. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  77617. result.yz = harmonics.L2_1.scale(0.858086);
  77618. result.zx = harmonics.L21.scale(0.858086);
  77619. result.xy = harmonics.L2_2.scale(0.858086);
  77620. result.scale(1.0 / Math.PI);
  77621. return result;
  77622. };
  77623. SphericalPolynomial.prototype.scale = function (scale) {
  77624. this.x = this.x.scale(scale);
  77625. this.y = this.y.scale(scale);
  77626. this.z = this.z.scale(scale);
  77627. this.xx = this.xx.scale(scale);
  77628. this.yy = this.yy.scale(scale);
  77629. this.zz = this.zz.scale(scale);
  77630. this.yz = this.yz.scale(scale);
  77631. this.zx = this.zx.scale(scale);
  77632. this.xy = this.xy.scale(scale);
  77633. };
  77634. return SphericalPolynomial;
  77635. }());
  77636. BABYLON.SphericalPolynomial = SphericalPolynomial;
  77637. var SphericalHarmonics = /** @class */ (function () {
  77638. function SphericalHarmonics() {
  77639. this.L00 = BABYLON.Vector3.Zero();
  77640. this.L1_1 = BABYLON.Vector3.Zero();
  77641. this.L10 = BABYLON.Vector3.Zero();
  77642. this.L11 = BABYLON.Vector3.Zero();
  77643. this.L2_2 = BABYLON.Vector3.Zero();
  77644. this.L2_1 = BABYLON.Vector3.Zero();
  77645. this.L20 = BABYLON.Vector3.Zero();
  77646. this.L21 = BABYLON.Vector3.Zero();
  77647. this.L22 = BABYLON.Vector3.Zero();
  77648. }
  77649. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  77650. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  77651. var c = colorVector.scale(deltaSolidAngle);
  77652. this.L00 = this.L00.add(c.scale(0.282095));
  77653. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  77654. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  77655. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  77656. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  77657. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  77658. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  77659. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  77660. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  77661. };
  77662. SphericalHarmonics.prototype.scale = function (scale) {
  77663. this.L00 = this.L00.scale(scale);
  77664. this.L1_1 = this.L1_1.scale(scale);
  77665. this.L10 = this.L10.scale(scale);
  77666. this.L11 = this.L11.scale(scale);
  77667. this.L2_2 = this.L2_2.scale(scale);
  77668. this.L2_1 = this.L2_1.scale(scale);
  77669. this.L20 = this.L20.scale(scale);
  77670. this.L21 = this.L21.scale(scale);
  77671. this.L22 = this.L22.scale(scale);
  77672. };
  77673. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  77674. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  77675. //
  77676. // E_lm = A_l * L_lm
  77677. //
  77678. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  77679. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  77680. // the scaling factors are given in equation 9.
  77681. // Constant (Band 0)
  77682. this.L00 = this.L00.scale(3.141593);
  77683. // Linear (Band 1)
  77684. this.L1_1 = this.L1_1.scale(2.094395);
  77685. this.L10 = this.L10.scale(2.094395);
  77686. this.L11 = this.L11.scale(2.094395);
  77687. // Quadratic (Band 2)
  77688. this.L2_2 = this.L2_2.scale(0.785398);
  77689. this.L2_1 = this.L2_1.scale(0.785398);
  77690. this.L20 = this.L20.scale(0.785398);
  77691. this.L21 = this.L21.scale(0.785398);
  77692. this.L22 = this.L22.scale(0.785398);
  77693. };
  77694. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  77695. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  77696. // L = (1/pi) * E * rho
  77697. //
  77698. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  77699. this.scale(1.0 / Math.PI);
  77700. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  77701. // (The pixel shader must apply albedo after texture fetches, etc).
  77702. };
  77703. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  77704. var result = new SphericalHarmonics();
  77705. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  77706. result.L1_1 = polynomial.y.scale(0.977204);
  77707. result.L10 = polynomial.z.scale(0.977204);
  77708. result.L11 = polynomial.x.scale(0.977204);
  77709. result.L2_2 = polynomial.xy.scale(1.16538);
  77710. result.L2_1 = polynomial.yz.scale(1.16538);
  77711. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  77712. result.L21 = polynomial.zx.scale(1.16538);
  77713. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  77714. result.scale(Math.PI);
  77715. return result;
  77716. };
  77717. return SphericalHarmonics;
  77718. }());
  77719. BABYLON.SphericalHarmonics = SphericalHarmonics;
  77720. })(BABYLON || (BABYLON = {}));
  77721. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  77722. "use strict";
  77723. var BABYLON;
  77724. (function (BABYLON) {
  77725. var FileFaceOrientation = /** @class */ (function () {
  77726. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  77727. this.name = name;
  77728. this.worldAxisForNormal = worldAxisForNormal;
  77729. this.worldAxisForFileX = worldAxisForFileX;
  77730. this.worldAxisForFileY = worldAxisForFileY;
  77731. }
  77732. return FileFaceOrientation;
  77733. }());
  77734. ;
  77735. /**
  77736. * Helper class dealing with the extraction of spherical polynomial dataArray
  77737. * from a cube map.
  77738. */
  77739. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  77740. function CubeMapToSphericalPolynomialTools() {
  77741. }
  77742. /**
  77743. * Converts a texture to the according Spherical Polynomial data.
  77744. * This extracts the first 3 orders only as they are the only one used in the lighting.
  77745. *
  77746. * @param texture The texture to extract the information from.
  77747. * @return The Spherical Polynomial data.
  77748. */
  77749. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  77750. if (!texture.isCube) {
  77751. // Only supports cube Textures currently.
  77752. return null;
  77753. }
  77754. var size = texture.getSize().width;
  77755. var right = texture.readPixels(0);
  77756. var left = texture.readPixels(1);
  77757. var up;
  77758. var down;
  77759. if (texture.isRenderTarget) {
  77760. up = texture.readPixels(3);
  77761. down = texture.readPixels(2);
  77762. }
  77763. else {
  77764. up = texture.readPixels(2);
  77765. down = texture.readPixels(3);
  77766. }
  77767. var front = texture.readPixels(4);
  77768. var back = texture.readPixels(5);
  77769. var gammaSpace = texture.gammaSpace;
  77770. // Always read as RGBA.
  77771. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  77772. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77773. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77774. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77775. }
  77776. var cubeInfo = {
  77777. size: size,
  77778. right: right,
  77779. left: left,
  77780. up: up,
  77781. down: down,
  77782. front: front,
  77783. back: back,
  77784. format: format,
  77785. type: type,
  77786. gammaSpace: gammaSpace,
  77787. };
  77788. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  77789. };
  77790. /**
  77791. * Converts a cubemap to the according Spherical Polynomial data.
  77792. * This extracts the first 3 orders only as they are the only one used in the lighting.
  77793. *
  77794. * @param cubeInfo The Cube map to extract the information from.
  77795. * @return The Spherical Polynomial data.
  77796. */
  77797. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  77798. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  77799. var totalSolidAngle = 0.0;
  77800. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  77801. var du = 2.0 / cubeInfo.size;
  77802. var dv = du;
  77803. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  77804. var minUV = du * 0.5 - 1.0;
  77805. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  77806. var fileFace = this.FileFaces[faceIndex];
  77807. var dataArray = cubeInfo[fileFace.name];
  77808. var v = minUV;
  77809. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  77810. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  77811. // Because SP is still linear, so summation is fine in that basis.
  77812. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  77813. for (var y = 0; y < cubeInfo.size; y++) {
  77814. var u = minUV;
  77815. for (var x = 0; x < cubeInfo.size; x++) {
  77816. // World direction (not normalised)
  77817. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  77818. worldDirection.normalize();
  77819. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  77820. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  77821. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  77822. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  77823. // Handle Integer types.
  77824. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  77825. r /= 255;
  77826. g /= 255;
  77827. b /= 255;
  77828. }
  77829. // Handle Gamma space textures.
  77830. if (cubeInfo.gammaSpace) {
  77831. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  77832. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  77833. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  77834. }
  77835. var color = new BABYLON.Color3(r, g, b);
  77836. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  77837. totalSolidAngle += deltaSolidAngle;
  77838. u += du;
  77839. }
  77840. v += dv;
  77841. }
  77842. }
  77843. // Solid angle for entire sphere is 4*pi
  77844. var sphereSolidAngle = 4.0 * Math.PI;
  77845. // Adjust the solid angle to allow for how many faces we processed.
  77846. var facesProcessed = 6.0;
  77847. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  77848. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  77849. // This is needed because the numerical integration over the cube uses a
  77850. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  77851. // and also to compensate for accumulative error due to float precision in the summation.
  77852. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  77853. sphericalHarmonics.scale(correctionFactor);
  77854. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  77855. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  77856. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  77857. };
  77858. CubeMapToSphericalPolynomialTools.FileFaces = [
  77859. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  77860. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  77861. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  77862. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  77863. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  77864. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  77865. ];
  77866. return CubeMapToSphericalPolynomialTools;
  77867. }());
  77868. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  77869. })(BABYLON || (BABYLON = {}));
  77870. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  77871. "use strict";
  77872. var BABYLON;
  77873. (function (BABYLON) {
  77874. /**
  77875. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  77876. */
  77877. var PanoramaToCubeMapTools = /** @class */ (function () {
  77878. function PanoramaToCubeMapTools() {
  77879. }
  77880. /**
  77881. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  77882. *
  77883. * @param float32Array The source data.
  77884. * @param inputWidth The width of the input panorama.
  77885. * @param inputhHeight The height of the input panorama.
  77886. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  77887. * @return The cubemap data
  77888. */
  77889. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  77890. if (!float32Array) {
  77891. throw "ConvertPanoramaToCubemap: input cannot be null";
  77892. }
  77893. if (float32Array.length != inputWidth * inputHeight * 3) {
  77894. throw "ConvertPanoramaToCubemap: input size is wrong";
  77895. }
  77896. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  77897. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  77898. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  77899. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  77900. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  77901. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  77902. return {
  77903. front: textureFront,
  77904. back: textureBack,
  77905. left: textureLeft,
  77906. right: textureRight,
  77907. up: textureUp,
  77908. down: textureDown,
  77909. size: size,
  77910. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  77911. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  77912. gammaSpace: false,
  77913. };
  77914. };
  77915. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  77916. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  77917. var textureArray = new Float32Array(buffer);
  77918. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  77919. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  77920. var dy = 1 / texSize;
  77921. var fy = 0;
  77922. for (var y = 0; y < texSize; y++) {
  77923. var xv1 = faceData[0];
  77924. var xv2 = faceData[2];
  77925. for (var x = 0; x < texSize; x++) {
  77926. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  77927. v.normalize();
  77928. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  77929. // 3 channels per pixels
  77930. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  77931. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  77932. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  77933. xv1 = xv1.add(rotDX1);
  77934. xv2 = xv2.add(rotDX2);
  77935. }
  77936. fy += dy;
  77937. }
  77938. return textureArray;
  77939. };
  77940. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  77941. var theta = Math.atan2(vDir.z, vDir.x);
  77942. var phi = Math.acos(vDir.y);
  77943. while (theta < -Math.PI)
  77944. theta += 2 * Math.PI;
  77945. while (theta > Math.PI)
  77946. theta -= 2 * Math.PI;
  77947. var dx = theta / Math.PI;
  77948. var dy = phi / Math.PI;
  77949. // recenter.
  77950. dx = dx * 0.5 + 0.5;
  77951. var px = Math.round(dx * inputWidth);
  77952. if (px < 0)
  77953. px = 0;
  77954. else if (px >= inputWidth)
  77955. px = inputWidth - 1;
  77956. var py = Math.round(dy * inputHeight);
  77957. if (py < 0)
  77958. py = 0;
  77959. else if (py >= inputHeight)
  77960. py = inputHeight - 1;
  77961. var inputY = (inputHeight - py - 1);
  77962. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  77963. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  77964. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  77965. return {
  77966. r: r,
  77967. g: g,
  77968. b: b
  77969. };
  77970. };
  77971. PanoramaToCubeMapTools.FACE_FRONT = [
  77972. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77973. new BABYLON.Vector3(1.0, -1.0, -1.0),
  77974. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  77975. new BABYLON.Vector3(1.0, 1.0, -1.0)
  77976. ];
  77977. PanoramaToCubeMapTools.FACE_BACK = [
  77978. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77979. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77980. new BABYLON.Vector3(1.0, 1.0, 1.0),
  77981. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  77982. ];
  77983. PanoramaToCubeMapTools.FACE_RIGHT = [
  77984. new BABYLON.Vector3(1.0, -1.0, -1.0),
  77985. new BABYLON.Vector3(1.0, -1.0, 1.0),
  77986. new BABYLON.Vector3(1.0, 1.0, -1.0),
  77987. new BABYLON.Vector3(1.0, 1.0, 1.0)
  77988. ];
  77989. PanoramaToCubeMapTools.FACE_LEFT = [
  77990. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  77991. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  77992. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  77993. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  77994. ];
  77995. PanoramaToCubeMapTools.FACE_DOWN = [
  77996. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  77997. new BABYLON.Vector3(1.0, 1.0, -1.0),
  77998. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  77999. new BABYLON.Vector3(1.0, 1.0, 1.0)
  78000. ];
  78001. PanoramaToCubeMapTools.FACE_UP = [
  78002. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  78003. new BABYLON.Vector3(1.0, -1.0, 1.0),
  78004. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  78005. new BABYLON.Vector3(1.0, -1.0, -1.0)
  78006. ];
  78007. return PanoramaToCubeMapTools;
  78008. }());
  78009. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  78010. })(BABYLON || (BABYLON = {}));
  78011. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  78012. "use strict";
  78013. var BABYLON;
  78014. (function (BABYLON) {
  78015. ;
  78016. /**
  78017. * This groups tools to convert HDR texture to native colors array.
  78018. */
  78019. var HDRTools = /** @class */ (function () {
  78020. function HDRTools() {
  78021. }
  78022. HDRTools.Ldexp = function (mantissa, exponent) {
  78023. if (exponent > 1023) {
  78024. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  78025. }
  78026. if (exponent < -1074) {
  78027. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  78028. }
  78029. return mantissa * Math.pow(2, exponent);
  78030. };
  78031. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  78032. if (exponent > 0) {
  78033. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  78034. float32array[index + 0] = red * exponent;
  78035. float32array[index + 1] = green * exponent;
  78036. float32array[index + 2] = blue * exponent;
  78037. }
  78038. else {
  78039. float32array[index + 0] = 0;
  78040. float32array[index + 1] = 0;
  78041. float32array[index + 2] = 0;
  78042. }
  78043. };
  78044. HDRTools.readStringLine = function (uint8array, startIndex) {
  78045. var line = "";
  78046. var character = "";
  78047. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  78048. character = String.fromCharCode(uint8array[i]);
  78049. if (character == "\n") {
  78050. break;
  78051. }
  78052. line += character;
  78053. }
  78054. return line;
  78055. };
  78056. /**
  78057. * Reads header information from an RGBE texture stored in a native array.
  78058. * More information on this format are available here:
  78059. * https://en.wikipedia.org/wiki/RGBE_image_format
  78060. *
  78061. * @param uint8array The binary file stored in native array.
  78062. * @return The header information.
  78063. */
  78064. HDRTools.RGBE_ReadHeader = function (uint8array) {
  78065. var height = 0;
  78066. var width = 0;
  78067. var line = this.readStringLine(uint8array, 0);
  78068. if (line[0] != '#' || line[1] != '?') {
  78069. throw "Bad HDR Format.";
  78070. }
  78071. var endOfHeader = false;
  78072. var findFormat = false;
  78073. var lineIndex = 0;
  78074. do {
  78075. lineIndex += (line.length + 1);
  78076. line = this.readStringLine(uint8array, lineIndex);
  78077. if (line == "FORMAT=32-bit_rle_rgbe") {
  78078. findFormat = true;
  78079. }
  78080. else if (line.length == 0) {
  78081. endOfHeader = true;
  78082. }
  78083. } while (!endOfHeader);
  78084. if (!findFormat) {
  78085. throw "HDR Bad header format, unsupported FORMAT";
  78086. }
  78087. lineIndex += (line.length + 1);
  78088. line = this.readStringLine(uint8array, lineIndex);
  78089. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  78090. var match = sizeRegexp.exec(line);
  78091. // TODO. Support +Y and -X if needed.
  78092. if (!match || match.length < 3) {
  78093. throw "HDR Bad header format, no size";
  78094. }
  78095. width = parseInt(match[2]);
  78096. height = parseInt(match[1]);
  78097. if (width < 8 || width > 0x7fff) {
  78098. throw "HDR Bad header format, unsupported size";
  78099. }
  78100. lineIndex += (line.length + 1);
  78101. return {
  78102. height: height,
  78103. width: width,
  78104. dataPosition: lineIndex
  78105. };
  78106. };
  78107. /**
  78108. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  78109. * This RGBE texture needs to store the information as a panorama.
  78110. *
  78111. * More information on this format are available here:
  78112. * https://en.wikipedia.org/wiki/RGBE_image_format
  78113. *
  78114. * @param buffer The binary file stored in an array buffer.
  78115. * @param size The expected size of the extracted cubemap.
  78116. * @return The Cube Map information.
  78117. */
  78118. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  78119. var uint8array = new Uint8Array(buffer);
  78120. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  78121. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78122. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  78123. return cubeMapData;
  78124. };
  78125. /**
  78126. * Returns the pixels data extracted from an RGBE texture.
  78127. * This pixels will be stored left to right up to down in the R G B order in one array.
  78128. *
  78129. * More information on this format are available here:
  78130. * https://en.wikipedia.org/wiki/RGBE_image_format
  78131. *
  78132. * @param uint8array The binary file stored in an array buffer.
  78133. * @param hdrInfo The header information of the file.
  78134. * @return The pixels data in RGB right to left up to down order.
  78135. */
  78136. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  78137. // Keep for multi format supports.
  78138. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  78139. };
  78140. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  78141. var num_scanlines = hdrInfo.height;
  78142. var scanline_width = hdrInfo.width;
  78143. var a, b, c, d, count;
  78144. var dataIndex = hdrInfo.dataPosition;
  78145. var index = 0, endIndex = 0, i = 0;
  78146. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  78147. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  78148. // 3 channels of 4 bytes per pixel in float.
  78149. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  78150. var resultArray = new Float32Array(resultBuffer);
  78151. // read in each successive scanline
  78152. while (num_scanlines > 0) {
  78153. a = uint8array[dataIndex++];
  78154. b = uint8array[dataIndex++];
  78155. c = uint8array[dataIndex++];
  78156. d = uint8array[dataIndex++];
  78157. if (a != 2 || b != 2 || (c & 0x80)) {
  78158. // this file is not run length encoded
  78159. throw "HDR Bad header format, not RLE";
  78160. }
  78161. if (((c << 8) | d) != scanline_width) {
  78162. throw "HDR Bad header format, wrong scan line width";
  78163. }
  78164. index = 0;
  78165. // read each of the four channels for the scanline into the buffer
  78166. for (i = 0; i < 4; i++) {
  78167. endIndex = (i + 1) * scanline_width;
  78168. while (index < endIndex) {
  78169. a = uint8array[dataIndex++];
  78170. b = uint8array[dataIndex++];
  78171. if (a > 128) {
  78172. // a run of the same value
  78173. count = a - 128;
  78174. if ((count == 0) || (count > endIndex - index)) {
  78175. throw "HDR Bad Format, bad scanline data (run)";
  78176. }
  78177. while (count-- > 0) {
  78178. scanLineArray[index++] = b;
  78179. }
  78180. }
  78181. else {
  78182. // a non-run
  78183. count = a;
  78184. if ((count == 0) || (count > endIndex - index)) {
  78185. throw "HDR Bad Format, bad scanline data (non-run)";
  78186. }
  78187. scanLineArray[index++] = b;
  78188. if (--count > 0) {
  78189. for (var j = 0; j < count; j++) {
  78190. scanLineArray[index++] = uint8array[dataIndex++];
  78191. }
  78192. }
  78193. }
  78194. }
  78195. }
  78196. // now convert data from buffer into floats
  78197. for (i = 0; i < scanline_width; i++) {
  78198. a = scanLineArray[i];
  78199. b = scanLineArray[i + scanline_width];
  78200. c = scanLineArray[i + 2 * scanline_width];
  78201. d = scanLineArray[i + 3 * scanline_width];
  78202. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  78203. }
  78204. num_scanlines--;
  78205. }
  78206. return resultArray;
  78207. };
  78208. return HDRTools;
  78209. }());
  78210. BABYLON.HDRTools = HDRTools;
  78211. })(BABYLON || (BABYLON = {}));
  78212. //# sourceMappingURL=babylon.hdr.js.map
  78213. "use strict";
  78214. var BABYLON;
  78215. (function (BABYLON) {
  78216. /**
  78217. * This represents a texture coming from an HDR input.
  78218. *
  78219. * The only supported format is currently panorama picture stored in RGBE format.
  78220. * Example of such files can be found on HDRLib: http://hdrlib.com/
  78221. */
  78222. var HDRCubeTexture = /** @class */ (function (_super) {
  78223. __extends(HDRCubeTexture, _super);
  78224. /**
  78225. * Instantiates an HDRTexture from the following parameters.
  78226. *
  78227. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  78228. * @param scene The scene the texture will be used in
  78229. * @param size The cubemap 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.
  78230. * @param noMipmap Forces to not generate the mipmap if true
  78231. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  78232. * @param useInGammaSpace 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)
  78233. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  78234. */
  78235. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  78236. if (noMipmap === void 0) { noMipmap = false; }
  78237. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78238. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78239. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78240. if (onLoad === void 0) { onLoad = null; }
  78241. if (onError === void 0) { onError = null; }
  78242. var _this = _super.call(this, scene) || this;
  78243. _this._useInGammaSpace = false;
  78244. _this._generateHarmonics = true;
  78245. _this._isBABYLONPreprocessed = false;
  78246. _this._onLoad = null;
  78247. _this._onError = null;
  78248. /**
  78249. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  78250. */
  78251. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  78252. /**
  78253. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  78254. * This is usefull at run time to apply the good shader.
  78255. */
  78256. _this.isPMREM = false;
  78257. _this._isBlocking = true;
  78258. _this._rotationY = 0;
  78259. /**
  78260. * Gets or sets the center of the bounding box associated with the cube texture
  78261. * It must define where the camera used to render the texture was set
  78262. */
  78263. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  78264. if (!url) {
  78265. return _this;
  78266. }
  78267. _this.name = url;
  78268. _this.url = url;
  78269. _this.hasAlpha = false;
  78270. _this.isCube = true;
  78271. _this._textureMatrix = BABYLON.Matrix.Identity();
  78272. _this._onLoad = onLoad;
  78273. _this._onError = onError;
  78274. _this.gammaSpace = false;
  78275. var caps = scene.getEngine().getCaps();
  78276. if (size) {
  78277. _this._isBABYLONPreprocessed = false;
  78278. _this._noMipmap = noMipmap;
  78279. _this._size = size;
  78280. _this._useInGammaSpace = useInGammaSpace;
  78281. _this._usePMREMGenerator = usePMREMGenerator &&
  78282. caps.textureLOD &&
  78283. caps.textureFloat &&
  78284. !_this._useInGammaSpace;
  78285. }
  78286. else {
  78287. _this._isBABYLONPreprocessed = true;
  78288. _this._noMipmap = false;
  78289. _this._useInGammaSpace = false;
  78290. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  78291. !_this._useInGammaSpace;
  78292. }
  78293. _this.isPMREM = _this._usePMREMGenerator;
  78294. _this._texture = _this._getFromCache(url, _this._noMipmap);
  78295. if (!_this._texture) {
  78296. if (!scene.useDelayedTextureLoading) {
  78297. _this.loadTexture();
  78298. }
  78299. else {
  78300. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  78301. }
  78302. }
  78303. return _this;
  78304. }
  78305. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  78306. /**
  78307. * Gets wether or not the texture is blocking during loading.
  78308. */
  78309. get: function () {
  78310. return this._isBlocking;
  78311. },
  78312. /**
  78313. * Sets wether or not the texture is blocking during loading.
  78314. */
  78315. set: function (value) {
  78316. this._isBlocking = value;
  78317. },
  78318. enumerable: true,
  78319. configurable: true
  78320. });
  78321. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  78322. /**
  78323. * Gets texture matrix rotation angle around Y axis radians.
  78324. */
  78325. get: function () {
  78326. return this._rotationY;
  78327. },
  78328. /**
  78329. * Sets texture matrix rotation angle around Y axis in radians.
  78330. */
  78331. set: function (value) {
  78332. this._rotationY = value;
  78333. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  78334. },
  78335. enumerable: true,
  78336. configurable: true
  78337. });
  78338. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  78339. get: function () {
  78340. return this._boundingBoxSize;
  78341. },
  78342. /**
  78343. * Gets or sets the size of the bounding box associated with the cube texture
  78344. * When defined, the cubemap will switch to local mode
  78345. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  78346. * @example https://www.babylonjs-playground.com/#RNASML
  78347. */
  78348. set: function (value) {
  78349. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  78350. return;
  78351. }
  78352. this._boundingBoxSize = value;
  78353. var scene = this.getScene();
  78354. if (scene) {
  78355. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  78356. }
  78357. },
  78358. enumerable: true,
  78359. configurable: true
  78360. });
  78361. /**
  78362. * Occurs when the file is a preprocessed .babylon.hdr file.
  78363. */
  78364. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  78365. var _this = this;
  78366. var mipLevels = 0;
  78367. var floatArrayView = null;
  78368. var scene = this.getScene();
  78369. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  78370. var mips = new Array();
  78371. if (!floatArrayView) {
  78372. return mips;
  78373. }
  78374. var startIndex = 30;
  78375. for (var level = 0; level < mipLevels; level++) {
  78376. mips.push([]);
  78377. // Fill each pixel of the mip level.
  78378. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  78379. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78380. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  78381. mips[level].push(faceData);
  78382. startIndex += faceSize;
  78383. }
  78384. }
  78385. return mips;
  78386. } : null;
  78387. var callback = function (buffer) {
  78388. var scene = _this.getScene();
  78389. if (!scene) {
  78390. return null;
  78391. }
  78392. // Create Native Array Views
  78393. var intArrayView = new Int32Array(buffer);
  78394. floatArrayView = new Float32Array(buffer);
  78395. // Fill header.
  78396. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  78397. _this._size = intArrayView[1]; // CubeMap max mip face size.
  78398. // Update Texture Information.
  78399. if (!_this._texture) {
  78400. return null;
  78401. }
  78402. _this._texture.updateSize(_this._size, _this._size);
  78403. // Fill polynomial information.
  78404. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  78405. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  78406. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  78407. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  78408. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  78409. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  78410. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  78411. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  78412. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  78413. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  78414. _this.sphericalPolynomial = sphericalPolynomial;
  78415. // Fill pixel data.
  78416. mipLevels = intArrayView[29]; // Number of mip levels.
  78417. var startIndex = 30;
  78418. var data = [];
  78419. var faceSize = Math.pow(_this._size, 2) * 3;
  78420. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78421. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  78422. startIndex += faceSize;
  78423. }
  78424. var results = [];
  78425. var byteArray = null;
  78426. // Push each faces.
  78427. for (var k = 0; k < 6; k++) {
  78428. var dataFace = null;
  78429. // To be deprecated.
  78430. if (version === 1) {
  78431. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  78432. dataFace = data[j];
  78433. }
  78434. // If special cases.
  78435. if (!mipmapGenerator && dataFace) {
  78436. if (!scene.getEngine().getCaps().textureFloat) {
  78437. // 3 channels of 1 bytes per pixel in bytes.
  78438. var byteBuffer = new ArrayBuffer(faceSize);
  78439. byteArray = new Uint8Array(byteBuffer);
  78440. }
  78441. for (var i = 0; i < _this._size * _this._size; i++) {
  78442. // Put in gamma space if requested.
  78443. if (_this._useInGammaSpace) {
  78444. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78445. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78446. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78447. }
  78448. // Convert to int texture for fallback.
  78449. if (byteArray) {
  78450. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78451. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78452. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78453. // May use luminance instead if the result is not accurate.
  78454. var max = Math.max(Math.max(r, g), b);
  78455. if (max > 255) {
  78456. var scale = 255 / max;
  78457. r *= scale;
  78458. g *= scale;
  78459. b *= scale;
  78460. }
  78461. byteArray[(i * 3) + 0] = r;
  78462. byteArray[(i * 3) + 1] = g;
  78463. byteArray[(i * 3) + 2] = b;
  78464. }
  78465. }
  78466. }
  78467. // Fill the array accordingly.
  78468. if (byteArray) {
  78469. results.push(byteArray);
  78470. }
  78471. else {
  78472. results.push(dataFace);
  78473. }
  78474. }
  78475. return results;
  78476. };
  78477. if (scene) {
  78478. 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, mipmapGenerator, this._onLoad, this._onError);
  78479. }
  78480. };
  78481. /**
  78482. * Occurs when the file is raw .hdr file.
  78483. */
  78484. HDRCubeTexture.prototype.loadHDRTexture = function () {
  78485. var _this = this;
  78486. var callback = function (buffer) {
  78487. var scene = _this.getScene();
  78488. if (!scene) {
  78489. return null;
  78490. }
  78491. // Extract the raw linear data.
  78492. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  78493. // Generate harmonics if needed.
  78494. if (_this._generateHarmonics) {
  78495. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  78496. _this.sphericalPolynomial = sphericalPolynomial;
  78497. }
  78498. var results = [];
  78499. var byteArray = null;
  78500. // Push each faces.
  78501. for (var j = 0; j < 6; j++) {
  78502. // Create uintarray fallback.
  78503. if (!scene.getEngine().getCaps().textureFloat) {
  78504. // 3 channels of 1 bytes per pixel in bytes.
  78505. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  78506. byteArray = new Uint8Array(byteBuffer);
  78507. }
  78508. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  78509. // If special cases.
  78510. if (_this._useInGammaSpace || byteArray) {
  78511. for (var i = 0; i < _this._size * _this._size; i++) {
  78512. // Put in gamma space if requested.
  78513. if (_this._useInGammaSpace) {
  78514. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  78515. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  78516. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  78517. }
  78518. // Convert to int texture for fallback.
  78519. if (byteArray) {
  78520. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  78521. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  78522. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  78523. // May use luminance instead if the result is not accurate.
  78524. var max = Math.max(Math.max(r, g), b);
  78525. if (max > 255) {
  78526. var scale = 255 / max;
  78527. r *= scale;
  78528. g *= scale;
  78529. b *= scale;
  78530. }
  78531. byteArray[(i * 3) + 0] = r;
  78532. byteArray[(i * 3) + 1] = g;
  78533. byteArray[(i * 3) + 2] = b;
  78534. }
  78535. }
  78536. }
  78537. if (byteArray) {
  78538. results.push(byteArray);
  78539. }
  78540. else {
  78541. results.push(dataFace);
  78542. }
  78543. }
  78544. return results;
  78545. };
  78546. var mipmapGenerator = null;
  78547. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  78548. // if (!this._noMipmap &&
  78549. // this._usePMREMGenerator) {
  78550. // mipmapGenerator = (data: ArrayBufferView[]) => {
  78551. // // Custom setup of the generator matching with the PBR shader values.
  78552. // var generator = new BABYLON.PMREMGenerator(data,
  78553. // this._size,
  78554. // this._size,
  78555. // 0,
  78556. // 3,
  78557. // this.getScene().getEngine().getCaps().textureFloat,
  78558. // 2048,
  78559. // 0.25,
  78560. // false,
  78561. // true);
  78562. // return generator.filterCubeMap();
  78563. // };
  78564. // }
  78565. var scene = this.getScene();
  78566. if (scene) {
  78567. 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, mipmapGenerator, this._onLoad, this._onError);
  78568. }
  78569. };
  78570. /**
  78571. * Starts the loading process of the texture.
  78572. */
  78573. HDRCubeTexture.prototype.loadTexture = function () {
  78574. if (this._isBABYLONPreprocessed) {
  78575. this.loadBabylonTexture();
  78576. }
  78577. else {
  78578. this.loadHDRTexture();
  78579. }
  78580. };
  78581. HDRCubeTexture.prototype.clone = function () {
  78582. var scene = this.getScene();
  78583. if (!scene) {
  78584. return this;
  78585. }
  78586. var size = (this._isBABYLONPreprocessed ? null : this._size);
  78587. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  78588. // Base texture
  78589. newTexture.level = this.level;
  78590. newTexture.wrapU = this.wrapU;
  78591. newTexture.wrapV = this.wrapV;
  78592. newTexture.coordinatesIndex = this.coordinatesIndex;
  78593. newTexture.coordinatesMode = this.coordinatesMode;
  78594. return newTexture;
  78595. };
  78596. // Methods
  78597. HDRCubeTexture.prototype.delayLoad = function () {
  78598. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78599. return;
  78600. }
  78601. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78602. this._texture = this._getFromCache(this.url, this._noMipmap);
  78603. if (!this._texture) {
  78604. this.loadTexture();
  78605. }
  78606. };
  78607. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  78608. return this._textureMatrix;
  78609. };
  78610. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  78611. this._textureMatrix = value;
  78612. };
  78613. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78614. var texture = null;
  78615. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78616. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  78617. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  78618. texture.name = parsedTexture.name;
  78619. texture.hasAlpha = parsedTexture.hasAlpha;
  78620. texture.level = parsedTexture.level;
  78621. texture.coordinatesMode = parsedTexture.coordinatesMode;
  78622. texture.isBlocking = parsedTexture.isBlocking;
  78623. }
  78624. if (texture) {
  78625. if (parsedTexture.boundingBoxPosition) {
  78626. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  78627. }
  78628. if (parsedTexture.boundingBoxSize) {
  78629. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  78630. }
  78631. if (parsedTexture.rotationY) {
  78632. texture.rotationY = parsedTexture.rotationY;
  78633. }
  78634. }
  78635. return texture;
  78636. };
  78637. HDRCubeTexture.prototype.serialize = function () {
  78638. if (!this.name) {
  78639. return null;
  78640. }
  78641. var serializationObject = {};
  78642. serializationObject.name = this.name;
  78643. serializationObject.hasAlpha = this.hasAlpha;
  78644. serializationObject.isCube = true;
  78645. serializationObject.level = this.level;
  78646. serializationObject.size = this._size;
  78647. serializationObject.coordinatesMode = this.coordinatesMode;
  78648. serializationObject.useInGammaSpace = this._useInGammaSpace;
  78649. serializationObject.generateHarmonics = this._generateHarmonics;
  78650. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  78651. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  78652. serializationObject.customType = "BABYLON.HDRCubeTexture";
  78653. serializationObject.noMipmap = this._noMipmap;
  78654. serializationObject.isBlocking = this._isBlocking;
  78655. serializationObject.rotationY = this._rotationY;
  78656. return serializationObject;
  78657. };
  78658. /**
  78659. * Saves as a file the data contained in the texture in a binary format.
  78660. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78661. * as the spherical used in the lighting.
  78662. * @param url The HDR file url.
  78663. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78664. * @param onError Method called if any error happens during download.
  78665. * @return The packed binary data.
  78666. */
  78667. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  78668. if (onError === void 0) { onError = null; }
  78669. var callback = function (buffer) {
  78670. var data = new Blob([buffer], { type: 'application/octet-stream' });
  78671. // Returns a URL you can use as a href.
  78672. var objUrl = window.URL.createObjectURL(data);
  78673. // Simulates a link to it and click to dowload.
  78674. var a = document.createElement("a");
  78675. document.body.appendChild(a);
  78676. a.style.display = "none";
  78677. a.href = objUrl;
  78678. a.download = "envmap.babylon.hdr";
  78679. a.click();
  78680. };
  78681. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  78682. };
  78683. /**
  78684. * Serializes the data contained in the texture in a binary format.
  78685. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  78686. * as the spherical used in the lighting.
  78687. * @param url The HDR file url.
  78688. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  78689. * @param onError Method called if any error happens during download.
  78690. * @return The packed binary data.
  78691. */
  78692. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  78693. if (onError === void 0) { onError = null; }
  78694. // Needs the url tho create the texture.
  78695. if (!url) {
  78696. return;
  78697. }
  78698. // Check Power of two size.
  78699. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  78700. return;
  78701. }
  78702. // Coming Back in 3.x.
  78703. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  78704. };
  78705. HDRCubeTexture._facesMapping = [
  78706. "right",
  78707. "left",
  78708. "up",
  78709. "down",
  78710. "front",
  78711. "back"
  78712. ];
  78713. return HDRCubeTexture;
  78714. }(BABYLON.BaseTexture));
  78715. BABYLON.HDRCubeTexture = HDRCubeTexture;
  78716. })(BABYLON || (BABYLON = {}));
  78717. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  78718. "use strict";
  78719. var BABYLON;
  78720. (function (BABYLON) {
  78721. var IndexedVector2 = /** @class */ (function (_super) {
  78722. __extends(IndexedVector2, _super);
  78723. function IndexedVector2(original, index) {
  78724. var _this = _super.call(this, original.x, original.y) || this;
  78725. _this.index = index;
  78726. return _this;
  78727. }
  78728. return IndexedVector2;
  78729. }(BABYLON.Vector2));
  78730. var PolygonPoints = /** @class */ (function () {
  78731. function PolygonPoints() {
  78732. this.elements = new Array();
  78733. }
  78734. PolygonPoints.prototype.add = function (originalPoints) {
  78735. var _this = this;
  78736. var result = new Array();
  78737. originalPoints.forEach(function (point) {
  78738. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  78739. var newPoint = new IndexedVector2(point, _this.elements.length);
  78740. result.push(newPoint);
  78741. _this.elements.push(newPoint);
  78742. }
  78743. });
  78744. return result;
  78745. };
  78746. PolygonPoints.prototype.computeBounds = function () {
  78747. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  78748. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  78749. this.elements.forEach(function (point) {
  78750. // x
  78751. if (point.x < lmin.x) {
  78752. lmin.x = point.x;
  78753. }
  78754. else if (point.x > lmax.x) {
  78755. lmax.x = point.x;
  78756. }
  78757. // y
  78758. if (point.y < lmin.y) {
  78759. lmin.y = point.y;
  78760. }
  78761. else if (point.y > lmax.y) {
  78762. lmax.y = point.y;
  78763. }
  78764. });
  78765. return {
  78766. min: lmin,
  78767. max: lmax,
  78768. width: lmax.x - lmin.x,
  78769. height: lmax.y - lmin.y
  78770. };
  78771. };
  78772. return PolygonPoints;
  78773. }());
  78774. var Polygon = /** @class */ (function () {
  78775. function Polygon() {
  78776. }
  78777. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  78778. return [
  78779. new BABYLON.Vector2(xmin, ymin),
  78780. new BABYLON.Vector2(xmax, ymin),
  78781. new BABYLON.Vector2(xmax, ymax),
  78782. new BABYLON.Vector2(xmin, ymax)
  78783. ];
  78784. };
  78785. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  78786. if (cx === void 0) { cx = 0; }
  78787. if (cy === void 0) { cy = 0; }
  78788. if (numberOfSides === void 0) { numberOfSides = 32; }
  78789. var result = new Array();
  78790. var angle = 0;
  78791. var increment = (Math.PI * 2) / numberOfSides;
  78792. for (var i = 0; i < numberOfSides; i++) {
  78793. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  78794. angle -= increment;
  78795. }
  78796. return result;
  78797. };
  78798. Polygon.Parse = function (input) {
  78799. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  78800. var i, result = [];
  78801. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  78802. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  78803. }
  78804. return result;
  78805. };
  78806. Polygon.StartingAt = function (x, y) {
  78807. return BABYLON.Path2.StartingAt(x, y);
  78808. };
  78809. return Polygon;
  78810. }());
  78811. BABYLON.Polygon = Polygon;
  78812. var PolygonMeshBuilder = /** @class */ (function () {
  78813. function PolygonMeshBuilder(name, contours, scene) {
  78814. this._points = new PolygonPoints();
  78815. this._outlinepoints = new PolygonPoints();
  78816. this._holes = new Array();
  78817. this._epoints = new Array();
  78818. this._eholes = new Array();
  78819. this._name = name;
  78820. this._scene = scene;
  78821. var points;
  78822. if (contours instanceof BABYLON.Path2) {
  78823. points = contours.getPoints();
  78824. }
  78825. else {
  78826. points = contours;
  78827. }
  78828. this._addToepoint(points);
  78829. this._points.add(points);
  78830. this._outlinepoints.add(points);
  78831. if (typeof earcut === 'undefined') {
  78832. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  78833. }
  78834. }
  78835. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  78836. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  78837. var p = points_1[_i];
  78838. this._epoints.push(p.x, p.y);
  78839. }
  78840. };
  78841. PolygonMeshBuilder.prototype.addHole = function (hole) {
  78842. this._points.add(hole);
  78843. var holepoints = new PolygonPoints();
  78844. holepoints.add(hole);
  78845. this._holes.push(holepoints);
  78846. this._eholes.push(this._epoints.length / 2);
  78847. this._addToepoint(hole);
  78848. return this;
  78849. };
  78850. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  78851. var _this = this;
  78852. if (updatable === void 0) { updatable = false; }
  78853. if (depth === void 0) { depth = 0; }
  78854. var result = new BABYLON.Mesh(this._name, this._scene);
  78855. var normals = new Array();
  78856. var positions = new Array();
  78857. var uvs = new Array();
  78858. var bounds = this._points.computeBounds();
  78859. this._points.elements.forEach(function (p) {
  78860. normals.push(0, 1.0, 0);
  78861. positions.push(p.x, 0, p.y);
  78862. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  78863. });
  78864. var indices = new Array();
  78865. var res = earcut(this._epoints, this._eholes, 2);
  78866. for (var i = 0; i < res.length; i++) {
  78867. indices.push(res[i]);
  78868. }
  78869. if (depth > 0) {
  78870. var positionscount = (positions.length / 3); //get the current pointcount
  78871. this._points.elements.forEach(function (p) {
  78872. normals.push(0, -1.0, 0);
  78873. positions.push(p.x, -depth, p.y);
  78874. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  78875. });
  78876. var totalCount = indices.length;
  78877. for (var i = 0; i < totalCount; i += 3) {
  78878. var i0 = indices[i + 0];
  78879. var i1 = indices[i + 1];
  78880. var i2 = indices[i + 2];
  78881. indices.push(i2 + positionscount);
  78882. indices.push(i1 + positionscount);
  78883. indices.push(i0 + positionscount);
  78884. }
  78885. //Add the sides
  78886. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  78887. this._holes.forEach(function (hole) {
  78888. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  78889. });
  78890. }
  78891. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  78892. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  78893. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  78894. result.setIndices(indices);
  78895. return result;
  78896. };
  78897. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  78898. var StartIndex = positions.length / 3;
  78899. var ulength = 0;
  78900. for (var i = 0; i < points.elements.length; i++) {
  78901. var p = points.elements[i];
  78902. var p1;
  78903. if ((i + 1) > points.elements.length - 1) {
  78904. p1 = points.elements[0];
  78905. }
  78906. else {
  78907. p1 = points.elements[i + 1];
  78908. }
  78909. positions.push(p.x, 0, p.y);
  78910. positions.push(p.x, -depth, p.y);
  78911. positions.push(p1.x, 0, p1.y);
  78912. positions.push(p1.x, -depth, p1.y);
  78913. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  78914. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  78915. var v3 = v2.subtract(v1);
  78916. var v4 = new BABYLON.Vector3(0, 1, 0);
  78917. var vn = BABYLON.Vector3.Cross(v3, v4);
  78918. vn = vn.normalize();
  78919. uvs.push(ulength / bounds.width, 0);
  78920. uvs.push(ulength / bounds.width, 1);
  78921. ulength += v3.length();
  78922. uvs.push((ulength / bounds.width), 0);
  78923. uvs.push((ulength / bounds.width), 1);
  78924. if (!flip) {
  78925. normals.push(-vn.x, -vn.y, -vn.z);
  78926. normals.push(-vn.x, -vn.y, -vn.z);
  78927. normals.push(-vn.x, -vn.y, -vn.z);
  78928. normals.push(-vn.x, -vn.y, -vn.z);
  78929. indices.push(StartIndex);
  78930. indices.push(StartIndex + 1);
  78931. indices.push(StartIndex + 2);
  78932. indices.push(StartIndex + 1);
  78933. indices.push(StartIndex + 3);
  78934. indices.push(StartIndex + 2);
  78935. }
  78936. else {
  78937. normals.push(vn.x, vn.y, vn.z);
  78938. normals.push(vn.x, vn.y, vn.z);
  78939. normals.push(vn.x, vn.y, vn.z);
  78940. normals.push(vn.x, vn.y, vn.z);
  78941. indices.push(StartIndex);
  78942. indices.push(StartIndex + 2);
  78943. indices.push(StartIndex + 1);
  78944. indices.push(StartIndex + 1);
  78945. indices.push(StartIndex + 2);
  78946. indices.push(StartIndex + 3);
  78947. }
  78948. StartIndex += 4;
  78949. }
  78950. ;
  78951. };
  78952. return PolygonMeshBuilder;
  78953. }());
  78954. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  78955. })(BABYLON || (BABYLON = {}));
  78956. //# sourceMappingURL=babylon.polygonMesh.js.map
  78957. "use strict";
  78958. var BABYLON;
  78959. (function (BABYLON) {
  78960. // Unique ID when we import meshes from Babylon to CSG
  78961. var currentCSGMeshId = 0;
  78962. // # class Vertex
  78963. // Represents a vertex of a polygon. Use your own vertex class instead of this
  78964. // one to provide additional features like texture coordinates and vertex
  78965. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  78966. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  78967. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  78968. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  78969. // is not used anywhere else.
  78970. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  78971. var Vertex = /** @class */ (function () {
  78972. function Vertex(pos, normal, uv) {
  78973. this.pos = pos;
  78974. this.normal = normal;
  78975. this.uv = uv;
  78976. }
  78977. Vertex.prototype.clone = function () {
  78978. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  78979. };
  78980. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  78981. // orientation of a polygon is flipped.
  78982. Vertex.prototype.flip = function () {
  78983. this.normal = this.normal.scale(-1);
  78984. };
  78985. // Create a new vertex between this vertex and `other` by linearly
  78986. // interpolating all properties using a parameter of `t`. Subclasses should
  78987. // override this to interpolate additional properties.
  78988. Vertex.prototype.interpolate = function (other, t) {
  78989. 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));
  78990. };
  78991. return Vertex;
  78992. }());
  78993. // # class Plane
  78994. // Represents a plane in 3D space.
  78995. var Plane = /** @class */ (function () {
  78996. function Plane(normal, w) {
  78997. this.normal = normal;
  78998. this.w = w;
  78999. }
  79000. Plane.FromPoints = function (a, b, c) {
  79001. var v0 = c.subtract(a);
  79002. var v1 = b.subtract(a);
  79003. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  79004. return null;
  79005. }
  79006. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  79007. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  79008. };
  79009. Plane.prototype.clone = function () {
  79010. return new Plane(this.normal.clone(), this.w);
  79011. };
  79012. Plane.prototype.flip = function () {
  79013. this.normal.scaleInPlace(-1);
  79014. this.w = -this.w;
  79015. };
  79016. // Split `polygon` by this plane if needed, then put the polygon or polygon
  79017. // fragments in the appropriate lists. Coplanar polygons go into either
  79018. // `coplanarFront` or `coplanarBack` depending on their orientation with
  79019. // respect to this plane. Polygons in front or in back of this plane go into
  79020. // either `front` or `back`.
  79021. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  79022. var COPLANAR = 0;
  79023. var FRONT = 1;
  79024. var BACK = 2;
  79025. var SPANNING = 3;
  79026. // Classify each point as well as the entire polygon into one of the above
  79027. // four classes.
  79028. var polygonType = 0;
  79029. var types = [];
  79030. var i;
  79031. var t;
  79032. for (i = 0; i < polygon.vertices.length; i++) {
  79033. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  79034. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  79035. polygonType |= type;
  79036. types.push(type);
  79037. }
  79038. // Put the polygon in the correct list, splitting it when necessary.
  79039. switch (polygonType) {
  79040. case COPLANAR:
  79041. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  79042. break;
  79043. case FRONT:
  79044. front.push(polygon);
  79045. break;
  79046. case BACK:
  79047. back.push(polygon);
  79048. break;
  79049. case SPANNING:
  79050. var f = [], b = [];
  79051. for (i = 0; i < polygon.vertices.length; i++) {
  79052. var j = (i + 1) % polygon.vertices.length;
  79053. var ti = types[i], tj = types[j];
  79054. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  79055. if (ti !== BACK)
  79056. f.push(vi);
  79057. if (ti !== FRONT)
  79058. b.push(ti !== BACK ? vi.clone() : vi);
  79059. if ((ti | tj) === SPANNING) {
  79060. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  79061. var v = vi.interpolate(vj, t);
  79062. f.push(v);
  79063. b.push(v.clone());
  79064. }
  79065. }
  79066. var poly;
  79067. if (f.length >= 3) {
  79068. poly = new Polygon(f, polygon.shared);
  79069. if (poly.plane)
  79070. front.push(poly);
  79071. }
  79072. if (b.length >= 3) {
  79073. poly = new Polygon(b, polygon.shared);
  79074. if (poly.plane)
  79075. back.push(poly);
  79076. }
  79077. break;
  79078. }
  79079. };
  79080. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  79081. // point is on the plane.
  79082. Plane.EPSILON = 1e-5;
  79083. return Plane;
  79084. }());
  79085. // # class Polygon
  79086. // Represents a convex polygon. The vertices used to initialize a polygon must
  79087. // be coplanar and form a convex loop.
  79088. //
  79089. // Each convex polygon has a `shared` property, which is shared between all
  79090. // polygons that are clones of each other or were split from the same polygon.
  79091. // This can be used to define per-polygon properties (such as surface color).
  79092. var Polygon = /** @class */ (function () {
  79093. function Polygon(vertices, shared) {
  79094. this.vertices = vertices;
  79095. this.shared = shared;
  79096. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  79097. }
  79098. Polygon.prototype.clone = function () {
  79099. var vertices = this.vertices.map(function (v) { return v.clone(); });
  79100. return new Polygon(vertices, this.shared);
  79101. };
  79102. Polygon.prototype.flip = function () {
  79103. this.vertices.reverse().map(function (v) { v.flip(); });
  79104. this.plane.flip();
  79105. };
  79106. return Polygon;
  79107. }());
  79108. // # class Node
  79109. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  79110. // by picking a polygon to split along. That polygon (and all other coplanar
  79111. // polygons) are added directly to that node and the other polygons are added to
  79112. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  79113. // no distinction between internal and leaf nodes.
  79114. var Node = /** @class */ (function () {
  79115. function Node(polygons) {
  79116. this.plane = null;
  79117. this.front = null;
  79118. this.back = null;
  79119. this.polygons = new Array();
  79120. if (polygons) {
  79121. this.build(polygons);
  79122. }
  79123. }
  79124. Node.prototype.clone = function () {
  79125. var node = new Node();
  79126. node.plane = this.plane && this.plane.clone();
  79127. node.front = this.front && this.front.clone();
  79128. node.back = this.back && this.back.clone();
  79129. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  79130. return node;
  79131. };
  79132. // Convert solid space to empty space and empty space to solid space.
  79133. Node.prototype.invert = function () {
  79134. for (var i = 0; i < this.polygons.length; i++) {
  79135. this.polygons[i].flip();
  79136. }
  79137. if (this.plane) {
  79138. this.plane.flip();
  79139. }
  79140. if (this.front) {
  79141. this.front.invert();
  79142. }
  79143. if (this.back) {
  79144. this.back.invert();
  79145. }
  79146. var temp = this.front;
  79147. this.front = this.back;
  79148. this.back = temp;
  79149. };
  79150. // Recursively remove all polygons in `polygons` that are inside this BSP
  79151. // tree.
  79152. Node.prototype.clipPolygons = function (polygons) {
  79153. if (!this.plane)
  79154. return polygons.slice();
  79155. var front = new Array(), back = new Array();
  79156. for (var i = 0; i < polygons.length; i++) {
  79157. this.plane.splitPolygon(polygons[i], front, back, front, back);
  79158. }
  79159. if (this.front) {
  79160. front = this.front.clipPolygons(front);
  79161. }
  79162. if (this.back) {
  79163. back = this.back.clipPolygons(back);
  79164. }
  79165. else {
  79166. back = [];
  79167. }
  79168. return front.concat(back);
  79169. };
  79170. // Remove all polygons in this BSP tree that are inside the other BSP tree
  79171. // `bsp`.
  79172. Node.prototype.clipTo = function (bsp) {
  79173. this.polygons = bsp.clipPolygons(this.polygons);
  79174. if (this.front)
  79175. this.front.clipTo(bsp);
  79176. if (this.back)
  79177. this.back.clipTo(bsp);
  79178. };
  79179. // Return a list of all polygons in this BSP tree.
  79180. Node.prototype.allPolygons = function () {
  79181. var polygons = this.polygons.slice();
  79182. if (this.front)
  79183. polygons = polygons.concat(this.front.allPolygons());
  79184. if (this.back)
  79185. polygons = polygons.concat(this.back.allPolygons());
  79186. return polygons;
  79187. };
  79188. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  79189. // new polygons are filtered down to the bottom of the tree and become new
  79190. // nodes there. Each set of polygons is partitioned using the first polygon
  79191. // (no heuristic is used to pick a good split).
  79192. Node.prototype.build = function (polygons) {
  79193. if (!polygons.length)
  79194. return;
  79195. if (!this.plane)
  79196. this.plane = polygons[0].plane.clone();
  79197. var front = new Array(), back = new Array();
  79198. for (var i = 0; i < polygons.length; i++) {
  79199. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  79200. }
  79201. if (front.length) {
  79202. if (!this.front)
  79203. this.front = new Node();
  79204. this.front.build(front);
  79205. }
  79206. if (back.length) {
  79207. if (!this.back)
  79208. this.back = new Node();
  79209. this.back.build(back);
  79210. }
  79211. };
  79212. return Node;
  79213. }());
  79214. var CSG = /** @class */ (function () {
  79215. function CSG() {
  79216. this.polygons = new Array();
  79217. }
  79218. // Convert BABYLON.Mesh to BABYLON.CSG
  79219. CSG.FromMesh = function (mesh) {
  79220. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  79221. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  79222. if (mesh instanceof BABYLON.Mesh) {
  79223. mesh.computeWorldMatrix(true);
  79224. matrix = mesh.getWorldMatrix();
  79225. meshPosition = mesh.position.clone();
  79226. meshRotation = mesh.rotation.clone();
  79227. if (mesh.rotationQuaternion) {
  79228. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  79229. }
  79230. meshScaling = mesh.scaling.clone();
  79231. }
  79232. else {
  79233. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  79234. }
  79235. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  79236. var subMeshes = mesh.subMeshes;
  79237. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  79238. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  79239. vertices = [];
  79240. for (var j = 0; j < 3; j++) {
  79241. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  79242. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  79243. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  79244. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  79245. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  79246. vertex = new Vertex(position, normal, uv);
  79247. vertices.push(vertex);
  79248. }
  79249. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  79250. // To handle the case of degenerated triangle
  79251. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  79252. if (polygon.plane)
  79253. polygons.push(polygon);
  79254. }
  79255. }
  79256. var csg = CSG.FromPolygons(polygons);
  79257. csg.matrix = matrix;
  79258. csg.position = meshPosition;
  79259. csg.rotation = meshRotation;
  79260. csg.scaling = meshScaling;
  79261. csg.rotationQuaternion = meshRotationQuaternion;
  79262. currentCSGMeshId++;
  79263. return csg;
  79264. };
  79265. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  79266. CSG.FromPolygons = function (polygons) {
  79267. var csg = new CSG();
  79268. csg.polygons = polygons;
  79269. return csg;
  79270. };
  79271. CSG.prototype.clone = function () {
  79272. var csg = new CSG();
  79273. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  79274. csg.copyTransformAttributes(this);
  79275. return csg;
  79276. };
  79277. CSG.prototype.union = function (csg) {
  79278. var a = new Node(this.clone().polygons);
  79279. var b = new Node(csg.clone().polygons);
  79280. a.clipTo(b);
  79281. b.clipTo(a);
  79282. b.invert();
  79283. b.clipTo(a);
  79284. b.invert();
  79285. a.build(b.allPolygons());
  79286. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79287. };
  79288. CSG.prototype.unionInPlace = function (csg) {
  79289. var a = new Node(this.polygons);
  79290. var b = new Node(csg.polygons);
  79291. a.clipTo(b);
  79292. b.clipTo(a);
  79293. b.invert();
  79294. b.clipTo(a);
  79295. b.invert();
  79296. a.build(b.allPolygons());
  79297. this.polygons = a.allPolygons();
  79298. };
  79299. CSG.prototype.subtract = function (csg) {
  79300. var a = new Node(this.clone().polygons);
  79301. var b = new Node(csg.clone().polygons);
  79302. a.invert();
  79303. a.clipTo(b);
  79304. b.clipTo(a);
  79305. b.invert();
  79306. b.clipTo(a);
  79307. b.invert();
  79308. a.build(b.allPolygons());
  79309. a.invert();
  79310. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79311. };
  79312. CSG.prototype.subtractInPlace = function (csg) {
  79313. var a = new Node(this.polygons);
  79314. var b = new Node(csg.polygons);
  79315. a.invert();
  79316. a.clipTo(b);
  79317. b.clipTo(a);
  79318. b.invert();
  79319. b.clipTo(a);
  79320. b.invert();
  79321. a.build(b.allPolygons());
  79322. a.invert();
  79323. this.polygons = a.allPolygons();
  79324. };
  79325. CSG.prototype.intersect = function (csg) {
  79326. var a = new Node(this.clone().polygons);
  79327. var b = new Node(csg.clone().polygons);
  79328. a.invert();
  79329. b.clipTo(a);
  79330. b.invert();
  79331. a.clipTo(b);
  79332. b.clipTo(a);
  79333. a.build(b.allPolygons());
  79334. a.invert();
  79335. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  79336. };
  79337. CSG.prototype.intersectInPlace = function (csg) {
  79338. var a = new Node(this.polygons);
  79339. var b = new Node(csg.polygons);
  79340. a.invert();
  79341. b.clipTo(a);
  79342. b.invert();
  79343. a.clipTo(b);
  79344. b.clipTo(a);
  79345. a.build(b.allPolygons());
  79346. a.invert();
  79347. this.polygons = a.allPolygons();
  79348. };
  79349. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  79350. // not modified.
  79351. CSG.prototype.inverse = function () {
  79352. var csg = this.clone();
  79353. csg.inverseInPlace();
  79354. return csg;
  79355. };
  79356. CSG.prototype.inverseInPlace = function () {
  79357. this.polygons.map(function (p) { p.flip(); });
  79358. };
  79359. // This is used to keep meshes transformations so they can be restored
  79360. // when we build back a Babylon Mesh
  79361. // NB : All CSG operations are performed in world coordinates
  79362. CSG.prototype.copyTransformAttributes = function (csg) {
  79363. this.matrix = csg.matrix;
  79364. this.position = csg.position;
  79365. this.rotation = csg.rotation;
  79366. this.scaling = csg.scaling;
  79367. this.rotationQuaternion = csg.rotationQuaternion;
  79368. return this;
  79369. };
  79370. // Build Raw mesh from CSG
  79371. // Coordinates here are in world space
  79372. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  79373. var matrix = this.matrix.clone();
  79374. matrix.invert();
  79375. 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;
  79376. if (keepSubMeshes) {
  79377. // Sort Polygons, since subMeshes are indices range
  79378. polygons.sort(function (a, b) {
  79379. if (a.shared.meshId === b.shared.meshId) {
  79380. return a.shared.subMeshId - b.shared.subMeshId;
  79381. }
  79382. else {
  79383. return a.shared.meshId - b.shared.meshId;
  79384. }
  79385. });
  79386. }
  79387. for (var i = 0, il = polygons.length; i < il; i++) {
  79388. polygon = polygons[i];
  79389. // Building SubMeshes
  79390. if (!subMesh_dict[polygon.shared.meshId]) {
  79391. subMesh_dict[polygon.shared.meshId] = {};
  79392. }
  79393. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  79394. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  79395. indexStart: +Infinity,
  79396. indexEnd: -Infinity,
  79397. materialIndex: polygon.shared.materialIndex
  79398. };
  79399. }
  79400. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  79401. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  79402. polygonIndices[0] = 0;
  79403. polygonIndices[1] = j - 1;
  79404. polygonIndices[2] = j;
  79405. for (var k = 0; k < 3; k++) {
  79406. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  79407. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  79408. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  79409. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  79410. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  79411. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  79412. // Check if 2 points can be merged
  79413. if (!(typeof vertex_idx !== 'undefined' &&
  79414. normals[vertex_idx * 3] === localNormal.x &&
  79415. normals[vertex_idx * 3 + 1] === localNormal.y &&
  79416. normals[vertex_idx * 3 + 2] === localNormal.z &&
  79417. uvs[vertex_idx * 2] === uv.x &&
  79418. uvs[vertex_idx * 2 + 1] === uv.y)) {
  79419. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  79420. uvs.push(uv.x, uv.y);
  79421. normals.push(normal.x, normal.y, normal.z);
  79422. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  79423. }
  79424. indices.push(vertex_idx);
  79425. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  79426. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  79427. currentIndex++;
  79428. }
  79429. }
  79430. }
  79431. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  79432. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  79433. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  79434. mesh.setIndices(indices, null);
  79435. if (keepSubMeshes) {
  79436. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  79437. var materialIndexOffset = 0, materialMaxIndex;
  79438. mesh.subMeshes = new Array();
  79439. for (var m in subMesh_dict) {
  79440. materialMaxIndex = -1;
  79441. for (var sm in subMesh_dict[m]) {
  79442. subMesh_obj = subMesh_dict[m][sm];
  79443. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  79444. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  79445. }
  79446. materialIndexOffset += ++materialMaxIndex;
  79447. }
  79448. }
  79449. return mesh;
  79450. };
  79451. // Build Mesh from CSG taking material and transforms into account
  79452. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  79453. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  79454. mesh.material = material;
  79455. mesh.position.copyFrom(this.position);
  79456. mesh.rotation.copyFrom(this.rotation);
  79457. if (this.rotationQuaternion) {
  79458. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  79459. }
  79460. mesh.scaling.copyFrom(this.scaling);
  79461. mesh.computeWorldMatrix(true);
  79462. return mesh;
  79463. };
  79464. return CSG;
  79465. }());
  79466. BABYLON.CSG = CSG;
  79467. })(BABYLON || (BABYLON = {}));
  79468. //# sourceMappingURL=babylon.csg.js.map
  79469. "use strict";
  79470. var BABYLON;
  79471. (function (BABYLON) {
  79472. var LensFlare = /** @class */ (function () {
  79473. function LensFlare(size, position, color, imgUrl, system) {
  79474. this.size = size;
  79475. this.position = position;
  79476. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  79477. this.color = color || new BABYLON.Color3(1, 1, 1);
  79478. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  79479. this._system = system;
  79480. system.lensFlares.push(this);
  79481. }
  79482. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  79483. return new LensFlare(size, position, color, imgUrl, system);
  79484. };
  79485. LensFlare.prototype.dispose = function () {
  79486. if (this.texture) {
  79487. this.texture.dispose();
  79488. }
  79489. // Remove from scene
  79490. var index = this._system.lensFlares.indexOf(this);
  79491. this._system.lensFlares.splice(index, 1);
  79492. };
  79493. ;
  79494. return LensFlare;
  79495. }());
  79496. BABYLON.LensFlare = LensFlare;
  79497. })(BABYLON || (BABYLON = {}));
  79498. //# sourceMappingURL=babylon.lensFlare.js.map
  79499. "use strict";
  79500. var BABYLON;
  79501. (function (BABYLON) {
  79502. var LensFlareSystem = /** @class */ (function () {
  79503. function LensFlareSystem(name, emitter, scene) {
  79504. this.name = name;
  79505. this.lensFlares = new Array();
  79506. this.borderLimit = 300;
  79507. this.viewportBorder = 0;
  79508. this.layerMask = 0x0FFFFFFF;
  79509. this._vertexBuffers = {};
  79510. this._isEnabled = true;
  79511. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79512. this._emitter = emitter;
  79513. this.id = name;
  79514. scene.lensFlareSystems.push(this);
  79515. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  79516. var engine = scene.getEngine();
  79517. // VBO
  79518. var vertices = [];
  79519. vertices.push(1, 1);
  79520. vertices.push(-1, 1);
  79521. vertices.push(-1, -1);
  79522. vertices.push(1, -1);
  79523. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79524. // Indices
  79525. var indices = [];
  79526. indices.push(0);
  79527. indices.push(1);
  79528. indices.push(2);
  79529. indices.push(0);
  79530. indices.push(2);
  79531. indices.push(3);
  79532. this._indexBuffer = engine.createIndexBuffer(indices);
  79533. // Effects
  79534. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  79535. }
  79536. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  79537. get: function () {
  79538. return this._isEnabled;
  79539. },
  79540. set: function (value) {
  79541. this._isEnabled = value;
  79542. },
  79543. enumerable: true,
  79544. configurable: true
  79545. });
  79546. LensFlareSystem.prototype.getScene = function () {
  79547. return this._scene;
  79548. };
  79549. LensFlareSystem.prototype.getEmitter = function () {
  79550. return this._emitter;
  79551. };
  79552. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  79553. this._emitter = newEmitter;
  79554. };
  79555. LensFlareSystem.prototype.getEmitterPosition = function () {
  79556. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  79557. };
  79558. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  79559. var position = this.getEmitterPosition();
  79560. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  79561. this._positionX = position.x;
  79562. this._positionY = position.y;
  79563. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  79564. if (this.viewportBorder > 0) {
  79565. globalViewport.x -= this.viewportBorder;
  79566. globalViewport.y -= this.viewportBorder;
  79567. globalViewport.width += this.viewportBorder * 2;
  79568. globalViewport.height += this.viewportBorder * 2;
  79569. position.x += this.viewportBorder;
  79570. position.y += this.viewportBorder;
  79571. this._positionX += this.viewportBorder;
  79572. this._positionY += this.viewportBorder;
  79573. }
  79574. if (position.z > 0) {
  79575. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  79576. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  79577. return true;
  79578. }
  79579. return true;
  79580. }
  79581. return false;
  79582. };
  79583. LensFlareSystem.prototype._isVisible = function () {
  79584. if (!this._isEnabled || !this._scene.activeCamera) {
  79585. return false;
  79586. }
  79587. var emitterPosition = this.getEmitterPosition();
  79588. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  79589. var distance = direction.length();
  79590. direction.normalize();
  79591. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  79592. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  79593. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  79594. };
  79595. LensFlareSystem.prototype.render = function () {
  79596. if (!this._effect.isReady() || !this._scene.activeCamera)
  79597. return false;
  79598. var engine = this._scene.getEngine();
  79599. var viewport = this._scene.activeCamera.viewport;
  79600. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  79601. // Position
  79602. if (!this.computeEffectivePosition(globalViewport)) {
  79603. return false;
  79604. }
  79605. // Visibility
  79606. if (!this._isVisible()) {
  79607. return false;
  79608. }
  79609. // Intensity
  79610. var awayX;
  79611. var awayY;
  79612. if (this._positionX < this.borderLimit + globalViewport.x) {
  79613. awayX = this.borderLimit + globalViewport.x - this._positionX;
  79614. }
  79615. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  79616. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  79617. }
  79618. else {
  79619. awayX = 0;
  79620. }
  79621. if (this._positionY < this.borderLimit + globalViewport.y) {
  79622. awayY = this.borderLimit + globalViewport.y - this._positionY;
  79623. }
  79624. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  79625. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  79626. }
  79627. else {
  79628. awayY = 0;
  79629. }
  79630. var away = (awayX > awayY) ? awayX : awayY;
  79631. away -= this.viewportBorder;
  79632. if (away > this.borderLimit) {
  79633. away = this.borderLimit;
  79634. }
  79635. var intensity = 1.0 - (away / this.borderLimit);
  79636. if (intensity < 0) {
  79637. return false;
  79638. }
  79639. if (intensity > 1.0) {
  79640. intensity = 1.0;
  79641. }
  79642. if (this.viewportBorder > 0) {
  79643. globalViewport.x += this.viewportBorder;
  79644. globalViewport.y += this.viewportBorder;
  79645. globalViewport.width -= this.viewportBorder * 2;
  79646. globalViewport.height -= this.viewportBorder * 2;
  79647. this._positionX -= this.viewportBorder;
  79648. this._positionY -= this.viewportBorder;
  79649. }
  79650. // Position
  79651. var centerX = globalViewport.x + globalViewport.width / 2;
  79652. var centerY = globalViewport.y + globalViewport.height / 2;
  79653. var distX = centerX - this._positionX;
  79654. var distY = centerY - this._positionY;
  79655. // Effects
  79656. engine.enableEffect(this._effect);
  79657. engine.setState(false);
  79658. engine.setDepthBuffer(false);
  79659. // VBOs
  79660. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79661. // Flares
  79662. for (var index = 0; index < this.lensFlares.length; index++) {
  79663. var flare = this.lensFlares[index];
  79664. engine.setAlphaMode(flare.alphaMode);
  79665. var x = centerX - (distX * flare.position);
  79666. var y = centerY - (distY * flare.position);
  79667. var cw = flare.size;
  79668. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  79669. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  79670. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  79671. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  79672. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  79673. // Texture
  79674. this._effect.setTexture("textureSampler", flare.texture);
  79675. // Color
  79676. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  79677. // Draw order
  79678. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79679. }
  79680. engine.setDepthBuffer(true);
  79681. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79682. return true;
  79683. };
  79684. LensFlareSystem.prototype.dispose = function () {
  79685. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79686. if (vertexBuffer) {
  79687. vertexBuffer.dispose();
  79688. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79689. }
  79690. if (this._indexBuffer) {
  79691. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79692. this._indexBuffer = null;
  79693. }
  79694. while (this.lensFlares.length) {
  79695. this.lensFlares[0].dispose();
  79696. }
  79697. // Remove from scene
  79698. var index = this._scene.lensFlareSystems.indexOf(this);
  79699. this._scene.lensFlareSystems.splice(index, 1);
  79700. };
  79701. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  79702. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  79703. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  79704. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  79705. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  79706. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  79707. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  79708. var parsedFlare = parsedLensFlareSystem.flares[index];
  79709. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  79710. }
  79711. return lensFlareSystem;
  79712. };
  79713. LensFlareSystem.prototype.serialize = function () {
  79714. var serializationObject = {};
  79715. serializationObject.id = this.id;
  79716. serializationObject.name = this.name;
  79717. serializationObject.emitterId = this.getEmitter().id;
  79718. serializationObject.borderLimit = this.borderLimit;
  79719. serializationObject.flares = [];
  79720. for (var index = 0; index < this.lensFlares.length; index++) {
  79721. var flare = this.lensFlares[index];
  79722. serializationObject.flares.push({
  79723. size: flare.size,
  79724. position: flare.position,
  79725. color: flare.color.asArray(),
  79726. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  79727. });
  79728. }
  79729. return serializationObject;
  79730. };
  79731. return LensFlareSystem;
  79732. }());
  79733. BABYLON.LensFlareSystem = LensFlareSystem;
  79734. })(BABYLON || (BABYLON = {}));
  79735. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  79736. "use strict";
  79737. var BABYLON;
  79738. (function (BABYLON) {
  79739. /**
  79740. * This is a holder class for the physics joint created by the physics plugin.
  79741. * It holds a set of functions to control the underlying joint.
  79742. */
  79743. var PhysicsJoint = /** @class */ (function () {
  79744. function PhysicsJoint(type, jointData) {
  79745. this.type = type;
  79746. this.jointData = jointData;
  79747. jointData.nativeParams = jointData.nativeParams || {};
  79748. }
  79749. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  79750. get: function () {
  79751. return this._physicsJoint;
  79752. },
  79753. set: function (newJoint) {
  79754. if (this._physicsJoint) {
  79755. //remove from the wolrd
  79756. }
  79757. this._physicsJoint = newJoint;
  79758. },
  79759. enumerable: true,
  79760. configurable: true
  79761. });
  79762. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  79763. set: function (physicsPlugin) {
  79764. this._physicsPlugin = physicsPlugin;
  79765. },
  79766. enumerable: true,
  79767. configurable: true
  79768. });
  79769. /**
  79770. * Execute a function that is physics-plugin specific.
  79771. * @param {Function} func the function that will be executed.
  79772. * It accepts two parameters: the physics world and the physics joint.
  79773. */
  79774. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  79775. func(this._physicsPlugin.world, this._physicsJoint);
  79776. };
  79777. //TODO check if the native joints are the same
  79778. //Joint Types
  79779. PhysicsJoint.DistanceJoint = 0;
  79780. PhysicsJoint.HingeJoint = 1;
  79781. PhysicsJoint.BallAndSocketJoint = 2;
  79782. PhysicsJoint.WheelJoint = 3;
  79783. PhysicsJoint.SliderJoint = 4;
  79784. //OIMO
  79785. PhysicsJoint.PrismaticJoint = 5;
  79786. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  79787. PhysicsJoint.UniversalJoint = 6;
  79788. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  79789. //Cannon
  79790. //Similar to a Ball-Joint. Different in params
  79791. PhysicsJoint.PointToPointJoint = 8;
  79792. //Cannon only at the moment
  79793. PhysicsJoint.SpringJoint = 9;
  79794. PhysicsJoint.LockJoint = 10;
  79795. return PhysicsJoint;
  79796. }());
  79797. BABYLON.PhysicsJoint = PhysicsJoint;
  79798. /**
  79799. * A class representing a physics distance joint.
  79800. */
  79801. var DistanceJoint = /** @class */ (function (_super) {
  79802. __extends(DistanceJoint, _super);
  79803. function DistanceJoint(jointData) {
  79804. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  79805. }
  79806. /**
  79807. * Update the predefined distance.
  79808. */
  79809. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  79810. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  79811. };
  79812. return DistanceJoint;
  79813. }(PhysicsJoint));
  79814. BABYLON.DistanceJoint = DistanceJoint;
  79815. var MotorEnabledJoint = /** @class */ (function (_super) {
  79816. __extends(MotorEnabledJoint, _super);
  79817. function MotorEnabledJoint(type, jointData) {
  79818. return _super.call(this, type, jointData) || this;
  79819. }
  79820. /**
  79821. * Set the motor values.
  79822. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79823. * @param {number} force the force to apply
  79824. * @param {number} maxForce max force for this motor.
  79825. */
  79826. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  79827. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  79828. };
  79829. /**
  79830. * Set the motor's limits.
  79831. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79832. */
  79833. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  79834. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  79835. };
  79836. return MotorEnabledJoint;
  79837. }(PhysicsJoint));
  79838. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  79839. /**
  79840. * This class represents a single hinge physics joint
  79841. */
  79842. var HingeJoint = /** @class */ (function (_super) {
  79843. __extends(HingeJoint, _super);
  79844. function HingeJoint(jointData) {
  79845. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  79846. }
  79847. /**
  79848. * Set the motor values.
  79849. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79850. * @param {number} force the force to apply
  79851. * @param {number} maxForce max force for this motor.
  79852. */
  79853. HingeJoint.prototype.setMotor = function (force, maxForce) {
  79854. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  79855. };
  79856. /**
  79857. * Set the motor's limits.
  79858. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79859. */
  79860. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  79861. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  79862. };
  79863. return HingeJoint;
  79864. }(MotorEnabledJoint));
  79865. BABYLON.HingeJoint = HingeJoint;
  79866. /**
  79867. * This class represents a dual hinge physics joint (same as wheel joint)
  79868. */
  79869. var Hinge2Joint = /** @class */ (function (_super) {
  79870. __extends(Hinge2Joint, _super);
  79871. function Hinge2Joint(jointData) {
  79872. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  79873. }
  79874. /**
  79875. * Set the motor values.
  79876. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79877. * @param {number} force the force to apply
  79878. * @param {number} maxForce max force for this motor.
  79879. * @param {motorIndex} the motor's index, 0 or 1.
  79880. */
  79881. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  79882. if (motorIndex === void 0) { motorIndex = 0; }
  79883. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  79884. };
  79885. /**
  79886. * Set the motor limits.
  79887. * Attention, this function is plugin specific. Engines won't react 100% the same.
  79888. * @param {number} upperLimit the upper limit
  79889. * @param {number} lowerLimit lower limit
  79890. * @param {motorIndex} the motor's index, 0 or 1.
  79891. */
  79892. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  79893. if (motorIndex === void 0) { motorIndex = 0; }
  79894. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  79895. };
  79896. return Hinge2Joint;
  79897. }(MotorEnabledJoint));
  79898. BABYLON.Hinge2Joint = Hinge2Joint;
  79899. })(BABYLON || (BABYLON = {}));
  79900. //# sourceMappingURL=babylon.physicsJoint.js.map
  79901. "use strict";
  79902. var BABYLON;
  79903. (function (BABYLON) {
  79904. var PhysicsImpostor = /** @class */ (function () {
  79905. function PhysicsImpostor(object, type, _options, _scene) {
  79906. if (_options === void 0) { _options = { mass: 0 }; }
  79907. var _this = this;
  79908. this.object = object;
  79909. this.type = type;
  79910. this._options = _options;
  79911. this._scene = _scene;
  79912. this._bodyUpdateRequired = false;
  79913. this._onBeforePhysicsStepCallbacks = new Array();
  79914. this._onAfterPhysicsStepCallbacks = new Array();
  79915. this._onPhysicsCollideCallbacks = [];
  79916. this._deltaPosition = BABYLON.Vector3.Zero();
  79917. this._isDisposed = false;
  79918. //temp variables for parent rotation calculations
  79919. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  79920. this._tmpQuat = new BABYLON.Quaternion();
  79921. this._tmpQuat2 = new BABYLON.Quaternion();
  79922. /**
  79923. * this function is executed by the physics engine.
  79924. */
  79925. this.beforeStep = function () {
  79926. if (!_this._physicsEngine) {
  79927. return;
  79928. }
  79929. _this.object.translate(_this._deltaPosition, -1);
  79930. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  79931. _this.object.computeWorldMatrix(false);
  79932. if (_this.object.parent && _this.object.rotationQuaternion) {
  79933. _this.getParentsRotation();
  79934. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  79935. }
  79936. else {
  79937. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  79938. }
  79939. if (!_this._options.disableBidirectionalTransformation) {
  79940. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  79941. }
  79942. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  79943. func(_this);
  79944. });
  79945. };
  79946. /**
  79947. * this function is executed by the physics engine.
  79948. */
  79949. this.afterStep = function () {
  79950. if (!_this._physicsEngine) {
  79951. return;
  79952. }
  79953. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  79954. func(_this);
  79955. });
  79956. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  79957. // object has now its world rotation. needs to be converted to local.
  79958. if (_this.object.parent && _this.object.rotationQuaternion) {
  79959. _this.getParentsRotation();
  79960. _this._tmpQuat.conjugateInPlace();
  79961. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  79962. }
  79963. // take the position set and make it the absolute position of this object.
  79964. _this.object.setAbsolutePosition(_this.object.position);
  79965. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  79966. _this.object.translate(_this._deltaPosition, 1);
  79967. };
  79968. /**
  79969. * Legacy collision detection event support
  79970. */
  79971. this.onCollideEvent = null;
  79972. //event and body object due to cannon's event-based architecture.
  79973. this.onCollide = function (e) {
  79974. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  79975. return;
  79976. }
  79977. if (!_this._physicsEngine) {
  79978. return;
  79979. }
  79980. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  79981. if (otherImpostor) {
  79982. // Legacy collision detection event support
  79983. if (_this.onCollideEvent) {
  79984. _this.onCollideEvent(_this, otherImpostor);
  79985. }
  79986. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  79987. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  79988. }).forEach(function (obj) {
  79989. obj.callback(_this, otherImpostor);
  79990. });
  79991. }
  79992. };
  79993. //sanity check!
  79994. if (!this.object) {
  79995. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  79996. return;
  79997. }
  79998. //legacy support for old syntax.
  79999. if (!this._scene && object.getScene) {
  80000. this._scene = object.getScene();
  80001. }
  80002. if (!this._scene) {
  80003. return;
  80004. }
  80005. this._physicsEngine = this._scene.getPhysicsEngine();
  80006. if (!this._physicsEngine) {
  80007. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  80008. }
  80009. else {
  80010. //set the object's quaternion, if not set
  80011. if (!this.object.rotationQuaternion) {
  80012. if (this.object.rotation) {
  80013. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  80014. }
  80015. else {
  80016. this.object.rotationQuaternion = new BABYLON.Quaternion();
  80017. }
  80018. }
  80019. //default options params
  80020. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  80021. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  80022. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  80023. this._joints = [];
  80024. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  80025. if (!this.object.parent || this._options.ignoreParent) {
  80026. this._init();
  80027. }
  80028. else if (this.object.parent.physicsImpostor) {
  80029. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  80030. }
  80031. }
  80032. }
  80033. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  80034. get: function () {
  80035. return this._isDisposed;
  80036. },
  80037. enumerable: true,
  80038. configurable: true
  80039. });
  80040. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  80041. get: function () {
  80042. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  80043. },
  80044. set: function (value) {
  80045. this.setMass(value);
  80046. },
  80047. enumerable: true,
  80048. configurable: true
  80049. });
  80050. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  80051. get: function () {
  80052. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  80053. },
  80054. set: function (value) {
  80055. if (!this._physicsEngine) {
  80056. return;
  80057. }
  80058. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  80059. },
  80060. enumerable: true,
  80061. configurable: true
  80062. });
  80063. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  80064. get: function () {
  80065. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  80066. },
  80067. set: function (value) {
  80068. if (!this._physicsEngine) {
  80069. return;
  80070. }
  80071. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  80072. },
  80073. enumerable: true,
  80074. configurable: true
  80075. });
  80076. /**
  80077. * This function will completly initialize this impostor.
  80078. * It will create a new body - but only if this mesh has no parent.
  80079. * If it has, this impostor will not be used other than to define the impostor
  80080. * of the child mesh.
  80081. */
  80082. PhysicsImpostor.prototype._init = function () {
  80083. if (!this._physicsEngine) {
  80084. return;
  80085. }
  80086. this._physicsEngine.removeImpostor(this);
  80087. this.physicsBody = null;
  80088. this._parent = this._parent || this._getPhysicsParent();
  80089. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  80090. this._physicsEngine.addImpostor(this);
  80091. }
  80092. };
  80093. PhysicsImpostor.prototype._getPhysicsParent = function () {
  80094. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  80095. var parentMesh = this.object.parent;
  80096. return parentMesh.physicsImpostor;
  80097. }
  80098. return null;
  80099. };
  80100. /**
  80101. * Should a new body be generated.
  80102. */
  80103. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  80104. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  80105. };
  80106. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  80107. this.forceUpdate();
  80108. };
  80109. /**
  80110. * Force a regeneration of this or the parent's impostor's body.
  80111. * Use under cautious - This will remove all joints already implemented.
  80112. */
  80113. PhysicsImpostor.prototype.forceUpdate = function () {
  80114. this._init();
  80115. if (this.parent && !this._options.ignoreParent) {
  80116. this.parent.forceUpdate();
  80117. }
  80118. };
  80119. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  80120. /*public get mesh(): AbstractMesh {
  80121. return this._mesh;
  80122. }*/
  80123. /**
  80124. * Gets the body that holds this impostor. Either its own, or its parent.
  80125. */
  80126. get: function () {
  80127. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  80128. },
  80129. /**
  80130. * Set the physics body. Used mainly by the physics engine/plugin
  80131. */
  80132. set: function (physicsBody) {
  80133. if (this._physicsBody && this._physicsEngine) {
  80134. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  80135. }
  80136. this._physicsBody = physicsBody;
  80137. this.resetUpdateFlags();
  80138. },
  80139. enumerable: true,
  80140. configurable: true
  80141. });
  80142. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  80143. get: function () {
  80144. return !this._options.ignoreParent && this._parent ? this._parent : null;
  80145. },
  80146. set: function (value) {
  80147. this._parent = value;
  80148. },
  80149. enumerable: true,
  80150. configurable: true
  80151. });
  80152. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  80153. this._bodyUpdateRequired = false;
  80154. };
  80155. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  80156. if (this.object.getBoundingInfo) {
  80157. var q = this.object.rotationQuaternion;
  80158. //reset rotation
  80159. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  80160. //calculate the world matrix with no rotation
  80161. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80162. var boundingInfo = this.object.getBoundingInfo();
  80163. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  80164. //bring back the rotation
  80165. this.object.rotationQuaternion = q;
  80166. //calculate the world matrix with the new rotation
  80167. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  80168. return size;
  80169. }
  80170. else {
  80171. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  80172. }
  80173. };
  80174. PhysicsImpostor.prototype.getObjectCenter = function () {
  80175. if (this.object.getBoundingInfo) {
  80176. var boundingInfo = this.object.getBoundingInfo();
  80177. return boundingInfo.boundingBox.centerWorld;
  80178. }
  80179. else {
  80180. return this.object.position;
  80181. }
  80182. };
  80183. /**
  80184. * Get a specific parametes from the options parameter.
  80185. */
  80186. PhysicsImpostor.prototype.getParam = function (paramName) {
  80187. return this._options[paramName];
  80188. };
  80189. /**
  80190. * Sets a specific parameter in the options given to the physics plugin
  80191. */
  80192. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  80193. this._options[paramName] = value;
  80194. this._bodyUpdateRequired = true;
  80195. };
  80196. /**
  80197. * Specifically change the body's mass option. Won't recreate the physics body object
  80198. */
  80199. PhysicsImpostor.prototype.setMass = function (mass) {
  80200. if (this.getParam("mass") !== mass) {
  80201. this.setParam("mass", mass);
  80202. }
  80203. if (this._physicsEngine) {
  80204. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  80205. }
  80206. };
  80207. PhysicsImpostor.prototype.getLinearVelocity = function () {
  80208. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  80209. };
  80210. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  80211. if (this._physicsEngine) {
  80212. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  80213. }
  80214. };
  80215. PhysicsImpostor.prototype.getAngularVelocity = function () {
  80216. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  80217. };
  80218. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  80219. if (this._physicsEngine) {
  80220. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  80221. }
  80222. };
  80223. /**
  80224. * Execute a function with the physics plugin native code.
  80225. * Provide a function the will have two variables - the world object and the physics body object.
  80226. */
  80227. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  80228. if (this._physicsEngine) {
  80229. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  80230. }
  80231. };
  80232. /**
  80233. * Register a function that will be executed before the physics world is stepping forward.
  80234. */
  80235. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  80236. this._onBeforePhysicsStepCallbacks.push(func);
  80237. };
  80238. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  80239. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  80240. if (index > -1) {
  80241. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  80242. }
  80243. else {
  80244. BABYLON.Tools.Warn("Function to remove was not found");
  80245. }
  80246. };
  80247. /**
  80248. * Register a function that will be executed after the physics step
  80249. */
  80250. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  80251. this._onAfterPhysicsStepCallbacks.push(func);
  80252. };
  80253. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  80254. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  80255. if (index > -1) {
  80256. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  80257. }
  80258. else {
  80259. BABYLON.Tools.Warn("Function to remove was not found");
  80260. }
  80261. };
  80262. /**
  80263. * register a function that will be executed when this impostor collides against a different body.
  80264. */
  80265. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  80266. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80267. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  80268. };
  80269. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  80270. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  80271. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  80272. if (index > -1) {
  80273. this._onPhysicsCollideCallbacks.splice(index, 1);
  80274. }
  80275. else {
  80276. BABYLON.Tools.Warn("Function to remove was not found");
  80277. }
  80278. };
  80279. PhysicsImpostor.prototype.getParentsRotation = function () {
  80280. var parent = this.object.parent;
  80281. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  80282. while (parent) {
  80283. if (parent.rotationQuaternion) {
  80284. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  80285. }
  80286. else {
  80287. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  80288. }
  80289. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  80290. parent = parent.parent;
  80291. }
  80292. return this._tmpQuat;
  80293. };
  80294. /**
  80295. * Apply a force
  80296. */
  80297. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  80298. if (this._physicsEngine) {
  80299. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  80300. }
  80301. return this;
  80302. };
  80303. /**
  80304. * Apply an impulse
  80305. */
  80306. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  80307. if (this._physicsEngine) {
  80308. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  80309. }
  80310. return this;
  80311. };
  80312. /**
  80313. * A help function to create a joint.
  80314. */
  80315. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  80316. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  80317. this.addJoint(otherImpostor, joint);
  80318. return this;
  80319. };
  80320. /**
  80321. * Add a joint to this impostor with a different impostor.
  80322. */
  80323. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  80324. this._joints.push({
  80325. otherImpostor: otherImpostor,
  80326. joint: joint
  80327. });
  80328. if (this._physicsEngine) {
  80329. this._physicsEngine.addJoint(this, otherImpostor, joint);
  80330. }
  80331. return this;
  80332. };
  80333. /**
  80334. * Will keep this body still, in a sleep mode.
  80335. */
  80336. PhysicsImpostor.prototype.sleep = function () {
  80337. if (this._physicsEngine) {
  80338. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  80339. }
  80340. return this;
  80341. };
  80342. /**
  80343. * Wake the body up.
  80344. */
  80345. PhysicsImpostor.prototype.wakeUp = function () {
  80346. if (this._physicsEngine) {
  80347. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  80348. }
  80349. return this;
  80350. };
  80351. PhysicsImpostor.prototype.clone = function (newObject) {
  80352. if (!newObject)
  80353. return null;
  80354. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  80355. };
  80356. PhysicsImpostor.prototype.dispose = function () {
  80357. var _this = this;
  80358. //no dispose if no physics engine is available.
  80359. if (!this._physicsEngine) {
  80360. return;
  80361. }
  80362. this._joints.forEach(function (j) {
  80363. if (_this._physicsEngine) {
  80364. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  80365. }
  80366. });
  80367. //dispose the physics body
  80368. this._physicsEngine.removeImpostor(this);
  80369. if (this.parent) {
  80370. this.parent.forceUpdate();
  80371. }
  80372. else {
  80373. /*this._object.getChildMeshes().forEach(function(mesh) {
  80374. if (mesh.physicsImpostor) {
  80375. if (disposeChildren) {
  80376. mesh.physicsImpostor.dispose();
  80377. mesh.physicsImpostor = null;
  80378. }
  80379. }
  80380. })*/
  80381. }
  80382. this._isDisposed = true;
  80383. };
  80384. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  80385. this._deltaPosition.copyFrom(position);
  80386. };
  80387. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  80388. if (!this._deltaRotation) {
  80389. this._deltaRotation = new BABYLON.Quaternion();
  80390. }
  80391. this._deltaRotation.copyFrom(rotation);
  80392. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  80393. };
  80394. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  80395. if (this._physicsEngine) {
  80396. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  80397. }
  80398. return this;
  80399. };
  80400. PhysicsImpostor.prototype.getRadius = function () {
  80401. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  80402. };
  80403. /**
  80404. * Sync a bone with this impostor
  80405. * @param bone The bone to sync to the impostor.
  80406. * @param boneMesh The mesh that the bone is influencing.
  80407. * @param jointPivot The pivot of the joint / bone in local space.
  80408. * @param distToJoint Optional distance from the impostor to the joint.
  80409. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80410. */
  80411. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  80412. var tempVec = PhysicsImpostor._tmpVecs[0];
  80413. var mesh = this.object;
  80414. if (mesh.rotationQuaternion) {
  80415. if (adjustRotation) {
  80416. var tempQuat = PhysicsImpostor._tmpQuat;
  80417. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  80418. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  80419. }
  80420. else {
  80421. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  80422. }
  80423. }
  80424. tempVec.x = 0;
  80425. tempVec.y = 0;
  80426. tempVec.z = 0;
  80427. if (jointPivot) {
  80428. tempVec.x = jointPivot.x;
  80429. tempVec.y = jointPivot.y;
  80430. tempVec.z = jointPivot.z;
  80431. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  80432. if (distToJoint === undefined || distToJoint === null) {
  80433. distToJoint = jointPivot.length();
  80434. }
  80435. tempVec.x *= distToJoint;
  80436. tempVec.y *= distToJoint;
  80437. tempVec.z *= distToJoint;
  80438. }
  80439. if (bone.getParent()) {
  80440. tempVec.addInPlace(mesh.getAbsolutePosition());
  80441. bone.setAbsolutePosition(tempVec, boneMesh);
  80442. }
  80443. else {
  80444. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  80445. boneMesh.position.x -= tempVec.x;
  80446. boneMesh.position.y -= tempVec.y;
  80447. boneMesh.position.z -= tempVec.z;
  80448. }
  80449. };
  80450. /**
  80451. * Sync impostor to a bone
  80452. * @param bone The bone that the impostor will be synced to.
  80453. * @param boneMesh The mesh that the bone is influencing.
  80454. * @param jointPivot The pivot of the joint / bone in local space.
  80455. * @param distToJoint Optional distance from the impostor to the joint.
  80456. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  80457. * @param boneAxis Optional vector3 axis the bone is aligned with
  80458. */
  80459. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  80460. var mesh = this.object;
  80461. if (mesh.rotationQuaternion) {
  80462. if (adjustRotation) {
  80463. var tempQuat = PhysicsImpostor._tmpQuat;
  80464. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  80465. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  80466. }
  80467. else {
  80468. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  80469. }
  80470. }
  80471. var pos = PhysicsImpostor._tmpVecs[0];
  80472. var boneDir = PhysicsImpostor._tmpVecs[1];
  80473. if (!boneAxis) {
  80474. boneAxis = PhysicsImpostor._tmpVecs[2];
  80475. boneAxis.x = 0;
  80476. boneAxis.y = 1;
  80477. boneAxis.z = 0;
  80478. }
  80479. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  80480. bone.getAbsolutePositionToRef(boneMesh, pos);
  80481. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  80482. distToJoint = jointPivot.length();
  80483. }
  80484. if (distToJoint !== undefined && distToJoint !== null) {
  80485. pos.x += boneDir.x * distToJoint;
  80486. pos.y += boneDir.y * distToJoint;
  80487. pos.z += boneDir.z * distToJoint;
  80488. }
  80489. mesh.setAbsolutePosition(pos);
  80490. };
  80491. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  80492. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  80493. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80494. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  80495. //Impostor types
  80496. PhysicsImpostor.NoImpostor = 0;
  80497. PhysicsImpostor.SphereImpostor = 1;
  80498. PhysicsImpostor.BoxImpostor = 2;
  80499. PhysicsImpostor.PlaneImpostor = 3;
  80500. PhysicsImpostor.MeshImpostor = 4;
  80501. PhysicsImpostor.CylinderImpostor = 7;
  80502. PhysicsImpostor.ParticleImpostor = 8;
  80503. PhysicsImpostor.HeightmapImpostor = 9;
  80504. return PhysicsImpostor;
  80505. }());
  80506. BABYLON.PhysicsImpostor = PhysicsImpostor;
  80507. })(BABYLON || (BABYLON = {}));
  80508. //# sourceMappingURL=babylon.physicsImpostor.js.map
  80509. "use strict";
  80510. var BABYLON;
  80511. (function (BABYLON) {
  80512. var PhysicsEngine = /** @class */ (function () {
  80513. function PhysicsEngine(gravity, _physicsPlugin) {
  80514. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  80515. this._physicsPlugin = _physicsPlugin;
  80516. //new methods and parameters
  80517. this._impostors = [];
  80518. this._joints = [];
  80519. if (!this._physicsPlugin.isSupported()) {
  80520. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  80521. + "Please make sure it is included.");
  80522. }
  80523. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  80524. this.setGravity(gravity);
  80525. this.setTimeStep();
  80526. }
  80527. PhysicsEngine.prototype.setGravity = function (gravity) {
  80528. this.gravity = gravity;
  80529. this._physicsPlugin.setGravity(this.gravity);
  80530. };
  80531. /**
  80532. * Set the time step of the physics engine.
  80533. * default is 1/60.
  80534. * To slow it down, enter 1/600 for example.
  80535. * To speed it up, 1/30
  80536. * @param {number} newTimeStep the new timestep to apply to this world.
  80537. */
  80538. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  80539. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  80540. this._physicsPlugin.setTimeStep(newTimeStep);
  80541. };
  80542. /**
  80543. * Get the time step of the physics engine.
  80544. */
  80545. PhysicsEngine.prototype.getTimeStep = function () {
  80546. return this._physicsPlugin.getTimeStep();
  80547. };
  80548. PhysicsEngine.prototype.dispose = function () {
  80549. this._impostors.forEach(function (impostor) {
  80550. impostor.dispose();
  80551. });
  80552. this._physicsPlugin.dispose();
  80553. };
  80554. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  80555. return this._physicsPlugin.name;
  80556. };
  80557. /**
  80558. * Adding a new impostor for the impostor tracking.
  80559. * This will be done by the impostor itself.
  80560. * @param {PhysicsImpostor} impostor the impostor to add
  80561. */
  80562. PhysicsEngine.prototype.addImpostor = function (impostor) {
  80563. impostor.uniqueId = this._impostors.push(impostor);
  80564. //if no parent, generate the body
  80565. if (!impostor.parent) {
  80566. this._physicsPlugin.generatePhysicsBody(impostor);
  80567. }
  80568. };
  80569. /**
  80570. * Remove an impostor from the engine.
  80571. * This impostor and its mesh will not longer be updated by the physics engine.
  80572. * @param {PhysicsImpostor} impostor the impostor to remove
  80573. */
  80574. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  80575. var index = this._impostors.indexOf(impostor);
  80576. if (index > -1) {
  80577. var removed = this._impostors.splice(index, 1);
  80578. //Is it needed?
  80579. if (removed.length) {
  80580. //this will also remove it from the world.
  80581. removed[0].physicsBody = null;
  80582. }
  80583. }
  80584. };
  80585. /**
  80586. * Add a joint to the physics engine
  80587. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  80588. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  80589. * @param {PhysicsJoint} the joint that will connect both impostors.
  80590. */
  80591. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  80592. var impostorJoint = {
  80593. mainImpostor: mainImpostor,
  80594. connectedImpostor: connectedImpostor,
  80595. joint: joint
  80596. };
  80597. joint.physicsPlugin = this._physicsPlugin;
  80598. this._joints.push(impostorJoint);
  80599. this._physicsPlugin.generateJoint(impostorJoint);
  80600. };
  80601. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  80602. var matchingJoints = this._joints.filter(function (impostorJoint) {
  80603. return (impostorJoint.connectedImpostor === connectedImpostor
  80604. && impostorJoint.joint === joint
  80605. && impostorJoint.mainImpostor === mainImpostor);
  80606. });
  80607. if (matchingJoints.length) {
  80608. this._physicsPlugin.removeJoint(matchingJoints[0]);
  80609. //TODO remove it from the list as well
  80610. }
  80611. };
  80612. /**
  80613. * Called by the scene. no need to call it.
  80614. */
  80615. PhysicsEngine.prototype._step = function (delta) {
  80616. var _this = this;
  80617. //check if any mesh has no body / requires an update
  80618. this._impostors.forEach(function (impostor) {
  80619. if (impostor.isBodyInitRequired()) {
  80620. _this._physicsPlugin.generatePhysicsBody(impostor);
  80621. }
  80622. });
  80623. if (delta > 0.1) {
  80624. delta = 0.1;
  80625. }
  80626. else if (delta <= 0) {
  80627. delta = 1.0 / 60.0;
  80628. }
  80629. this._physicsPlugin.executeStep(delta, this._impostors);
  80630. };
  80631. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  80632. return this._physicsPlugin;
  80633. };
  80634. PhysicsEngine.prototype.getImpostors = function () {
  80635. return this._impostors;
  80636. };
  80637. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  80638. for (var i = 0; i < this._impostors.length; ++i) {
  80639. if (this._impostors[i].object === object) {
  80640. return this._impostors[i];
  80641. }
  80642. }
  80643. return null;
  80644. };
  80645. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  80646. for (var i = 0; i < this._impostors.length; ++i) {
  80647. if (this._impostors[i].physicsBody === body) {
  80648. return this._impostors[i];
  80649. }
  80650. }
  80651. return null;
  80652. };
  80653. // Statics
  80654. PhysicsEngine.Epsilon = 0.001;
  80655. return PhysicsEngine;
  80656. }());
  80657. BABYLON.PhysicsEngine = PhysicsEngine;
  80658. })(BABYLON || (BABYLON = {}));
  80659. //# sourceMappingURL=babylon.physicsEngine.js.map
  80660. "use strict";
  80661. var BABYLON;
  80662. (function (BABYLON) {
  80663. var PhysicsHelper = /** @class */ (function () {
  80664. function PhysicsHelper(scene) {
  80665. this._scene = scene;
  80666. this._physicsEngine = this._scene.getPhysicsEngine();
  80667. if (!this._physicsEngine) {
  80668. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  80669. }
  80670. }
  80671. /**
  80672. * @param {Vector3} origin the origin of the explosion
  80673. * @param {number} radius the explosion radius
  80674. * @param {number} strength the explosion strength
  80675. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80676. */
  80677. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  80678. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80679. if (!this._physicsEngine) {
  80680. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  80681. return null;
  80682. }
  80683. var impostors = this._physicsEngine.getImpostors();
  80684. if (impostors.length === 0) {
  80685. return null;
  80686. }
  80687. var event = new PhysicsRadialExplosionEvent(this._scene);
  80688. impostors.forEach(function (impostor) {
  80689. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80690. if (!impostorForceAndContactPoint) {
  80691. return;
  80692. }
  80693. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80694. });
  80695. event.dispose(false);
  80696. return event;
  80697. };
  80698. /**
  80699. * @param {Vector3} origin the origin of the explosion
  80700. * @param {number} radius the explosion radius
  80701. * @param {number} strength the explosion strength
  80702. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80703. */
  80704. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  80705. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80706. if (!this._physicsEngine) {
  80707. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80708. return null;
  80709. }
  80710. var impostors = this._physicsEngine.getImpostors();
  80711. if (impostors.length === 0) {
  80712. return null;
  80713. }
  80714. var event = new PhysicsRadialExplosionEvent(this._scene);
  80715. impostors.forEach(function (impostor) {
  80716. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  80717. if (!impostorForceAndContactPoint) {
  80718. return;
  80719. }
  80720. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  80721. });
  80722. event.dispose(false);
  80723. return event;
  80724. };
  80725. /**
  80726. * @param {Vector3} origin the origin of the explosion
  80727. * @param {number} radius the explosion radius
  80728. * @param {number} strength the explosion strength
  80729. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  80730. */
  80731. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  80732. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80733. if (!this._physicsEngine) {
  80734. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80735. return null;
  80736. }
  80737. var impostors = this._physicsEngine.getImpostors();
  80738. if (impostors.length === 0) {
  80739. return null;
  80740. }
  80741. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  80742. event.dispose(false);
  80743. return event;
  80744. };
  80745. /**
  80746. * @param {Vector3} origin the origin of the updraft
  80747. * @param {number} radius the radius of the updraft
  80748. * @param {number} strength the strength of the updraft
  80749. * @param {number} height the height of the updraft
  80750. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  80751. */
  80752. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  80753. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  80754. if (!this._physicsEngine) {
  80755. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80756. return null;
  80757. }
  80758. if (this._physicsEngine.getImpostors().length === 0) {
  80759. return null;
  80760. }
  80761. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  80762. event.dispose(false);
  80763. return event;
  80764. };
  80765. /**
  80766. * @param {Vector3} origin the of the vortex
  80767. * @param {number} radius the radius of the vortex
  80768. * @param {number} strength the strength of the vortex
  80769. * @param {number} height the height of the vortex
  80770. */
  80771. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  80772. if (!this._physicsEngine) {
  80773. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  80774. return null;
  80775. }
  80776. if (this._physicsEngine.getImpostors().length === 0) {
  80777. return null;
  80778. }
  80779. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  80780. event.dispose(false);
  80781. return event;
  80782. };
  80783. return PhysicsHelper;
  80784. }());
  80785. BABYLON.PhysicsHelper = PhysicsHelper;
  80786. /***** Radial explosion *****/
  80787. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  80788. function PhysicsRadialExplosionEvent(scene) {
  80789. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  80790. this._rays = [];
  80791. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  80792. this._scene = scene;
  80793. }
  80794. /**
  80795. * Returns the data related to the radial explosion event (sphere & rays).
  80796. * @returns {PhysicsRadialExplosionEventData}
  80797. */
  80798. PhysicsRadialExplosionEvent.prototype.getData = function () {
  80799. this._dataFetched = true;
  80800. return {
  80801. sphere: this._sphere,
  80802. rays: this._rays,
  80803. };
  80804. };
  80805. /**
  80806. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  80807. * @param impostor
  80808. * @param {Vector3} origin the origin of the explosion
  80809. * @param {number} radius the explosion radius
  80810. * @param {number} strength the explosion strength
  80811. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  80812. * @returns {Nullable<PhysicsForceAndContactPoint>}
  80813. */
  80814. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  80815. if (impostor.mass === 0) {
  80816. return null;
  80817. }
  80818. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  80819. return null;
  80820. }
  80821. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  80822. return null;
  80823. }
  80824. var impostorObjectCenter = impostor.getObjectCenter();
  80825. var direction = impostorObjectCenter.subtract(origin);
  80826. var ray = new BABYLON.Ray(origin, direction, radius);
  80827. this._rays.push(ray);
  80828. var hit = ray.intersectsMesh(impostor.object);
  80829. var contactPoint = hit.pickedPoint;
  80830. if (!contactPoint) {
  80831. return null;
  80832. }
  80833. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  80834. if (distanceFromOrigin > radius) {
  80835. return null;
  80836. }
  80837. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  80838. ? strength
  80839. : strength * (1 - (distanceFromOrigin / radius));
  80840. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  80841. return { force: force, contactPoint: contactPoint };
  80842. };
  80843. /**
  80844. * Disposes the sphere.
  80845. * @param {bolean} force
  80846. */
  80847. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  80848. var _this = this;
  80849. if (force === void 0) { force = true; }
  80850. if (force) {
  80851. this._sphere.dispose();
  80852. }
  80853. else {
  80854. setTimeout(function () {
  80855. if (!_this._dataFetched) {
  80856. _this._sphere.dispose();
  80857. }
  80858. }, 0);
  80859. }
  80860. };
  80861. /*** Helpers ***/
  80862. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  80863. if (!this._sphere) {
  80864. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  80865. this._sphere.isVisible = false;
  80866. }
  80867. };
  80868. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  80869. var impostorObject = impostor.object;
  80870. this._prepareSphere();
  80871. this._sphere.position = origin;
  80872. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  80873. this._sphere._updateBoundingInfo();
  80874. this._sphere.computeWorldMatrix(true);
  80875. return this._sphere.intersectsMesh(impostorObject, true);
  80876. };
  80877. return PhysicsRadialExplosionEvent;
  80878. }());
  80879. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  80880. /***** Gravitational Field *****/
  80881. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  80882. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  80883. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  80884. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80885. this._physicsHelper = physicsHelper;
  80886. this._scene = scene;
  80887. this._origin = origin;
  80888. this._radius = radius;
  80889. this._strength = strength;
  80890. this._falloff = falloff;
  80891. this._tickCallback = this._tick.bind(this);
  80892. }
  80893. /**
  80894. * Returns the data related to the gravitational field event (sphere).
  80895. * @returns {PhysicsGravitationalFieldEventData}
  80896. */
  80897. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  80898. this._dataFetched = true;
  80899. return {
  80900. sphere: this._sphere,
  80901. };
  80902. };
  80903. /**
  80904. * Enables the gravitational field.
  80905. */
  80906. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  80907. this._tickCallback.call(this);
  80908. this._scene.registerBeforeRender(this._tickCallback);
  80909. };
  80910. /**
  80911. * Disables the gravitational field.
  80912. */
  80913. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  80914. this._scene.unregisterBeforeRender(this._tickCallback);
  80915. };
  80916. /**
  80917. * Disposes the sphere.
  80918. * @param {bolean} force
  80919. */
  80920. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  80921. var _this = this;
  80922. if (force === void 0) { force = true; }
  80923. if (force) {
  80924. this._sphere.dispose();
  80925. }
  80926. else {
  80927. setTimeout(function () {
  80928. if (!_this._dataFetched) {
  80929. _this._sphere.dispose();
  80930. }
  80931. }, 0);
  80932. }
  80933. };
  80934. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  80935. // Since the params won't change, we fetch the event only once
  80936. if (this._sphere) {
  80937. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  80938. }
  80939. else {
  80940. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  80941. if (radialExplosionEvent) {
  80942. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  80943. }
  80944. }
  80945. };
  80946. return PhysicsGravitationalFieldEvent;
  80947. }());
  80948. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  80949. /***** Updraft *****/
  80950. var PhysicsUpdraftEvent = /** @class */ (function () {
  80951. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  80952. this._scene = _scene;
  80953. this._origin = _origin;
  80954. this._radius = _radius;
  80955. this._strength = _strength;
  80956. this._height = _height;
  80957. this._updraftMode = _updraftMode;
  80958. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  80959. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  80960. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  80961. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  80962. this._physicsEngine = this._scene.getPhysicsEngine();
  80963. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  80964. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  80965. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  80966. this._originDirection = this._origin.subtract(this._originTop).normalize();
  80967. }
  80968. this._tickCallback = this._tick.bind(this);
  80969. }
  80970. /**
  80971. * Returns the data related to the updraft event (cylinder).
  80972. * @returns {PhysicsUpdraftEventData}
  80973. */
  80974. PhysicsUpdraftEvent.prototype.getData = function () {
  80975. this._dataFetched = true;
  80976. return {
  80977. cylinder: this._cylinder,
  80978. };
  80979. };
  80980. /**
  80981. * Enables the updraft.
  80982. */
  80983. PhysicsUpdraftEvent.prototype.enable = function () {
  80984. this._tickCallback.call(this);
  80985. this._scene.registerBeforeRender(this._tickCallback);
  80986. };
  80987. /**
  80988. * Disables the cortex.
  80989. */
  80990. PhysicsUpdraftEvent.prototype.disable = function () {
  80991. this._scene.unregisterBeforeRender(this._tickCallback);
  80992. };
  80993. /**
  80994. * Disposes the sphere.
  80995. * @param {bolean} force
  80996. */
  80997. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  80998. var _this = this;
  80999. if (force === void 0) { force = true; }
  81000. if (force) {
  81001. this._cylinder.dispose();
  81002. }
  81003. else {
  81004. setTimeout(function () {
  81005. if (!_this._dataFetched) {
  81006. _this._cylinder.dispose();
  81007. }
  81008. }, 0);
  81009. }
  81010. };
  81011. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81012. if (impostor.mass === 0) {
  81013. return null;
  81014. }
  81015. if (!this._intersectsWithCylinder(impostor)) {
  81016. return null;
  81017. }
  81018. var impostorObjectCenter = impostor.getObjectCenter();
  81019. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  81020. var direction = this._originDirection;
  81021. }
  81022. else {
  81023. var direction = impostorObjectCenter.subtract(this._originTop);
  81024. }
  81025. var multiplier = this._strength * -1;
  81026. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81027. return { force: force, contactPoint: impostorObjectCenter };
  81028. };
  81029. PhysicsUpdraftEvent.prototype._tick = function () {
  81030. var _this = this;
  81031. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81032. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81033. if (!impostorForceAndContactPoint) {
  81034. return;
  81035. }
  81036. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81037. });
  81038. };
  81039. /*** Helpers ***/
  81040. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  81041. if (!this._cylinder) {
  81042. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  81043. height: this._height,
  81044. diameter: this._radius * 2,
  81045. }, this._scene);
  81046. this._cylinder.isVisible = false;
  81047. }
  81048. };
  81049. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  81050. var impostorObject = impostor.object;
  81051. this._prepareCylinder();
  81052. this._cylinder.position = this._cylinderPosition;
  81053. return this._cylinder.intersectsMesh(impostorObject, true);
  81054. };
  81055. return PhysicsUpdraftEvent;
  81056. }());
  81057. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  81058. /***** Vortex *****/
  81059. var PhysicsVortexEvent = /** @class */ (function () {
  81060. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  81061. this._scene = _scene;
  81062. this._origin = _origin;
  81063. this._radius = _radius;
  81064. this._strength = _strength;
  81065. this._height = _height;
  81066. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  81067. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  81068. this._updraftMultiplier = 0.02;
  81069. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  81070. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  81071. this._physicsEngine = this._scene.getPhysicsEngine();
  81072. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  81073. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  81074. this._tickCallback = this._tick.bind(this);
  81075. }
  81076. /**
  81077. * Returns the data related to the vortex event (cylinder).
  81078. * @returns {PhysicsVortexEventData}
  81079. */
  81080. PhysicsVortexEvent.prototype.getData = function () {
  81081. this._dataFetched = true;
  81082. return {
  81083. cylinder: this._cylinder,
  81084. };
  81085. };
  81086. /**
  81087. * Enables the vortex.
  81088. */
  81089. PhysicsVortexEvent.prototype.enable = function () {
  81090. this._tickCallback.call(this);
  81091. this._scene.registerBeforeRender(this._tickCallback);
  81092. };
  81093. /**
  81094. * Disables the cortex.
  81095. */
  81096. PhysicsVortexEvent.prototype.disable = function () {
  81097. this._scene.unregisterBeforeRender(this._tickCallback);
  81098. };
  81099. /**
  81100. * Disposes the sphere.
  81101. * @param {bolean} force
  81102. */
  81103. PhysicsVortexEvent.prototype.dispose = function (force) {
  81104. var _this = this;
  81105. if (force === void 0) { force = true; }
  81106. if (force) {
  81107. this._cylinder.dispose();
  81108. }
  81109. else {
  81110. setTimeout(function () {
  81111. if (!_this._dataFetched) {
  81112. _this._cylinder.dispose();
  81113. }
  81114. }, 0);
  81115. }
  81116. };
  81117. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  81118. if (impostor.mass === 0) {
  81119. return null;
  81120. }
  81121. if (!this._intersectsWithCylinder(impostor)) {
  81122. return null;
  81123. }
  81124. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81125. return null;
  81126. }
  81127. var impostorObjectCenter = impostor.getObjectCenter();
  81128. 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)
  81129. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  81130. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  81131. var hit = ray.intersectsMesh(impostor.object);
  81132. var contactPoint = hit.pickedPoint;
  81133. if (!contactPoint) {
  81134. return null;
  81135. }
  81136. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  81137. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  81138. var directionToOrigin = contactPoint.normalize();
  81139. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81140. directionToOrigin = directionToOrigin.negate();
  81141. }
  81142. // TODO: find a more physically based solution
  81143. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  81144. var forceX = directionToOrigin.x * this._strength / 8;
  81145. var forceY = directionToOrigin.y * this._updraftMultiplier;
  81146. var forceZ = directionToOrigin.z * this._strength / 8;
  81147. }
  81148. else {
  81149. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  81150. var forceY = this._originTop.y * this._updraftMultiplier;
  81151. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  81152. }
  81153. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  81154. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  81155. return { force: force, contactPoint: impostorObjectCenter };
  81156. };
  81157. PhysicsVortexEvent.prototype._tick = function () {
  81158. var _this = this;
  81159. this._physicsEngine.getImpostors().forEach(function (impostor) {
  81160. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  81161. if (!impostorForceAndContactPoint) {
  81162. return;
  81163. }
  81164. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81165. });
  81166. };
  81167. /*** Helpers ***/
  81168. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  81169. if (!this._cylinder) {
  81170. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  81171. height: this._height,
  81172. diameter: this._radius * 2,
  81173. }, this._scene);
  81174. this._cylinder.isVisible = false;
  81175. }
  81176. };
  81177. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  81178. var impostorObject = impostor.object;
  81179. this._prepareCylinder();
  81180. this._cylinder.position = this._cylinderPosition;
  81181. return this._cylinder.intersectsMesh(impostorObject, true);
  81182. };
  81183. return PhysicsVortexEvent;
  81184. }());
  81185. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  81186. /***** Enums *****/
  81187. /**
  81188. * The strenght of the force in correspondence to the distance of the affected object
  81189. */
  81190. var PhysicsRadialImpulseFalloff;
  81191. (function (PhysicsRadialImpulseFalloff) {
  81192. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  81193. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  81194. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  81195. /**
  81196. * The strenght of the force in correspondence to the distance of the affected object
  81197. */
  81198. var PhysicsUpdraftMode;
  81199. (function (PhysicsUpdraftMode) {
  81200. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  81201. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  81202. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  81203. })(BABYLON || (BABYLON = {}));
  81204. //# sourceMappingURL=babylon.physicsHelper.js.map
  81205. "use strict";
  81206. var BABYLON;
  81207. (function (BABYLON) {
  81208. var CannonJSPlugin = /** @class */ (function () {
  81209. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  81210. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  81211. if (iterations === void 0) { iterations = 10; }
  81212. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  81213. this.name = "CannonJSPlugin";
  81214. this._physicsMaterials = new Array();
  81215. this._fixedTimeStep = 1 / 60;
  81216. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  81217. this.BJSCANNON = CANNON;
  81218. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  81219. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  81220. this._tmpPosition = BABYLON.Vector3.Zero();
  81221. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  81222. this._tmpUnityRotation = new BABYLON.Quaternion();
  81223. if (!this.isSupported()) {
  81224. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  81225. return;
  81226. }
  81227. this._extendNamespace();
  81228. this.world = new this.BJSCANNON.World();
  81229. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  81230. this.world.solver.iterations = iterations;
  81231. }
  81232. CannonJSPlugin.prototype.setGravity = function (gravity) {
  81233. this.world.gravity.copy(gravity);
  81234. };
  81235. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  81236. this._fixedTimeStep = timeStep;
  81237. };
  81238. CannonJSPlugin.prototype.getTimeStep = function () {
  81239. return this._fixedTimeStep;
  81240. };
  81241. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  81242. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  81243. };
  81244. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81245. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81246. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81247. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  81248. };
  81249. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81250. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  81251. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  81252. impostor.physicsBody.applyForce(impulse, worldPoint);
  81253. };
  81254. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81255. //parent-child relationship. Does this impostor has a parent impostor?
  81256. if (impostor.parent) {
  81257. if (impostor.physicsBody) {
  81258. this.removePhysicsBody(impostor);
  81259. //TODO is that needed?
  81260. impostor.forceUpdate();
  81261. }
  81262. return;
  81263. }
  81264. //should a new body be created for this impostor?
  81265. if (impostor.isBodyInitRequired()) {
  81266. var shape = this._createShape(impostor);
  81267. //unregister events, if body is being changed
  81268. var oldBody = impostor.physicsBody;
  81269. if (oldBody) {
  81270. this.removePhysicsBody(impostor);
  81271. }
  81272. //create the body and material
  81273. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  81274. var bodyCreationObject = {
  81275. mass: impostor.getParam("mass"),
  81276. material: material
  81277. };
  81278. // A simple extend, in case native options were used.
  81279. var nativeOptions = impostor.getParam("nativeOptions");
  81280. for (var key in nativeOptions) {
  81281. if (nativeOptions.hasOwnProperty(key)) {
  81282. bodyCreationObject[key] = nativeOptions[key];
  81283. }
  81284. }
  81285. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  81286. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  81287. this.world.addEventListener("preStep", impostor.beforeStep);
  81288. this.world.addEventListener("postStep", impostor.afterStep);
  81289. impostor.physicsBody.addShape(shape);
  81290. this.world.add(impostor.physicsBody);
  81291. //try to keep the body moving in the right direction by taking old properties.
  81292. //Should be tested!
  81293. if (oldBody) {
  81294. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  81295. impostor.physicsBody[param].copy(oldBody[param]);
  81296. });
  81297. }
  81298. this._processChildMeshes(impostor);
  81299. }
  81300. //now update the body's transformation
  81301. this._updatePhysicsBodyTransformation(impostor);
  81302. };
  81303. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  81304. var _this = this;
  81305. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  81306. var currentRotation = mainImpostor.object.rotationQuaternion;
  81307. if (meshChildren.length) {
  81308. var processMesh = function (localPosition, mesh) {
  81309. if (!currentRotation || !mesh.rotationQuaternion) {
  81310. return;
  81311. }
  81312. var childImpostor = mesh.getPhysicsImpostor();
  81313. if (childImpostor) {
  81314. var parent = childImpostor.parent;
  81315. if (parent !== mainImpostor) {
  81316. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  81317. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  81318. if (childImpostor.physicsBody) {
  81319. _this.removePhysicsBody(childImpostor);
  81320. childImpostor.physicsBody = null;
  81321. }
  81322. childImpostor.parent = mainImpostor;
  81323. childImpostor.resetUpdateFlags();
  81324. 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));
  81325. //Add the mass of the children.
  81326. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  81327. }
  81328. }
  81329. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  81330. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  81331. };
  81332. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  81333. }
  81334. };
  81335. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81336. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  81337. this.world.removeEventListener("preStep", impostor.beforeStep);
  81338. this.world.removeEventListener("postStep", impostor.afterStep);
  81339. this.world.remove(impostor.physicsBody);
  81340. };
  81341. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81342. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81343. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81344. if (!mainBody || !connectedBody) {
  81345. return;
  81346. }
  81347. var constraint;
  81348. var jointData = impostorJoint.joint.jointData;
  81349. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  81350. var constraintData = {
  81351. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  81352. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  81353. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  81354. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  81355. maxForce: jointData.nativeParams.maxForce,
  81356. collideConnected: !!jointData.collision
  81357. };
  81358. switch (impostorJoint.joint.type) {
  81359. case BABYLON.PhysicsJoint.HingeJoint:
  81360. case BABYLON.PhysicsJoint.Hinge2Joint:
  81361. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  81362. break;
  81363. case BABYLON.PhysicsJoint.DistanceJoint:
  81364. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  81365. break;
  81366. case BABYLON.PhysicsJoint.SpringJoint:
  81367. var springData = jointData;
  81368. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  81369. restLength: springData.length,
  81370. stiffness: springData.stiffness,
  81371. damping: springData.damping,
  81372. localAnchorA: constraintData.pivotA,
  81373. localAnchorB: constraintData.pivotB
  81374. });
  81375. break;
  81376. case BABYLON.PhysicsJoint.LockJoint:
  81377. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  81378. break;
  81379. case BABYLON.PhysicsJoint.PointToPointJoint:
  81380. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  81381. default:
  81382. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  81383. break;
  81384. }
  81385. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  81386. constraint.collideConnected = !!jointData.collision;
  81387. impostorJoint.joint.physicsJoint = constraint;
  81388. //don't add spring as constraint, as it is not one.
  81389. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  81390. this.world.addConstraint(constraint);
  81391. }
  81392. else {
  81393. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  81394. constraint.applyForce();
  81395. });
  81396. }
  81397. };
  81398. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  81399. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  81400. };
  81401. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  81402. var index;
  81403. var mat;
  81404. for (index = 0; index < this._physicsMaterials.length; index++) {
  81405. mat = this._physicsMaterials[index];
  81406. if (mat.friction === friction && mat.restitution === restitution) {
  81407. return mat;
  81408. }
  81409. }
  81410. var currentMat = new this.BJSCANNON.Material(name);
  81411. currentMat.friction = friction;
  81412. currentMat.restitution = restitution;
  81413. this._physicsMaterials.push(currentMat);
  81414. return currentMat;
  81415. };
  81416. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  81417. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  81418. };
  81419. CannonJSPlugin.prototype._createShape = function (impostor) {
  81420. var object = impostor.object;
  81421. var returnValue;
  81422. var extendSize = impostor.getObjectExtendSize();
  81423. switch (impostor.type) {
  81424. case BABYLON.PhysicsImpostor.SphereImpostor:
  81425. var radiusX = extendSize.x;
  81426. var radiusY = extendSize.y;
  81427. var radiusZ = extendSize.z;
  81428. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  81429. break;
  81430. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  81431. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81432. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  81433. break;
  81434. case BABYLON.PhysicsImpostor.BoxImpostor:
  81435. var box = extendSize.scale(0.5);
  81436. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  81437. break;
  81438. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81439. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  81440. returnValue = new this.BJSCANNON.Plane();
  81441. break;
  81442. case BABYLON.PhysicsImpostor.MeshImpostor:
  81443. // should transform the vertex data to world coordinates!!
  81444. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  81445. var rawFaces = object.getIndices ? object.getIndices() : [];
  81446. if (!rawVerts)
  81447. return;
  81448. // get only scale! so the object could transform correctly.
  81449. var oldPosition = object.position.clone();
  81450. var oldRotation = object.rotation && object.rotation.clone();
  81451. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  81452. object.position.copyFromFloats(0, 0, 0);
  81453. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81454. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81455. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81456. var transform = object.computeWorldMatrix(true);
  81457. // convert rawVerts to object space
  81458. var temp = new Array();
  81459. var index;
  81460. for (index = 0; index < rawVerts.length; index += 3) {
  81461. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  81462. }
  81463. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  81464. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  81465. //now set back the transformation!
  81466. object.position.copyFrom(oldPosition);
  81467. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  81468. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  81469. break;
  81470. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  81471. var oldPosition2 = object.position.clone();
  81472. var oldRotation2 = object.rotation && object.rotation.clone();
  81473. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  81474. object.position.copyFromFloats(0, 0, 0);
  81475. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  81476. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  81477. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  81478. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  81479. returnValue = this._createHeightmap(object);
  81480. object.position.copyFrom(oldPosition2);
  81481. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  81482. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  81483. object.computeWorldMatrix(true);
  81484. break;
  81485. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81486. returnValue = new this.BJSCANNON.Particle();
  81487. break;
  81488. }
  81489. return returnValue;
  81490. };
  81491. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  81492. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81493. var transform = object.computeWorldMatrix(true);
  81494. // convert rawVerts to object space
  81495. var temp = new Array();
  81496. var index;
  81497. for (index = 0; index < pos.length; index += 3) {
  81498. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  81499. }
  81500. pos = temp;
  81501. var matrix = new Array();
  81502. //For now pointDepth will not be used and will be automatically calculated.
  81503. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  81504. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  81505. var boundingInfo = object.getBoundingInfo();
  81506. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  81507. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  81508. var elementSize = dim * 2 / arraySize;
  81509. for (var i = 0; i < pos.length; i = i + 3) {
  81510. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  81511. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  81512. var y = -pos[i + 2] + minY;
  81513. if (!matrix[x]) {
  81514. matrix[x] = [];
  81515. }
  81516. if (!matrix[x][z]) {
  81517. matrix[x][z] = y;
  81518. }
  81519. matrix[x][z] = Math.max(y, matrix[x][z]);
  81520. }
  81521. for (var x = 0; x <= arraySize; ++x) {
  81522. if (!matrix[x]) {
  81523. var loc = 1;
  81524. while (!matrix[(x + loc) % arraySize]) {
  81525. loc++;
  81526. }
  81527. matrix[x] = matrix[(x + loc) % arraySize].slice();
  81528. //console.log("missing x", x);
  81529. }
  81530. for (var z = 0; z <= arraySize; ++z) {
  81531. if (!matrix[x][z]) {
  81532. var loc = 1;
  81533. var newValue;
  81534. while (newValue === undefined) {
  81535. newValue = matrix[x][(z + loc++) % arraySize];
  81536. }
  81537. matrix[x][z] = newValue;
  81538. }
  81539. }
  81540. }
  81541. var shape = new this.BJSCANNON.Heightfield(matrix, {
  81542. elementSize: elementSize
  81543. });
  81544. //For future reference, needed for body transformation
  81545. shape.minY = minY;
  81546. return shape;
  81547. };
  81548. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  81549. var object = impostor.object;
  81550. //make sure it is updated...
  81551. object.computeWorldMatrix && object.computeWorldMatrix(true);
  81552. // The delta between the mesh position and the mesh bounding box center
  81553. var bInfo = object.getBoundingInfo();
  81554. if (!bInfo)
  81555. return;
  81556. var center = impostor.getObjectCenter();
  81557. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  81558. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  81559. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  81560. this._tmpPosition.copyFrom(center);
  81561. var quaternion = object.rotationQuaternion;
  81562. if (!quaternion) {
  81563. return;
  81564. }
  81565. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  81566. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  81567. //-90 DEG in X, precalculated
  81568. quaternion = quaternion.multiply(this._minus90X);
  81569. //Invert! (Precalculated, 90 deg in X)
  81570. //No need to clone. this will never change.
  81571. impostor.setDeltaRotation(this._plus90X);
  81572. }
  81573. //If it is a heightfield, if should be centered.
  81574. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  81575. var mesh = object;
  81576. var boundingInfo = mesh.getBoundingInfo();
  81577. //calculate the correct body position:
  81578. var rotationQuaternion = mesh.rotationQuaternion;
  81579. mesh.rotationQuaternion = this._tmpUnityRotation;
  81580. mesh.computeWorldMatrix(true);
  81581. //get original center with no rotation
  81582. var c = center.clone();
  81583. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  81584. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  81585. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  81586. mesh.setPreTransformMatrix(p);
  81587. mesh.computeWorldMatrix(true);
  81588. //calculate the translation
  81589. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  81590. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  81591. //add it inverted to the delta
  81592. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  81593. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  81594. //rotation is back
  81595. mesh.rotationQuaternion = rotationQuaternion;
  81596. mesh.setPreTransformMatrix(oldPivot);
  81597. mesh.computeWorldMatrix(true);
  81598. }
  81599. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  81600. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  81601. //this._tmpPosition.copyFrom(object.position);
  81602. }
  81603. impostor.setDeltaPosition(this._tmpDeltaPosition);
  81604. //Now update the impostor object
  81605. impostor.physicsBody.position.copy(this._tmpPosition);
  81606. impostor.physicsBody.quaternion.copy(quaternion);
  81607. };
  81608. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  81609. impostor.object.position.copyFrom(impostor.physicsBody.position);
  81610. if (impostor.object.rotationQuaternion) {
  81611. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  81612. }
  81613. };
  81614. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  81615. impostor.physicsBody.position.copy(newPosition);
  81616. impostor.physicsBody.quaternion.copy(newRotation);
  81617. };
  81618. CannonJSPlugin.prototype.isSupported = function () {
  81619. return this.BJSCANNON !== undefined;
  81620. };
  81621. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  81622. impostor.physicsBody.velocity.copy(velocity);
  81623. };
  81624. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  81625. impostor.physicsBody.angularVelocity.copy(velocity);
  81626. };
  81627. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  81628. var v = impostor.physicsBody.velocity;
  81629. if (!v) {
  81630. return null;
  81631. }
  81632. return new BABYLON.Vector3(v.x, v.y, v.z);
  81633. };
  81634. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  81635. var v = impostor.physicsBody.angularVelocity;
  81636. if (!v) {
  81637. return null;
  81638. }
  81639. return new BABYLON.Vector3(v.x, v.y, v.z);
  81640. };
  81641. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  81642. impostor.physicsBody.mass = mass;
  81643. impostor.physicsBody.updateMassProperties();
  81644. };
  81645. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  81646. return impostor.physicsBody.mass;
  81647. };
  81648. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  81649. return impostor.physicsBody.material.friction;
  81650. };
  81651. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  81652. impostor.physicsBody.material.friction = friction;
  81653. };
  81654. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  81655. return impostor.physicsBody.material.restitution;
  81656. };
  81657. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  81658. impostor.physicsBody.material.restitution = restitution;
  81659. };
  81660. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  81661. impostor.physicsBody.sleep();
  81662. };
  81663. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  81664. impostor.physicsBody.wakeUp();
  81665. };
  81666. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  81667. joint.physicsJoint.distance = maxDistance;
  81668. };
  81669. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81670. // if (!motorIndex) {
  81671. // joint.physicsJoint.enableMotor();
  81672. // }
  81673. // }
  81674. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  81675. // if (!motorIndex) {
  81676. // joint.physicsJoint.disableMotor();
  81677. // }
  81678. // }
  81679. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  81680. if (!motorIndex) {
  81681. joint.physicsJoint.enableMotor();
  81682. joint.physicsJoint.setMotorSpeed(speed);
  81683. if (maxForce) {
  81684. this.setLimit(joint, maxForce);
  81685. }
  81686. }
  81687. };
  81688. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  81689. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  81690. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  81691. };
  81692. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  81693. var body = impostor.physicsBody;
  81694. mesh.position.x = body.position.x;
  81695. mesh.position.y = body.position.y;
  81696. mesh.position.z = body.position.z;
  81697. if (mesh.rotationQuaternion) {
  81698. mesh.rotationQuaternion.x = body.quaternion.x;
  81699. mesh.rotationQuaternion.y = body.quaternion.y;
  81700. mesh.rotationQuaternion.z = body.quaternion.z;
  81701. mesh.rotationQuaternion.w = body.quaternion.w;
  81702. }
  81703. };
  81704. CannonJSPlugin.prototype.getRadius = function (impostor) {
  81705. var shape = impostor.physicsBody.shapes[0];
  81706. return shape.boundingSphereRadius;
  81707. };
  81708. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  81709. var shape = impostor.physicsBody.shapes[0];
  81710. result.x = shape.halfExtents.x * 2;
  81711. result.y = shape.halfExtents.y * 2;
  81712. result.z = shape.halfExtents.z * 2;
  81713. };
  81714. CannonJSPlugin.prototype.dispose = function () {
  81715. };
  81716. CannonJSPlugin.prototype._extendNamespace = function () {
  81717. //this will force cannon to execute at least one step when using interpolation
  81718. var step_tmp1 = new this.BJSCANNON.Vec3();
  81719. var Engine = this.BJSCANNON;
  81720. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  81721. maxSubSteps = maxSubSteps || 10;
  81722. timeSinceLastCalled = timeSinceLastCalled || 0;
  81723. if (timeSinceLastCalled === 0) {
  81724. this.internalStep(dt);
  81725. this.time += dt;
  81726. }
  81727. else {
  81728. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  81729. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  81730. var t0 = performance.now();
  81731. for (var i = 0; i !== internalSteps; i++) {
  81732. this.internalStep(dt);
  81733. if (performance.now() - t0 > dt * 1000) {
  81734. break;
  81735. }
  81736. }
  81737. this.time += timeSinceLastCalled;
  81738. var h = this.time % dt;
  81739. var h_div_dt = h / dt;
  81740. var interpvelo = step_tmp1;
  81741. var bodies = this.bodies;
  81742. for (var j = 0; j !== bodies.length; j++) {
  81743. var b = bodies[j];
  81744. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  81745. b.position.vsub(b.previousPosition, interpvelo);
  81746. interpvelo.scale(h_div_dt, interpvelo);
  81747. b.position.vadd(interpvelo, b.interpolatedPosition);
  81748. }
  81749. else {
  81750. b.interpolatedPosition.copy(b.position);
  81751. b.interpolatedQuaternion.copy(b.quaternion);
  81752. }
  81753. }
  81754. }
  81755. };
  81756. };
  81757. return CannonJSPlugin;
  81758. }());
  81759. BABYLON.CannonJSPlugin = CannonJSPlugin;
  81760. })(BABYLON || (BABYLON = {}));
  81761. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  81762. "use strict";
  81763. var BABYLON;
  81764. (function (BABYLON) {
  81765. var OimoJSPlugin = /** @class */ (function () {
  81766. function OimoJSPlugin(iterations) {
  81767. this.name = "OimoJSPlugin";
  81768. this._tmpImpostorsArray = [];
  81769. this._tmpPositionVector = BABYLON.Vector3.Zero();
  81770. this.BJSOIMO = OIMO;
  81771. this.world = new this.BJSOIMO.World({
  81772. iterations: iterations
  81773. });
  81774. this.world.clear();
  81775. }
  81776. OimoJSPlugin.prototype.setGravity = function (gravity) {
  81777. this.world.gravity.copy(gravity);
  81778. };
  81779. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  81780. this.world.timeStep = timeStep;
  81781. };
  81782. OimoJSPlugin.prototype.getTimeStep = function () {
  81783. return this.world.timeStep;
  81784. };
  81785. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  81786. var _this = this;
  81787. impostors.forEach(function (impostor) {
  81788. impostor.beforeStep();
  81789. });
  81790. this.world.step();
  81791. impostors.forEach(function (impostor) {
  81792. impostor.afterStep();
  81793. //update the ordered impostors array
  81794. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  81795. });
  81796. //check for collisions
  81797. var contact = this.world.contacts;
  81798. while (contact !== null) {
  81799. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  81800. contact = contact.next;
  81801. continue;
  81802. }
  81803. //is this body colliding with any other? get the impostor
  81804. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  81805. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  81806. if (!mainImpostor || !collidingImpostor) {
  81807. contact = contact.next;
  81808. continue;
  81809. }
  81810. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  81811. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  81812. contact = contact.next;
  81813. }
  81814. };
  81815. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  81816. var mass = impostor.physicsBody.mass;
  81817. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  81818. };
  81819. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  81820. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  81821. this.applyImpulse(impostor, force, contactPoint);
  81822. };
  81823. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  81824. var _this = this;
  81825. //parent-child relationship. Does this impostor has a parent impostor?
  81826. if (impostor.parent) {
  81827. if (impostor.physicsBody) {
  81828. this.removePhysicsBody(impostor);
  81829. //TODO is that needed?
  81830. impostor.forceUpdate();
  81831. }
  81832. return;
  81833. }
  81834. if (impostor.isBodyInitRequired()) {
  81835. var bodyConfig = {
  81836. name: impostor.uniqueId,
  81837. //Oimo must have mass, also for static objects.
  81838. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  81839. size: [],
  81840. type: [],
  81841. pos: [],
  81842. posShape: [],
  81843. rot: [],
  81844. rotShape: [],
  81845. move: impostor.getParam("mass") !== 0,
  81846. density: impostor.getParam("mass"),
  81847. friction: impostor.getParam("friction"),
  81848. restitution: impostor.getParam("restitution"),
  81849. //Supporting older versions of Oimo
  81850. world: this.world
  81851. };
  81852. var impostors = [impostor];
  81853. var addToArray = function (parent) {
  81854. if (!parent.getChildMeshes)
  81855. return;
  81856. parent.getChildMeshes().forEach(function (m) {
  81857. if (m.physicsImpostor) {
  81858. impostors.push(m.physicsImpostor);
  81859. //m.physicsImpostor._init();
  81860. }
  81861. });
  81862. };
  81863. addToArray(impostor.object);
  81864. var checkWithEpsilon_1 = function (value) {
  81865. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  81866. };
  81867. impostors.forEach(function (i) {
  81868. if (!i.object.rotationQuaternion) {
  81869. return;
  81870. }
  81871. //get the correct bounding box
  81872. var oldQuaternion = i.object.rotationQuaternion;
  81873. var rot = oldQuaternion.toEulerAngles();
  81874. var extendSize = i.getObjectExtendSize();
  81875. var radToDeg = 57.295779513082320876;
  81876. if (i === impostor) {
  81877. var center = impostor.getObjectCenter();
  81878. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  81879. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  81880. //Can also use Array.prototype.push.apply
  81881. bodyConfig.pos.push(center.x);
  81882. bodyConfig.pos.push(center.y);
  81883. bodyConfig.pos.push(center.z);
  81884. bodyConfig.posShape.push(0, 0, 0);
  81885. //tmp solution
  81886. bodyConfig.rot.push(rot.x * radToDeg);
  81887. bodyConfig.rot.push(rot.y * radToDeg);
  81888. bodyConfig.rot.push(rot.z * radToDeg);
  81889. bodyConfig.rotShape.push(0, 0, 0);
  81890. }
  81891. else {
  81892. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  81893. bodyConfig.posShape.push(localPosition.x);
  81894. bodyConfig.posShape.push(localPosition.y);
  81895. bodyConfig.posShape.push(localPosition.z);
  81896. bodyConfig.pos.push(0, 0, 0);
  81897. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  81898. bodyConfig.rot.push(0);
  81899. bodyConfig.rot.push(0);
  81900. bodyConfig.rot.push(0);
  81901. bodyConfig.rotShape.push(rot.x * radToDeg);
  81902. bodyConfig.rotShape.push(rot.y * radToDeg);
  81903. bodyConfig.rotShape.push(rot.z * radToDeg);
  81904. }
  81905. // register mesh
  81906. switch (i.type) {
  81907. case BABYLON.PhysicsImpostor.ParticleImpostor:
  81908. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  81909. case BABYLON.PhysicsImpostor.SphereImpostor:
  81910. var radiusX = extendSize.x;
  81911. var radiusY = extendSize.y;
  81912. var radiusZ = extendSize.z;
  81913. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  81914. bodyConfig.type.push('sphere');
  81915. //due to the way oimo works with compounds, add 3 times
  81916. bodyConfig.size.push(size);
  81917. bodyConfig.size.push(size);
  81918. bodyConfig.size.push(size);
  81919. break;
  81920. case BABYLON.PhysicsImpostor.CylinderImpostor:
  81921. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  81922. var sizeY = checkWithEpsilon_1(extendSize.y);
  81923. bodyConfig.type.push('cylinder');
  81924. bodyConfig.size.push(sizeX);
  81925. bodyConfig.size.push(sizeY);
  81926. //due to the way oimo works with compounds, add one more value.
  81927. bodyConfig.size.push(sizeY);
  81928. break;
  81929. case BABYLON.PhysicsImpostor.PlaneImpostor:
  81930. case BABYLON.PhysicsImpostor.BoxImpostor:
  81931. default:
  81932. var sizeX = checkWithEpsilon_1(extendSize.x);
  81933. var sizeY = checkWithEpsilon_1(extendSize.y);
  81934. var sizeZ = checkWithEpsilon_1(extendSize.z);
  81935. bodyConfig.type.push('box');
  81936. //if (i === impostor) {
  81937. bodyConfig.size.push(sizeX);
  81938. bodyConfig.size.push(sizeY);
  81939. bodyConfig.size.push(sizeZ);
  81940. //} else {
  81941. // bodyConfig.size.push(0,0,0);
  81942. //}
  81943. break;
  81944. }
  81945. //actually not needed, but hey...
  81946. i.object.rotationQuaternion = oldQuaternion;
  81947. });
  81948. impostor.physicsBody = this.world.add(bodyConfig);
  81949. }
  81950. else {
  81951. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  81952. }
  81953. impostor.setDeltaPosition(this._tmpPositionVector);
  81954. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  81955. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  81956. };
  81957. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  81958. //impostor.physicsBody.dispose();
  81959. //Same as : (older oimo versions)
  81960. this.world.removeRigidBody(impostor.physicsBody);
  81961. };
  81962. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  81963. var mainBody = impostorJoint.mainImpostor.physicsBody;
  81964. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  81965. if (!mainBody || !connectedBody) {
  81966. return;
  81967. }
  81968. var jointData = impostorJoint.joint.jointData;
  81969. var options = jointData.nativeParams || {};
  81970. var type;
  81971. var nativeJointData = {
  81972. body1: mainBody,
  81973. body2: connectedBody,
  81974. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  81975. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  81976. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  81977. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  81978. min: options.min,
  81979. max: options.max,
  81980. collision: options.collision || jointData.collision,
  81981. spring: options.spring,
  81982. //supporting older version of Oimo
  81983. world: this.world
  81984. };
  81985. switch (impostorJoint.joint.type) {
  81986. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  81987. type = "jointBall";
  81988. break;
  81989. case BABYLON.PhysicsJoint.SpringJoint:
  81990. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  81991. var springData = jointData;
  81992. nativeJointData.min = springData.length || nativeJointData.min;
  81993. //Max should also be set, just make sure it is at least min
  81994. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  81995. case BABYLON.PhysicsJoint.DistanceJoint:
  81996. type = "jointDistance";
  81997. nativeJointData.max = jointData.maxDistance;
  81998. break;
  81999. case BABYLON.PhysicsJoint.PrismaticJoint:
  82000. type = "jointPrisme";
  82001. break;
  82002. case BABYLON.PhysicsJoint.SliderJoint:
  82003. type = "jointSlide";
  82004. break;
  82005. case BABYLON.PhysicsJoint.WheelJoint:
  82006. type = "jointWheel";
  82007. break;
  82008. case BABYLON.PhysicsJoint.HingeJoint:
  82009. default:
  82010. type = "jointHinge";
  82011. break;
  82012. }
  82013. nativeJointData.type = type;
  82014. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  82015. };
  82016. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82017. //Bug in Oimo prevents us from disposing a joint in the playground
  82018. //joint.joint.physicsJoint.dispose();
  82019. //So we will bruteforce it!
  82020. try {
  82021. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  82022. }
  82023. catch (e) {
  82024. BABYLON.Tools.Warn(e);
  82025. }
  82026. };
  82027. OimoJSPlugin.prototype.isSupported = function () {
  82028. return this.BJSOIMO !== undefined;
  82029. };
  82030. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82031. if (!impostor.physicsBody.sleeping) {
  82032. //TODO check that
  82033. /*if (impostor.physicsBody.shapes.next) {
  82034. var parentShape = this._getLastShape(impostor.physicsBody);
  82035. impostor.object.position.copyFrom(parentShape.position);
  82036. console.log(parentShape.position);
  82037. } else {*/
  82038. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  82039. //}
  82040. if (impostor.object.rotationQuaternion) {
  82041. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  82042. }
  82043. }
  82044. };
  82045. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82046. var body = impostor.physicsBody;
  82047. body.position.copy(newPosition);
  82048. body.orientation.copy(newRotation);
  82049. body.syncShapes();
  82050. body.awake();
  82051. };
  82052. /*private _getLastShape(body: any): any {
  82053. var lastShape = body.shapes;
  82054. while (lastShape.next) {
  82055. lastShape = lastShape.next;
  82056. }
  82057. return lastShape;
  82058. }*/
  82059. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82060. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  82061. };
  82062. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82063. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  82064. };
  82065. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82066. var v = impostor.physicsBody.linearVelocity;
  82067. if (!v) {
  82068. return null;
  82069. }
  82070. return new BABYLON.Vector3(v.x, v.y, v.z);
  82071. };
  82072. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82073. var v = impostor.physicsBody.angularVelocity;
  82074. if (!v) {
  82075. return null;
  82076. }
  82077. return new BABYLON.Vector3(v.x, v.y, v.z);
  82078. };
  82079. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82080. var staticBody = mass === 0;
  82081. //this will actually set the body's density and not its mass.
  82082. //But this is how oimo treats the mass variable.
  82083. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  82084. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  82085. };
  82086. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  82087. return impostor.physicsBody.shapes.density;
  82088. };
  82089. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  82090. return impostor.physicsBody.shapes.friction;
  82091. };
  82092. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82093. impostor.physicsBody.shapes.friction = friction;
  82094. };
  82095. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82096. return impostor.physicsBody.shapes.restitution;
  82097. };
  82098. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82099. impostor.physicsBody.shapes.restitution = restitution;
  82100. };
  82101. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  82102. impostor.physicsBody.sleep();
  82103. };
  82104. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  82105. impostor.physicsBody.awake();
  82106. };
  82107. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82108. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  82109. if (minDistance !== void 0) {
  82110. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  82111. }
  82112. };
  82113. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82114. //TODO separate rotational and transational motors.
  82115. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82116. if (motor) {
  82117. motor.setMotor(speed, maxForce);
  82118. }
  82119. };
  82120. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  82121. //TODO separate rotational and transational motors.
  82122. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  82123. if (motor) {
  82124. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  82125. }
  82126. };
  82127. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82128. var body = impostor.physicsBody;
  82129. mesh.position.x = body.position.x;
  82130. mesh.position.y = body.position.y;
  82131. mesh.position.z = body.position.z;
  82132. if (mesh.rotationQuaternion) {
  82133. mesh.rotationQuaternion.x = body.orientation.x;
  82134. mesh.rotationQuaternion.y = body.orientation.y;
  82135. mesh.rotationQuaternion.z = body.orientation.z;
  82136. mesh.rotationQuaternion.w = body.orientation.s;
  82137. }
  82138. };
  82139. OimoJSPlugin.prototype.getRadius = function (impostor) {
  82140. return impostor.physicsBody.shapes.radius;
  82141. };
  82142. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82143. var shape = impostor.physicsBody.shapes;
  82144. result.x = shape.halfWidth * 2;
  82145. result.y = shape.halfHeight * 2;
  82146. result.z = shape.halfDepth * 2;
  82147. };
  82148. OimoJSPlugin.prototype.dispose = function () {
  82149. this.world.clear();
  82150. };
  82151. return OimoJSPlugin;
  82152. }());
  82153. BABYLON.OimoJSPlugin = OimoJSPlugin;
  82154. })(BABYLON || (BABYLON = {}));
  82155. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  82156. "use strict";
  82157. var BABYLON;
  82158. (function (BABYLON) {
  82159. /*
  82160. * Based on jsTGALoader - Javascript loader for TGA file
  82161. * By Vincent Thibault
  82162. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  82163. */
  82164. var TGATools = /** @class */ (function () {
  82165. function TGATools() {
  82166. }
  82167. TGATools.GetTGAHeader = function (data) {
  82168. var offset = 0;
  82169. var header = {
  82170. id_length: data[offset++],
  82171. colormap_type: data[offset++],
  82172. image_type: data[offset++],
  82173. colormap_index: data[offset++] | data[offset++] << 8,
  82174. colormap_length: data[offset++] | data[offset++] << 8,
  82175. colormap_size: data[offset++],
  82176. origin: [
  82177. data[offset++] | data[offset++] << 8,
  82178. data[offset++] | data[offset++] << 8
  82179. ],
  82180. width: data[offset++] | data[offset++] << 8,
  82181. height: data[offset++] | data[offset++] << 8,
  82182. pixel_size: data[offset++],
  82183. flags: data[offset++]
  82184. };
  82185. return header;
  82186. };
  82187. TGATools.UploadContent = function (gl, data) {
  82188. // Not enough data to contain header ?
  82189. if (data.length < 19) {
  82190. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  82191. return;
  82192. }
  82193. // Read Header
  82194. var offset = 18;
  82195. var header = TGATools.GetTGAHeader(data);
  82196. // Assume it's a valid Targa file.
  82197. if (header.id_length + offset > data.length) {
  82198. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  82199. return;
  82200. }
  82201. // Skip not needed data
  82202. offset += header.id_length;
  82203. var use_rle = false;
  82204. var use_pal = false;
  82205. var use_grey = false;
  82206. // Get some informations.
  82207. switch (header.image_type) {
  82208. case TGATools._TYPE_RLE_INDEXED:
  82209. use_rle = true;
  82210. case TGATools._TYPE_INDEXED:
  82211. use_pal = true;
  82212. break;
  82213. case TGATools._TYPE_RLE_RGB:
  82214. use_rle = true;
  82215. case TGATools._TYPE_RGB:
  82216. // use_rgb = true;
  82217. break;
  82218. case TGATools._TYPE_RLE_GREY:
  82219. use_rle = true;
  82220. case TGATools._TYPE_GREY:
  82221. use_grey = true;
  82222. break;
  82223. }
  82224. var pixel_data;
  82225. // var numAlphaBits = header.flags & 0xf;
  82226. var pixel_size = header.pixel_size >> 3;
  82227. var pixel_total = header.width * header.height * pixel_size;
  82228. // Read palettes
  82229. var palettes;
  82230. if (use_pal) {
  82231. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  82232. }
  82233. // Read LRE
  82234. if (use_rle) {
  82235. pixel_data = new Uint8Array(pixel_total);
  82236. var c, count, i;
  82237. var localOffset = 0;
  82238. var pixels = new Uint8Array(pixel_size);
  82239. while (offset < pixel_total && localOffset < pixel_total) {
  82240. c = data[offset++];
  82241. count = (c & 0x7f) + 1;
  82242. // RLE pixels
  82243. if (c & 0x80) {
  82244. // Bind pixel tmp array
  82245. for (i = 0; i < pixel_size; ++i) {
  82246. pixels[i] = data[offset++];
  82247. }
  82248. // Copy pixel array
  82249. for (i = 0; i < count; ++i) {
  82250. pixel_data.set(pixels, localOffset + i * pixel_size);
  82251. }
  82252. localOffset += pixel_size * count;
  82253. }
  82254. else {
  82255. count *= pixel_size;
  82256. for (i = 0; i < count; ++i) {
  82257. pixel_data[localOffset + i] = data[offset++];
  82258. }
  82259. localOffset += count;
  82260. }
  82261. }
  82262. }
  82263. else {
  82264. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  82265. }
  82266. // Load to texture
  82267. var x_start, y_start, x_step, y_step, y_end, x_end;
  82268. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  82269. default:
  82270. case TGATools._ORIGIN_UL:
  82271. x_start = 0;
  82272. x_step = 1;
  82273. x_end = header.width;
  82274. y_start = 0;
  82275. y_step = 1;
  82276. y_end = header.height;
  82277. break;
  82278. case TGATools._ORIGIN_BL:
  82279. x_start = 0;
  82280. x_step = 1;
  82281. x_end = header.width;
  82282. y_start = header.height - 1;
  82283. y_step = -1;
  82284. y_end = -1;
  82285. break;
  82286. case TGATools._ORIGIN_UR:
  82287. x_start = header.width - 1;
  82288. x_step = -1;
  82289. x_end = -1;
  82290. y_start = 0;
  82291. y_step = 1;
  82292. y_end = header.height;
  82293. break;
  82294. case TGATools._ORIGIN_BR:
  82295. x_start = header.width - 1;
  82296. x_step = -1;
  82297. x_end = -1;
  82298. y_start = header.height - 1;
  82299. y_step = -1;
  82300. y_end = -1;
  82301. break;
  82302. }
  82303. // Load the specify method
  82304. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  82305. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  82306. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  82307. };
  82308. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82309. var image = pixel_data, colormap = palettes;
  82310. var width = header.width, height = header.height;
  82311. var color, i = 0, x, y;
  82312. var imageData = new Uint8Array(width * height * 4);
  82313. for (y = y_start; y !== y_end; y += y_step) {
  82314. for (x = x_start; x !== x_end; x += x_step, i++) {
  82315. color = image[i];
  82316. imageData[(x + width * y) * 4 + 3] = 255;
  82317. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  82318. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  82319. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  82320. }
  82321. }
  82322. return imageData;
  82323. };
  82324. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82325. var image = pixel_data;
  82326. var width = header.width, height = header.height;
  82327. var color, i = 0, x, y;
  82328. var imageData = new Uint8Array(width * height * 4);
  82329. for (y = y_start; y !== y_end; y += y_step) {
  82330. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82331. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  82332. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  82333. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  82334. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  82335. imageData[(x + width * y) * 4 + 0] = r;
  82336. imageData[(x + width * y) * 4 + 1] = g;
  82337. imageData[(x + width * y) * 4 + 2] = b;
  82338. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  82339. }
  82340. }
  82341. return imageData;
  82342. };
  82343. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82344. var image = pixel_data;
  82345. var width = header.width, height = header.height;
  82346. var i = 0, x, y;
  82347. var imageData = new Uint8Array(width * height * 4);
  82348. for (y = y_start; y !== y_end; y += y_step) {
  82349. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  82350. imageData[(x + width * y) * 4 + 3] = 255;
  82351. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82352. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82353. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82354. }
  82355. }
  82356. return imageData;
  82357. };
  82358. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82359. var image = pixel_data;
  82360. var width = header.width, height = header.height;
  82361. var i = 0, x, y;
  82362. var imageData = new Uint8Array(width * height * 4);
  82363. for (y = y_start; y !== y_end; y += y_step) {
  82364. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  82365. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82366. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  82367. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  82368. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  82369. }
  82370. }
  82371. return imageData;
  82372. };
  82373. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82374. var image = pixel_data;
  82375. var width = header.width, height = header.height;
  82376. var color, i = 0, x, y;
  82377. var imageData = new Uint8Array(width * height * 4);
  82378. for (y = y_start; y !== y_end; y += y_step) {
  82379. for (x = x_start; x !== x_end; x += x_step, i++) {
  82380. color = image[i];
  82381. imageData[(x + width * y) * 4 + 0] = color;
  82382. imageData[(x + width * y) * 4 + 1] = color;
  82383. imageData[(x + width * y) * 4 + 2] = color;
  82384. imageData[(x + width * y) * 4 + 3] = 255;
  82385. }
  82386. }
  82387. return imageData;
  82388. };
  82389. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  82390. var image = pixel_data;
  82391. var width = header.width, height = header.height;
  82392. var i = 0, x, y;
  82393. var imageData = new Uint8Array(width * height * 4);
  82394. for (y = y_start; y !== y_end; y += y_step) {
  82395. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  82396. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  82397. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  82398. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  82399. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  82400. }
  82401. }
  82402. return imageData;
  82403. };
  82404. //private static _TYPE_NO_DATA = 0;
  82405. TGATools._TYPE_INDEXED = 1;
  82406. TGATools._TYPE_RGB = 2;
  82407. TGATools._TYPE_GREY = 3;
  82408. TGATools._TYPE_RLE_INDEXED = 9;
  82409. TGATools._TYPE_RLE_RGB = 10;
  82410. TGATools._TYPE_RLE_GREY = 11;
  82411. TGATools._ORIGIN_MASK = 0x30;
  82412. TGATools._ORIGIN_SHIFT = 0x04;
  82413. TGATools._ORIGIN_BL = 0x00;
  82414. TGATools._ORIGIN_BR = 0x01;
  82415. TGATools._ORIGIN_UL = 0x02;
  82416. TGATools._ORIGIN_UR = 0x03;
  82417. return TGATools;
  82418. }());
  82419. BABYLON.TGATools = TGATools;
  82420. })(BABYLON || (BABYLON = {}));
  82421. //# sourceMappingURL=babylon.tga.js.map
  82422. "use strict";
  82423. var BABYLON;
  82424. (function (BABYLON) {
  82425. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  82426. // All values and structures referenced from:
  82427. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  82428. var DDS_MAGIC = 0x20534444;
  82429. var
  82430. //DDSD_CAPS = 0x1,
  82431. //DDSD_HEIGHT = 0x2,
  82432. //DDSD_WIDTH = 0x4,
  82433. //DDSD_PITCH = 0x8,
  82434. //DDSD_PIXELFORMAT = 0x1000,
  82435. DDSD_MIPMAPCOUNT = 0x20000;
  82436. //DDSD_LINEARSIZE = 0x80000,
  82437. //DDSD_DEPTH = 0x800000;
  82438. // var DDSCAPS_COMPLEX = 0x8,
  82439. // DDSCAPS_MIPMAP = 0x400000,
  82440. // DDSCAPS_TEXTURE = 0x1000;
  82441. var DDSCAPS2_CUBEMAP = 0x200;
  82442. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  82443. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  82444. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  82445. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  82446. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  82447. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  82448. // DDSCAPS2_VOLUME = 0x200000;
  82449. var
  82450. //DDPF_ALPHAPIXELS = 0x1,
  82451. //DDPF_ALPHA = 0x2,
  82452. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  82453. //DDPF_YUV = 0x200,
  82454. DDPF_LUMINANCE = 0x20000;
  82455. function FourCCToInt32(value) {
  82456. return value.charCodeAt(0) +
  82457. (value.charCodeAt(1) << 8) +
  82458. (value.charCodeAt(2) << 16) +
  82459. (value.charCodeAt(3) << 24);
  82460. }
  82461. function Int32ToFourCC(value) {
  82462. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  82463. }
  82464. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  82465. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  82466. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  82467. var FOURCC_DX10 = FourCCToInt32("DX10");
  82468. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  82469. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  82470. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  82471. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  82472. var headerLengthInt = 31; // The header length in 32 bit ints
  82473. // Offsets into the header array
  82474. var off_magic = 0;
  82475. var off_size = 1;
  82476. var off_flags = 2;
  82477. var off_height = 3;
  82478. var off_width = 4;
  82479. var off_mipmapCount = 7;
  82480. var off_pfFlags = 20;
  82481. var off_pfFourCC = 21;
  82482. var off_RGBbpp = 22;
  82483. var off_RMask = 23;
  82484. var off_GMask = 24;
  82485. var off_BMask = 25;
  82486. var off_AMask = 26;
  82487. // var off_caps1 = 27;
  82488. var off_caps2 = 28;
  82489. // var off_caps3 = 29;
  82490. // var off_caps4 = 30;
  82491. var off_dxgiFormat = 32;
  82492. ;
  82493. var DDSTools = /** @class */ (function () {
  82494. function DDSTools() {
  82495. }
  82496. DDSTools.GetDDSInfo = function (arrayBuffer) {
  82497. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82498. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  82499. var mipmapCount = 1;
  82500. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  82501. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82502. }
  82503. var fourCC = header[off_pfFourCC];
  82504. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  82505. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82506. switch (fourCC) {
  82507. case FOURCC_D3DFMT_R16G16B16A16F:
  82508. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82509. break;
  82510. case FOURCC_D3DFMT_R32G32B32A32F:
  82511. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82512. break;
  82513. case FOURCC_DX10:
  82514. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  82515. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82516. break;
  82517. }
  82518. }
  82519. return {
  82520. width: header[off_width],
  82521. height: header[off_height],
  82522. mipmapCount: mipmapCount,
  82523. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  82524. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  82525. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  82526. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  82527. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  82528. dxgiFormat: dxgiFormat,
  82529. textureType: textureType
  82530. };
  82531. };
  82532. DDSTools._ToHalfFloat = function (value) {
  82533. if (!DDSTools._FloatView) {
  82534. DDSTools._FloatView = new Float32Array(1);
  82535. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  82536. }
  82537. DDSTools._FloatView[0] = value;
  82538. var x = DDSTools._Int32View[0];
  82539. var bits = (x >> 16) & 0x8000; /* Get the sign */
  82540. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  82541. var e = (x >> 23) & 0xff; /* Using int is faster here */
  82542. /* If zero, or denormal, or exponent underflows too much for a denormal
  82543. * half, return signed zero. */
  82544. if (e < 103) {
  82545. return bits;
  82546. }
  82547. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  82548. if (e > 142) {
  82549. bits |= 0x7c00;
  82550. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  82551. * not Inf, so make sure we set one mantissa bit too. */
  82552. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  82553. return bits;
  82554. }
  82555. /* If exponent underflows but not too much, return a denormal */
  82556. if (e < 113) {
  82557. m |= 0x0800;
  82558. /* Extra rounding may overflow and set mantissa to 0 and exponent
  82559. * to 1, which is OK. */
  82560. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  82561. return bits;
  82562. }
  82563. bits |= ((e - 112) << 10) | (m >> 1);
  82564. bits += m & 1;
  82565. return bits;
  82566. };
  82567. DDSTools._FromHalfFloat = function (value) {
  82568. var s = (value & 0x8000) >> 15;
  82569. var e = (value & 0x7C00) >> 10;
  82570. var f = value & 0x03FF;
  82571. if (e === 0) {
  82572. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  82573. }
  82574. else if (e == 0x1F) {
  82575. return f ? NaN : ((s ? -1 : 1) * Infinity);
  82576. }
  82577. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  82578. };
  82579. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82580. var destArray = new Float32Array(dataLength);
  82581. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82582. var index = 0;
  82583. for (var y = 0; y < height; y++) {
  82584. for (var x = 0; x < width; x++) {
  82585. var srcPos = (x + y * width) * 4;
  82586. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  82587. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  82588. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  82589. if (DDSTools.StoreLODInAlphaChannel) {
  82590. destArray[index + 3] = lod;
  82591. }
  82592. else {
  82593. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  82594. }
  82595. index += 4;
  82596. }
  82597. }
  82598. return destArray;
  82599. };
  82600. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82601. if (DDSTools.StoreLODInAlphaChannel) {
  82602. var destArray = new Uint16Array(dataLength);
  82603. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82604. var index = 0;
  82605. for (var y = 0; y < height; y++) {
  82606. for (var x = 0; x < width; x++) {
  82607. var srcPos = (x + y * width) * 4;
  82608. destArray[index] = srcData[srcPos];
  82609. destArray[index + 1] = srcData[srcPos + 1];
  82610. destArray[index + 2] = srcData[srcPos + 2];
  82611. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  82612. index += 4;
  82613. }
  82614. }
  82615. return destArray;
  82616. }
  82617. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  82618. };
  82619. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82620. if (DDSTools.StoreLODInAlphaChannel) {
  82621. var destArray = new Float32Array(dataLength);
  82622. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82623. var index = 0;
  82624. for (var y = 0; y < height; y++) {
  82625. for (var x = 0; x < width; x++) {
  82626. var srcPos = (x + y * width) * 4;
  82627. destArray[index] = srcData[srcPos];
  82628. destArray[index + 1] = srcData[srcPos + 1];
  82629. destArray[index + 2] = srcData[srcPos + 2];
  82630. destArray[index + 3] = lod;
  82631. index += 4;
  82632. }
  82633. }
  82634. return destArray;
  82635. }
  82636. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  82637. };
  82638. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82639. var destArray = new Uint8Array(dataLength);
  82640. var srcData = new Float32Array(arrayBuffer, dataOffset);
  82641. var index = 0;
  82642. for (var y = 0; y < height; y++) {
  82643. for (var x = 0; x < width; x++) {
  82644. var srcPos = (x + y * width) * 4;
  82645. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  82646. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  82647. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  82648. if (DDSTools.StoreLODInAlphaChannel) {
  82649. destArray[index + 3] = lod;
  82650. }
  82651. else {
  82652. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  82653. }
  82654. index += 4;
  82655. }
  82656. }
  82657. return destArray;
  82658. };
  82659. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  82660. var destArray = new Uint8Array(dataLength);
  82661. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  82662. var index = 0;
  82663. for (var y = 0; y < height; y++) {
  82664. for (var x = 0; x < width; x++) {
  82665. var srcPos = (x + y * width) * 4;
  82666. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  82667. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  82668. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  82669. if (DDSTools.StoreLODInAlphaChannel) {
  82670. destArray[index + 3] = lod;
  82671. }
  82672. else {
  82673. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  82674. }
  82675. index += 4;
  82676. }
  82677. }
  82678. return destArray;
  82679. };
  82680. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  82681. var byteArray = new Uint8Array(dataLength);
  82682. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82683. var index = 0;
  82684. for (var y = 0; y < height; y++) {
  82685. for (var x = 0; x < width; x++) {
  82686. var srcPos = (x + y * width) * 4;
  82687. byteArray[index] = srcData[srcPos + rOffset];
  82688. byteArray[index + 1] = srcData[srcPos + gOffset];
  82689. byteArray[index + 2] = srcData[srcPos + bOffset];
  82690. byteArray[index + 3] = srcData[srcPos + aOffset];
  82691. index += 4;
  82692. }
  82693. }
  82694. return byteArray;
  82695. };
  82696. DDSTools._ExtractLongWordOrder = function (value) {
  82697. if (value === 0 || value === 255 || value === -16777216) {
  82698. return 0;
  82699. }
  82700. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  82701. };
  82702. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  82703. var byteArray = new Uint8Array(dataLength);
  82704. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82705. var index = 0;
  82706. for (var y = 0; y < height; y++) {
  82707. for (var x = 0; x < width; x++) {
  82708. var srcPos = (x + y * width) * 3;
  82709. byteArray[index] = srcData[srcPos + rOffset];
  82710. byteArray[index + 1] = srcData[srcPos + gOffset];
  82711. byteArray[index + 2] = srcData[srcPos + bOffset];
  82712. index += 3;
  82713. }
  82714. }
  82715. return byteArray;
  82716. };
  82717. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  82718. var byteArray = new Uint8Array(dataLength);
  82719. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  82720. var index = 0;
  82721. for (var y = 0; y < height; y++) {
  82722. for (var x = 0; x < width; x++) {
  82723. var srcPos = (x + y * width);
  82724. byteArray[index] = srcData[srcPos];
  82725. index++;
  82726. }
  82727. }
  82728. return byteArray;
  82729. };
  82730. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  82731. if (lodIndex === void 0) { lodIndex = -1; }
  82732. var ext = engine.getCaps().s3tc;
  82733. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  82734. var fourCC, width, height, dataLength = 0, dataOffset;
  82735. var byteArray, mipmapCount, mip;
  82736. var internalFormat = 0;
  82737. var format = 0;
  82738. var blockBytes = 1;
  82739. if (header[off_magic] !== DDS_MAGIC) {
  82740. BABYLON.Tools.Error("Invalid magic number in DDS header");
  82741. return;
  82742. }
  82743. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  82744. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  82745. return;
  82746. }
  82747. if (info.isCompressed && !ext) {
  82748. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  82749. return;
  82750. }
  82751. var bpp = header[off_RGBbpp];
  82752. dataOffset = header[off_size] + 4;
  82753. var computeFormats = false;
  82754. if (info.isFourCC) {
  82755. fourCC = header[off_pfFourCC];
  82756. switch (fourCC) {
  82757. case FOURCC_DXT1:
  82758. blockBytes = 8;
  82759. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  82760. break;
  82761. case FOURCC_DXT3:
  82762. blockBytes = 16;
  82763. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  82764. break;
  82765. case FOURCC_DXT5:
  82766. blockBytes = 16;
  82767. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  82768. break;
  82769. case FOURCC_D3DFMT_R16G16B16A16F:
  82770. computeFormats = true;
  82771. break;
  82772. case FOURCC_D3DFMT_R32G32B32A32F:
  82773. computeFormats = true;
  82774. break;
  82775. case FOURCC_DX10:
  82776. // There is an additionnal header so dataOffset need to be changed
  82777. dataOffset += 5 * 4; // 5 uints
  82778. var supported = false;
  82779. switch (info.dxgiFormat) {
  82780. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  82781. computeFormats = true;
  82782. supported = true;
  82783. break;
  82784. case DXGI_FORMAT_B8G8R8X8_UNORM:
  82785. info.isRGB = true;
  82786. info.isFourCC = false;
  82787. bpp = 32;
  82788. supported = true;
  82789. break;
  82790. }
  82791. if (supported) {
  82792. break;
  82793. }
  82794. default:
  82795. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  82796. return;
  82797. }
  82798. }
  82799. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  82800. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  82801. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  82802. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  82803. if (computeFormats) {
  82804. format = engine._getWebGLTextureType(info.textureType);
  82805. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82806. }
  82807. mipmapCount = 1;
  82808. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  82809. mipmapCount = Math.max(1, header[off_mipmapCount]);
  82810. }
  82811. for (var face = 0; face < faces; face++) {
  82812. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  82813. width = header[off_width];
  82814. height = header[off_height];
  82815. for (mip = 0; mip < mipmapCount; ++mip) {
  82816. if (lodIndex === -1 || lodIndex === mip) {
  82817. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  82818. var i = (lodIndex === -1) ? mip : 0;
  82819. if (!info.isCompressed && info.isFourCC) {
  82820. dataLength = width * height * 4;
  82821. var floatArray = null;
  82822. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  82823. if (bpp === 128) {
  82824. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82825. }
  82826. else if (bpp === 64) {
  82827. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82828. }
  82829. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82830. format = engine._getWebGLTextureType(info.textureType);
  82831. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82832. }
  82833. else {
  82834. if (bpp === 128) {
  82835. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82836. }
  82837. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  82838. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82839. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82840. format = engine._getWebGLTextureType(info.textureType);
  82841. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  82842. }
  82843. else {
  82844. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  82845. }
  82846. }
  82847. if (floatArray) {
  82848. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  82849. }
  82850. }
  82851. else if (info.isRGB) {
  82852. if (bpp === 24) {
  82853. dataLength = width * height * 3;
  82854. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  82855. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  82856. }
  82857. else {
  82858. dataLength = width * height * 4;
  82859. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  82860. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  82861. }
  82862. }
  82863. else if (info.isLuminance) {
  82864. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  82865. var unpaddedRowSize = width;
  82866. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  82867. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  82868. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  82869. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  82870. }
  82871. else {
  82872. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  82873. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  82874. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  82875. }
  82876. }
  82877. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  82878. width *= 0.5;
  82879. height *= 0.5;
  82880. width = Math.max(1.0, width);
  82881. height = Math.max(1.0, height);
  82882. }
  82883. if (currentFace !== undefined) {
  82884. // Loading a single face
  82885. break;
  82886. }
  82887. }
  82888. };
  82889. DDSTools.StoreLODInAlphaChannel = false;
  82890. return DDSTools;
  82891. }());
  82892. BABYLON.DDSTools = DDSTools;
  82893. })(BABYLON || (BABYLON = {}));
  82894. //# sourceMappingURL=babylon.dds.js.map
  82895. "use strict";
  82896. var BABYLON;
  82897. (function (BABYLON) {
  82898. /**
  82899. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  82900. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  82901. */
  82902. var KhronosTextureContainer = /** @class */ (function () {
  82903. /**
  82904. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  82905. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  82906. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  82907. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  82908. */
  82909. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  82910. this.arrayBuffer = arrayBuffer;
  82911. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  82912. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  82913. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  82914. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  82915. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  82916. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  82917. BABYLON.Tools.Error("texture missing KTX identifier");
  82918. return;
  82919. }
  82920. // load the reset of the header in native 32 bit int
  82921. var header = new Int32Array(this.arrayBuffer, 12, 13);
  82922. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  82923. var oppositeEndianess = header[0] === 0x01020304;
  82924. // read all the header elements in order they exist in the file, without modification (sans endainness)
  82925. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  82926. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  82927. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  82928. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  82929. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  82930. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  82931. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  82932. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  82933. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  82934. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  82935. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  82936. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  82937. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  82938. if (this.glType !== 0) {
  82939. BABYLON.Tools.Error("only compressed formats currently supported");
  82940. return;
  82941. }
  82942. else {
  82943. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  82944. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  82945. }
  82946. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  82947. BABYLON.Tools.Error("only 2D textures currently supported");
  82948. return;
  82949. }
  82950. if (this.numberOfArrayElements !== 0) {
  82951. BABYLON.Tools.Error("texture arrays not currently supported");
  82952. return;
  82953. }
  82954. if (this.numberOfFaces !== facesExpected) {
  82955. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  82956. return;
  82957. }
  82958. // we now have a completely validated file, so could use existence of loadType as success
  82959. // would need to make this more elaborate & adjust checks above to support more than one load type
  82960. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  82961. }
  82962. // not as fast hardware based, but will probably never need to use
  82963. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  82964. return ((val & 0xFF) << 24)
  82965. | ((val & 0xFF00) << 8)
  82966. | ((val >> 8) & 0xFF00)
  82967. | ((val >> 24) & 0xFF);
  82968. };
  82969. /**
  82970. * It is assumed that the texture has already been created & is currently bound
  82971. */
  82972. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  82973. switch (this.loadType) {
  82974. case KhronosTextureContainer.COMPRESSED_2D:
  82975. this._upload2DCompressedLevels(gl, loadMipmaps);
  82976. break;
  82977. case KhronosTextureContainer.TEX_2D:
  82978. case KhronosTextureContainer.COMPRESSED_3D:
  82979. case KhronosTextureContainer.TEX_3D:
  82980. }
  82981. };
  82982. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  82983. // initialize width & height for level 1
  82984. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  82985. var width = this.pixelWidth;
  82986. var height = this.pixelHeight;
  82987. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  82988. for (var level = 0; level < mipmapCount; level++) {
  82989. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  82990. for (var face = 0; face < this.numberOfFaces; face++) {
  82991. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  82992. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  82993. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  82994. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  82995. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  82996. }
  82997. width = Math.max(1.0, width * 0.5);
  82998. height = Math.max(1.0, height * 0.5);
  82999. }
  83000. };
  83001. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  83002. // load types
  83003. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  83004. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  83005. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  83006. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  83007. return KhronosTextureContainer;
  83008. }());
  83009. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  83010. })(BABYLON || (BABYLON = {}));
  83011. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  83012. "use strict";
  83013. var BABYLON;
  83014. (function (BABYLON) {
  83015. var Debug;
  83016. (function (Debug) {
  83017. /**
  83018. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  83019. */
  83020. var SkeletonViewer = /** @class */ (function () {
  83021. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  83022. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  83023. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  83024. this.skeleton = skeleton;
  83025. this.mesh = mesh;
  83026. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  83027. this.renderingGroupId = renderingGroupId;
  83028. this.color = BABYLON.Color3.White();
  83029. this._debugLines = new Array();
  83030. this._isEnabled = false;
  83031. this._scene = scene;
  83032. this.update();
  83033. this._renderFunction = this.update.bind(this);
  83034. }
  83035. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  83036. get: function () {
  83037. return this._isEnabled;
  83038. },
  83039. set: function (value) {
  83040. if (this._isEnabled === value) {
  83041. return;
  83042. }
  83043. this._isEnabled = value;
  83044. if (value) {
  83045. this._scene.registerBeforeRender(this._renderFunction);
  83046. }
  83047. else {
  83048. this._scene.unregisterBeforeRender(this._renderFunction);
  83049. }
  83050. },
  83051. enumerable: true,
  83052. configurable: true
  83053. });
  83054. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  83055. if (x === void 0) { x = 0; }
  83056. if (y === void 0) { y = 0; }
  83057. if (z === void 0) { z = 0; }
  83058. var tmat = BABYLON.Tmp.Matrix[0];
  83059. var parentBone = bone.getParent();
  83060. tmat.copyFrom(bone.getLocalMatrix());
  83061. if (x !== 0 || y !== 0 || z !== 0) {
  83062. var tmat2 = BABYLON.Tmp.Matrix[1];
  83063. BABYLON.Matrix.IdentityToRef(tmat2);
  83064. tmat2.m[12] = x;
  83065. tmat2.m[13] = y;
  83066. tmat2.m[14] = z;
  83067. tmat2.multiplyToRef(tmat, tmat);
  83068. }
  83069. if (parentBone) {
  83070. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  83071. }
  83072. tmat.multiplyToRef(meshMat, tmat);
  83073. position.x = tmat.m[12];
  83074. position.y = tmat.m[13];
  83075. position.z = tmat.m[14];
  83076. };
  83077. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  83078. var len = bones.length;
  83079. var meshPos = this.mesh.position;
  83080. for (var i = 0; i < len; i++) {
  83081. var bone = bones[i];
  83082. var points = this._debugLines[i];
  83083. if (!points) {
  83084. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83085. this._debugLines[i] = points;
  83086. }
  83087. this._getBonePosition(points[0], bone, meshMat);
  83088. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  83089. points[0].subtractInPlace(meshPos);
  83090. points[1].subtractInPlace(meshPos);
  83091. }
  83092. };
  83093. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  83094. var len = bones.length;
  83095. var boneNum = 0;
  83096. var meshPos = this.mesh.position;
  83097. for (var i = len - 1; i >= 0; i--) {
  83098. var childBone = bones[i];
  83099. var parentBone = childBone.getParent();
  83100. if (!parentBone) {
  83101. continue;
  83102. }
  83103. var points = this._debugLines[boneNum];
  83104. if (!points) {
  83105. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83106. this._debugLines[boneNum] = points;
  83107. }
  83108. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  83109. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  83110. points[0].subtractInPlace(meshPos);
  83111. points[1].subtractInPlace(meshPos);
  83112. boneNum++;
  83113. }
  83114. };
  83115. SkeletonViewer.prototype.update = function () {
  83116. if (this.autoUpdateBonesMatrices) {
  83117. this.skeleton.computeAbsoluteTransforms();
  83118. }
  83119. if (this.skeleton.bones[0].length === undefined) {
  83120. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83121. }
  83122. else {
  83123. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  83124. }
  83125. if (!this._debugMesh) {
  83126. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  83127. this._debugMesh.renderingGroupId = this.renderingGroupId;
  83128. }
  83129. else {
  83130. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  83131. }
  83132. this._debugMesh.position.copyFrom(this.mesh.position);
  83133. this._debugMesh.color = this.color;
  83134. };
  83135. SkeletonViewer.prototype.dispose = function () {
  83136. if (this._debugMesh) {
  83137. this.isEnabled = false;
  83138. this._debugMesh.dispose();
  83139. this._debugMesh = null;
  83140. }
  83141. };
  83142. return SkeletonViewer;
  83143. }());
  83144. Debug.SkeletonViewer = SkeletonViewer;
  83145. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83146. })(BABYLON || (BABYLON = {}));
  83147. //# sourceMappingURL=babylon.skeletonViewer.js.map
  83148. "use strict";
  83149. /**
  83150. * Module Debug contains the (visual) components to debug a scene correctly
  83151. */
  83152. var BABYLON;
  83153. (function (BABYLON) {
  83154. var Debug;
  83155. (function (Debug) {
  83156. /**
  83157. * The Axes viewer will show 3 axes in a specific point in space
  83158. */
  83159. var AxesViewer = /** @class */ (function () {
  83160. function AxesViewer(scene, scaleLines) {
  83161. if (scaleLines === void 0) { scaleLines = 1; }
  83162. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83163. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83164. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83165. this.scaleLines = 1;
  83166. this.scaleLines = scaleLines;
  83167. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  83168. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  83169. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  83170. this._xmesh.renderingGroupId = 2;
  83171. this._ymesh.renderingGroupId = 2;
  83172. this._zmesh.renderingGroupId = 2;
  83173. this._xmesh.material.checkReadyOnlyOnce = true;
  83174. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  83175. this._ymesh.material.checkReadyOnlyOnce = true;
  83176. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  83177. this._zmesh.material.checkReadyOnlyOnce = true;
  83178. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  83179. this.scene = scene;
  83180. }
  83181. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  83182. var scaleLines = this.scaleLines;
  83183. if (this._xmesh) {
  83184. this._xmesh.position.copyFrom(position);
  83185. }
  83186. if (this._ymesh) {
  83187. this._ymesh.position.copyFrom(position);
  83188. }
  83189. if (this._zmesh) {
  83190. this._zmesh.position.copyFrom(position);
  83191. }
  83192. var point2 = this._xline[1];
  83193. point2.x = xaxis.x * scaleLines;
  83194. point2.y = xaxis.y * scaleLines;
  83195. point2.z = xaxis.z * scaleLines;
  83196. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  83197. point2 = this._yline[1];
  83198. point2.x = yaxis.x * scaleLines;
  83199. point2.y = yaxis.y * scaleLines;
  83200. point2.z = yaxis.z * scaleLines;
  83201. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  83202. point2 = this._zline[1];
  83203. point2.x = zaxis.x * scaleLines;
  83204. point2.y = zaxis.y * scaleLines;
  83205. point2.z = zaxis.z * scaleLines;
  83206. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  83207. };
  83208. AxesViewer.prototype.dispose = function () {
  83209. if (this._xmesh) {
  83210. this._xmesh.dispose();
  83211. }
  83212. if (this._ymesh) {
  83213. this._ymesh.dispose();
  83214. }
  83215. if (this._zmesh) {
  83216. this._zmesh.dispose();
  83217. }
  83218. this._xmesh = null;
  83219. this._ymesh = null;
  83220. this._zmesh = null;
  83221. this.scene = null;
  83222. };
  83223. return AxesViewer;
  83224. }());
  83225. Debug.AxesViewer = AxesViewer;
  83226. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83227. })(BABYLON || (BABYLON = {}));
  83228. //# sourceMappingURL=babylon.axesViewer.js.map
  83229. "use strict";
  83230. var BABYLON;
  83231. (function (BABYLON) {
  83232. var Debug;
  83233. (function (Debug) {
  83234. /**
  83235. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  83236. */
  83237. var BoneAxesViewer = /** @class */ (function (_super) {
  83238. __extends(BoneAxesViewer, _super);
  83239. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  83240. if (scaleLines === void 0) { scaleLines = 1; }
  83241. var _this = _super.call(this, scene, scaleLines) || this;
  83242. _this.pos = BABYLON.Vector3.Zero();
  83243. _this.xaxis = BABYLON.Vector3.Zero();
  83244. _this.yaxis = BABYLON.Vector3.Zero();
  83245. _this.zaxis = BABYLON.Vector3.Zero();
  83246. _this.mesh = mesh;
  83247. _this.bone = bone;
  83248. return _this;
  83249. }
  83250. BoneAxesViewer.prototype.update = function () {
  83251. if (!this.mesh || !this.bone) {
  83252. return;
  83253. }
  83254. var bone = this.bone;
  83255. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  83256. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  83257. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  83258. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  83259. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  83260. };
  83261. BoneAxesViewer.prototype.dispose = function () {
  83262. if (this.mesh) {
  83263. this.mesh = null;
  83264. this.bone = null;
  83265. _super.prototype.dispose.call(this);
  83266. }
  83267. };
  83268. return BoneAxesViewer;
  83269. }(Debug.AxesViewer));
  83270. Debug.BoneAxesViewer = BoneAxesViewer;
  83271. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83272. })(BABYLON || (BABYLON = {}));
  83273. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  83274. "use strict";
  83275. var BABYLON;
  83276. (function (BABYLON) {
  83277. var RayHelper = /** @class */ (function () {
  83278. function RayHelper(ray) {
  83279. this.ray = ray;
  83280. }
  83281. RayHelper.CreateAndShow = function (ray, scene, color) {
  83282. var helper = new RayHelper(ray);
  83283. helper.show(scene, color);
  83284. return helper;
  83285. };
  83286. RayHelper.prototype.show = function (scene, color) {
  83287. if (!this._renderFunction && this.ray) {
  83288. var ray = this.ray;
  83289. this._renderFunction = this._render.bind(this);
  83290. this._scene = scene;
  83291. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  83292. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  83293. if (this._renderFunction) {
  83294. this._scene.registerBeforeRender(this._renderFunction);
  83295. }
  83296. }
  83297. if (color && this._renderLine) {
  83298. this._renderLine.color.copyFrom(color);
  83299. }
  83300. };
  83301. RayHelper.prototype.hide = function () {
  83302. if (this._renderFunction && this._scene) {
  83303. this._scene.unregisterBeforeRender(this._renderFunction);
  83304. this._scene = null;
  83305. this._renderFunction = null;
  83306. if (this._renderLine) {
  83307. this._renderLine.dispose();
  83308. this._renderLine = null;
  83309. }
  83310. this._renderPoints = [];
  83311. }
  83312. };
  83313. RayHelper.prototype._render = function () {
  83314. var ray = this.ray;
  83315. if (!ray) {
  83316. return;
  83317. }
  83318. var point = this._renderPoints[1];
  83319. var len = Math.min(ray.length, 1000000);
  83320. point.copyFrom(ray.direction);
  83321. point.scaleInPlace(len);
  83322. point.addInPlace(ray.origin);
  83323. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  83324. };
  83325. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  83326. this._attachedToMesh = mesh;
  83327. var ray = this.ray;
  83328. if (!ray) {
  83329. return;
  83330. }
  83331. if (!ray.direction) {
  83332. ray.direction = BABYLON.Vector3.Zero();
  83333. }
  83334. if (!ray.origin) {
  83335. ray.origin = BABYLON.Vector3.Zero();
  83336. }
  83337. if (length) {
  83338. ray.length = length;
  83339. }
  83340. if (!meshSpaceOrigin) {
  83341. meshSpaceOrigin = BABYLON.Vector3.Zero();
  83342. }
  83343. if (!meshSpaceDirection) {
  83344. // -1 so that this will work with Mesh.lookAt
  83345. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  83346. }
  83347. if (!this._meshSpaceDirection) {
  83348. this._meshSpaceDirection = meshSpaceDirection.clone();
  83349. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  83350. }
  83351. else {
  83352. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  83353. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  83354. }
  83355. if (!this._updateToMeshFunction) {
  83356. this._updateToMeshFunction = this._updateToMesh.bind(this);
  83357. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  83358. }
  83359. this._updateToMesh();
  83360. };
  83361. RayHelper.prototype.detachFromMesh = function () {
  83362. if (this._attachedToMesh) {
  83363. if (this._updateToMeshFunction) {
  83364. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  83365. }
  83366. this._attachedToMesh = null;
  83367. this._updateToMeshFunction = null;
  83368. }
  83369. };
  83370. RayHelper.prototype._updateToMesh = function () {
  83371. var ray = this.ray;
  83372. if (!this._attachedToMesh || !ray) {
  83373. return;
  83374. }
  83375. if (this._attachedToMesh._isDisposed) {
  83376. this.detachFromMesh();
  83377. return;
  83378. }
  83379. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  83380. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  83381. };
  83382. RayHelper.prototype.dispose = function () {
  83383. this.hide();
  83384. this.detachFromMesh();
  83385. this.ray = null;
  83386. };
  83387. return RayHelper;
  83388. }());
  83389. BABYLON.RayHelper = RayHelper;
  83390. })(BABYLON || (BABYLON = {}));
  83391. //# sourceMappingURL=babylon.rayHelper.js.map
  83392. "use strict";
  83393. var BABYLON;
  83394. (function (BABYLON) {
  83395. // load the inspector using require, if not present in the global namespace.
  83396. var DebugLayer = /** @class */ (function () {
  83397. function DebugLayer(scene) {
  83398. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83399. this._scene = scene;
  83400. // load inspector using require, if it doesn't exist on the global namespace.
  83401. }
  83402. /** Creates the inspector window. */
  83403. DebugLayer.prototype._createInspector = function (config) {
  83404. if (config === void 0) { config = {}; }
  83405. var popup = config.popup || false;
  83406. var initialTab = config.initialTab || 0;
  83407. var parentElement = config.parentElement || null;
  83408. if (!this._inspector) {
  83409. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  83410. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  83411. } // else nothing to do,; instance is already existing
  83412. };
  83413. DebugLayer.prototype.isVisible = function () {
  83414. if (!this._inspector) {
  83415. return false;
  83416. }
  83417. return true;
  83418. };
  83419. DebugLayer.prototype.hide = function () {
  83420. if (this._inspector) {
  83421. try {
  83422. this._inspector.dispose();
  83423. }
  83424. catch (e) {
  83425. // If the inspector has been removed directly from the inspector tool
  83426. }
  83427. this._inspector = null;
  83428. }
  83429. };
  83430. DebugLayer.prototype.show = function (config) {
  83431. if (config === void 0) { config = {}; }
  83432. if (typeof this.BJSINSPECTOR == 'undefined') {
  83433. // Load inspector and add it to the DOM
  83434. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  83435. }
  83436. else {
  83437. // Otherwise creates the inspector
  83438. this._createInspector(config);
  83439. }
  83440. };
  83441. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  83442. return DebugLayer;
  83443. }());
  83444. BABYLON.DebugLayer = DebugLayer;
  83445. })(BABYLON || (BABYLON = {}));
  83446. //# sourceMappingURL=babylon.debugLayer.js.map
  83447. "use strict";
  83448. var BABYLON;
  83449. (function (BABYLON) {
  83450. var Debug;
  83451. (function (Debug) {
  83452. /**
  83453. * Used to show the physics impostor around the specific mesh.
  83454. */
  83455. var PhysicsViewer = /** @class */ (function () {
  83456. function PhysicsViewer(scene) {
  83457. this._impostors = [];
  83458. this._meshes = [];
  83459. this._numMeshes = 0;
  83460. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83461. var physicEngine = this._scene.getPhysicsEngine();
  83462. if (physicEngine) {
  83463. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  83464. }
  83465. }
  83466. PhysicsViewer.prototype._updateDebugMeshes = function () {
  83467. var plugin = this._physicsEnginePlugin;
  83468. for (var i = 0; i < this._numMeshes; i++) {
  83469. var impostor = this._impostors[i];
  83470. if (!impostor) {
  83471. continue;
  83472. }
  83473. if (impostor.isDisposed) {
  83474. this.hideImpostor(this._impostors[i--]);
  83475. }
  83476. else {
  83477. var mesh = this._meshes[i];
  83478. if (mesh && plugin) {
  83479. plugin.syncMeshWithImpostor(mesh, impostor);
  83480. }
  83481. }
  83482. }
  83483. };
  83484. PhysicsViewer.prototype.showImpostor = function (impostor) {
  83485. if (!this._scene) {
  83486. return;
  83487. }
  83488. for (var i = 0; i < this._numMeshes; i++) {
  83489. if (this._impostors[i] == impostor) {
  83490. return;
  83491. }
  83492. }
  83493. var debugMesh = this._getDebugMesh(impostor, this._scene);
  83494. if (debugMesh) {
  83495. this._impostors[this._numMeshes] = impostor;
  83496. this._meshes[this._numMeshes] = debugMesh;
  83497. if (this._numMeshes === 0) {
  83498. this._renderFunction = this._updateDebugMeshes.bind(this);
  83499. this._scene.registerBeforeRender(this._renderFunction);
  83500. }
  83501. this._numMeshes++;
  83502. }
  83503. };
  83504. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  83505. if (!impostor || !this._scene) {
  83506. return;
  83507. }
  83508. var removed = false;
  83509. for (var i = 0; i < this._numMeshes; i++) {
  83510. if (this._impostors[i] == impostor) {
  83511. var mesh = this._meshes[i];
  83512. if (!mesh) {
  83513. continue;
  83514. }
  83515. this._scene.removeMesh(mesh);
  83516. mesh.dispose();
  83517. this._numMeshes--;
  83518. if (this._numMeshes > 0) {
  83519. this._meshes[i] = this._meshes[this._numMeshes];
  83520. this._impostors[i] = this._impostors[this._numMeshes];
  83521. this._meshes[this._numMeshes] = null;
  83522. this._impostors[this._numMeshes] = null;
  83523. }
  83524. else {
  83525. this._meshes[0] = null;
  83526. this._impostors[0] = null;
  83527. }
  83528. removed = true;
  83529. break;
  83530. }
  83531. }
  83532. if (removed && this._numMeshes === 0) {
  83533. this._scene.unregisterBeforeRender(this._renderFunction);
  83534. }
  83535. };
  83536. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  83537. if (!this._debugMaterial) {
  83538. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  83539. this._debugMaterial.wireframe = true;
  83540. }
  83541. return this._debugMaterial;
  83542. };
  83543. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  83544. if (!this._debugBoxMesh) {
  83545. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  83546. this._debugBoxMesh.renderingGroupId = 1;
  83547. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83548. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  83549. scene.removeMesh(this._debugBoxMesh);
  83550. }
  83551. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  83552. };
  83553. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  83554. if (!this._debugSphereMesh) {
  83555. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  83556. this._debugSphereMesh.renderingGroupId = 1;
  83557. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  83558. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  83559. scene.removeMesh(this._debugSphereMesh);
  83560. }
  83561. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  83562. };
  83563. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  83564. var mesh = null;
  83565. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  83566. mesh = this._getDebugBoxMesh(scene);
  83567. impostor.getBoxSizeToRef(mesh.scaling);
  83568. }
  83569. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  83570. mesh = this._getDebugSphereMesh(scene);
  83571. var radius = impostor.getRadius();
  83572. mesh.scaling.x = radius * 2;
  83573. mesh.scaling.y = radius * 2;
  83574. mesh.scaling.z = radius * 2;
  83575. }
  83576. return mesh;
  83577. };
  83578. PhysicsViewer.prototype.dispose = function () {
  83579. for (var i = 0; i < this._numMeshes; i++) {
  83580. this.hideImpostor(this._impostors[i]);
  83581. }
  83582. if (this._debugBoxMesh) {
  83583. this._debugBoxMesh.dispose();
  83584. }
  83585. if (this._debugSphereMesh) {
  83586. this._debugSphereMesh.dispose();
  83587. }
  83588. if (this._debugMaterial) {
  83589. this._debugMaterial.dispose();
  83590. }
  83591. this._impostors.length = 0;
  83592. this._scene = null;
  83593. this._physicsEnginePlugin = null;
  83594. };
  83595. return PhysicsViewer;
  83596. }());
  83597. Debug.PhysicsViewer = PhysicsViewer;
  83598. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  83599. })(BABYLON || (BABYLON = {}));
  83600. //# sourceMappingURL=babylon.physicsViewer.js.map
  83601. "use strict";
  83602. var BABYLON;
  83603. (function (BABYLON) {
  83604. var BoundingBoxRenderer = /** @class */ (function () {
  83605. function BoundingBoxRenderer(scene) {
  83606. this.frontColor = new BABYLON.Color3(1, 1, 1);
  83607. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  83608. this.showBackLines = true;
  83609. this.renderList = new BABYLON.SmartArray(32);
  83610. this._vertexBuffers = {};
  83611. this._scene = scene;
  83612. }
  83613. BoundingBoxRenderer.prototype._prepareRessources = function () {
  83614. if (this._colorShader) {
  83615. return;
  83616. }
  83617. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  83618. attributes: [BABYLON.VertexBuffer.PositionKind],
  83619. uniforms: ["world", "viewProjection", "color"]
  83620. });
  83621. var engine = this._scene.getEngine();
  83622. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  83623. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  83624. this._createIndexBuffer();
  83625. };
  83626. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  83627. var engine = this._scene.getEngine();
  83628. 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]);
  83629. };
  83630. BoundingBoxRenderer.prototype._rebuild = function () {
  83631. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83632. if (vb) {
  83633. vb._rebuild();
  83634. }
  83635. this._createIndexBuffer();
  83636. };
  83637. BoundingBoxRenderer.prototype.reset = function () {
  83638. this.renderList.reset();
  83639. };
  83640. BoundingBoxRenderer.prototype.render = function () {
  83641. if (this.renderList.length === 0) {
  83642. return;
  83643. }
  83644. this._prepareRessources();
  83645. if (!this._colorShader.isReady()) {
  83646. return;
  83647. }
  83648. var engine = this._scene.getEngine();
  83649. engine.setDepthWrite(false);
  83650. this._colorShader._preBind();
  83651. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  83652. var boundingBox = this.renderList.data[boundingBoxIndex];
  83653. var min = boundingBox.minimum;
  83654. var max = boundingBox.maximum;
  83655. var diff = max.subtract(min);
  83656. var median = min.add(diff.scale(0.5));
  83657. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83658. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83659. .multiply(boundingBox.getWorldMatrix());
  83660. // VBOs
  83661. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83662. if (this.showBackLines) {
  83663. // Back
  83664. engine.setDepthFunctionToGreaterOrEqual();
  83665. this._scene.resetCachedMaterial();
  83666. this._colorShader.setColor4("color", this.backColor.toColor4());
  83667. this._colorShader.bind(worldMatrix);
  83668. // Draw order
  83669. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83670. }
  83671. // Front
  83672. engine.setDepthFunctionToLess();
  83673. this._scene.resetCachedMaterial();
  83674. this._colorShader.setColor4("color", this.frontColor.toColor4());
  83675. this._colorShader.bind(worldMatrix);
  83676. // Draw order
  83677. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83678. }
  83679. this._colorShader.unbind();
  83680. engine.setDepthFunctionToLessOrEqual();
  83681. engine.setDepthWrite(true);
  83682. };
  83683. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  83684. this._prepareRessources();
  83685. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  83686. return;
  83687. }
  83688. var engine = this._scene.getEngine();
  83689. engine.setDepthWrite(false);
  83690. engine.setColorWrite(false);
  83691. this._colorShader._preBind();
  83692. var boundingBox = mesh._boundingInfo.boundingBox;
  83693. var min = boundingBox.minimum;
  83694. var max = boundingBox.maximum;
  83695. var diff = max.subtract(min);
  83696. var median = min.add(diff.scale(0.5));
  83697. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  83698. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  83699. .multiply(boundingBox.getWorldMatrix());
  83700. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  83701. engine.setDepthFunctionToLess();
  83702. this._scene.resetCachedMaterial();
  83703. this._colorShader.bind(worldMatrix);
  83704. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  83705. this._colorShader.unbind();
  83706. engine.setDepthFunctionToLessOrEqual();
  83707. engine.setDepthWrite(true);
  83708. engine.setColorWrite(true);
  83709. };
  83710. BoundingBoxRenderer.prototype.dispose = function () {
  83711. if (!this._colorShader) {
  83712. return;
  83713. }
  83714. this.renderList.dispose();
  83715. this._colorShader.dispose();
  83716. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83717. if (buffer) {
  83718. buffer.dispose();
  83719. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83720. }
  83721. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83722. };
  83723. return BoundingBoxRenderer;
  83724. }());
  83725. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  83726. })(BABYLON || (BABYLON = {}));
  83727. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  83728. "use strict";
  83729. var BABYLON;
  83730. (function (BABYLON) {
  83731. var MorphTarget = /** @class */ (function () {
  83732. function MorphTarget(name, influence) {
  83733. if (influence === void 0) { influence = 0; }
  83734. this.name = name;
  83735. this.animations = new Array();
  83736. this._positions = null;
  83737. this._normals = null;
  83738. this._tangents = null;
  83739. this.onInfluenceChanged = new BABYLON.Observable();
  83740. this.influence = influence;
  83741. }
  83742. Object.defineProperty(MorphTarget.prototype, "influence", {
  83743. get: function () {
  83744. return this._influence;
  83745. },
  83746. set: function (influence) {
  83747. if (this._influence === influence) {
  83748. return;
  83749. }
  83750. var previous = this._influence;
  83751. this._influence = influence;
  83752. if (this.onInfluenceChanged.hasObservers) {
  83753. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  83754. }
  83755. },
  83756. enumerable: true,
  83757. configurable: true
  83758. });
  83759. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  83760. get: function () {
  83761. return !!this._positions;
  83762. },
  83763. enumerable: true,
  83764. configurable: true
  83765. });
  83766. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  83767. get: function () {
  83768. return !!this._normals;
  83769. },
  83770. enumerable: true,
  83771. configurable: true
  83772. });
  83773. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  83774. get: function () {
  83775. return !!this._tangents;
  83776. },
  83777. enumerable: true,
  83778. configurable: true
  83779. });
  83780. MorphTarget.prototype.setPositions = function (data) {
  83781. this._positions = data;
  83782. };
  83783. MorphTarget.prototype.getPositions = function () {
  83784. return this._positions;
  83785. };
  83786. MorphTarget.prototype.setNormals = function (data) {
  83787. this._normals = data;
  83788. };
  83789. MorphTarget.prototype.getNormals = function () {
  83790. return this._normals;
  83791. };
  83792. MorphTarget.prototype.setTangents = function (data) {
  83793. this._tangents = data;
  83794. };
  83795. MorphTarget.prototype.getTangents = function () {
  83796. return this._tangents;
  83797. };
  83798. /**
  83799. * Serializes the current target into a Serialization object.
  83800. * Returns the serialized object.
  83801. */
  83802. MorphTarget.prototype.serialize = function () {
  83803. var serializationObject = {};
  83804. serializationObject.name = this.name;
  83805. serializationObject.influence = this.influence;
  83806. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  83807. if (this.hasNormals) {
  83808. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  83809. }
  83810. if (this.hasTangents) {
  83811. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  83812. }
  83813. // Animations
  83814. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  83815. return serializationObject;
  83816. };
  83817. // Statics
  83818. MorphTarget.Parse = function (serializationObject) {
  83819. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  83820. result.setPositions(serializationObject.positions);
  83821. if (serializationObject.normals) {
  83822. result.setNormals(serializationObject.normals);
  83823. }
  83824. if (serializationObject.tangents) {
  83825. result.setTangents(serializationObject.tangents);
  83826. }
  83827. // Animations
  83828. if (serializationObject.animations) {
  83829. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  83830. var parsedAnimation = serializationObject.animations[animationIndex];
  83831. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  83832. }
  83833. }
  83834. return result;
  83835. };
  83836. MorphTarget.FromMesh = function (mesh, name, influence) {
  83837. if (!name) {
  83838. name = mesh.name;
  83839. }
  83840. var result = new MorphTarget(name, influence);
  83841. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  83843. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  83844. }
  83845. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  83846. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  83847. }
  83848. return result;
  83849. };
  83850. return MorphTarget;
  83851. }());
  83852. BABYLON.MorphTarget = MorphTarget;
  83853. })(BABYLON || (BABYLON = {}));
  83854. //# sourceMappingURL=babylon.morphTarget.js.map
  83855. "use strict";
  83856. var BABYLON;
  83857. (function (BABYLON) {
  83858. var MorphTargetManager = /** @class */ (function () {
  83859. function MorphTargetManager(scene) {
  83860. if (scene === void 0) { scene = null; }
  83861. this._targets = new Array();
  83862. this._targetObservable = new Array();
  83863. this._activeTargets = new BABYLON.SmartArray(16);
  83864. this._supportsNormals = false;
  83865. this._supportsTangents = false;
  83866. this._vertexCount = 0;
  83867. this._uniqueId = 0;
  83868. this._tempInfluences = new Array();
  83869. if (!scene) {
  83870. scene = BABYLON.Engine.LastCreatedScene;
  83871. }
  83872. this._scene = scene;
  83873. if (this._scene) {
  83874. this._scene.morphTargetManagers.push(this);
  83875. this._uniqueId = this._scene.getUniqueId();
  83876. }
  83877. }
  83878. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  83879. get: function () {
  83880. return this._uniqueId;
  83881. },
  83882. enumerable: true,
  83883. configurable: true
  83884. });
  83885. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  83886. get: function () {
  83887. return this._vertexCount;
  83888. },
  83889. enumerable: true,
  83890. configurable: true
  83891. });
  83892. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  83893. get: function () {
  83894. return this._supportsNormals;
  83895. },
  83896. enumerable: true,
  83897. configurable: true
  83898. });
  83899. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  83900. get: function () {
  83901. return this._supportsTangents;
  83902. },
  83903. enumerable: true,
  83904. configurable: true
  83905. });
  83906. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  83907. get: function () {
  83908. return this._targets.length;
  83909. },
  83910. enumerable: true,
  83911. configurable: true
  83912. });
  83913. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  83914. get: function () {
  83915. return this._activeTargets.length;
  83916. },
  83917. enumerable: true,
  83918. configurable: true
  83919. });
  83920. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  83921. get: function () {
  83922. return this._influences;
  83923. },
  83924. enumerable: true,
  83925. configurable: true
  83926. });
  83927. MorphTargetManager.prototype.getActiveTarget = function (index) {
  83928. return this._activeTargets.data[index];
  83929. };
  83930. MorphTargetManager.prototype.getTarget = function (index) {
  83931. return this._targets[index];
  83932. };
  83933. MorphTargetManager.prototype.addTarget = function (target) {
  83934. var _this = this;
  83935. this._targets.push(target);
  83936. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  83937. _this._syncActiveTargets(needUpdate);
  83938. }));
  83939. this._syncActiveTargets(true);
  83940. };
  83941. MorphTargetManager.prototype.removeTarget = function (target) {
  83942. var index = this._targets.indexOf(target);
  83943. if (index >= 0) {
  83944. this._targets.splice(index, 1);
  83945. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  83946. this._syncActiveTargets(true);
  83947. }
  83948. };
  83949. /**
  83950. * Serializes the current manager into a Serialization object.
  83951. * Returns the serialized object.
  83952. */
  83953. MorphTargetManager.prototype.serialize = function () {
  83954. var serializationObject = {};
  83955. serializationObject.id = this.uniqueId;
  83956. serializationObject.targets = [];
  83957. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  83958. var target = _a[_i];
  83959. serializationObject.targets.push(target.serialize());
  83960. }
  83961. return serializationObject;
  83962. };
  83963. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  83964. var influenceCount = 0;
  83965. this._activeTargets.reset();
  83966. this._supportsNormals = true;
  83967. this._supportsTangents = true;
  83968. this._vertexCount = 0;
  83969. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  83970. var target = _a[_i];
  83971. this._activeTargets.push(target);
  83972. this._tempInfluences[influenceCount++] = target.influence;
  83973. var positions = target.getPositions();
  83974. if (positions) {
  83975. this._supportsNormals = this._supportsNormals && target.hasNormals;
  83976. this._supportsTangents = this._supportsTangents && target.hasTangents;
  83977. var vertexCount = positions.length / 3;
  83978. if (this._vertexCount === 0) {
  83979. this._vertexCount = vertexCount;
  83980. }
  83981. else if (this._vertexCount !== vertexCount) {
  83982. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  83983. return;
  83984. }
  83985. }
  83986. }
  83987. if (!this._influences || this._influences.length !== influenceCount) {
  83988. this._influences = new Float32Array(influenceCount);
  83989. }
  83990. for (var index = 0; index < influenceCount; index++) {
  83991. this._influences[index] = this._tempInfluences[index];
  83992. }
  83993. if (needUpdate && this._scene) {
  83994. // Flag meshes as dirty to resync with the active targets
  83995. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  83996. var mesh = _c[_b];
  83997. if (mesh.morphTargetManager === this) {
  83998. mesh._syncGeometryWithMorphTargetManager();
  83999. }
  84000. }
  84001. }
  84002. };
  84003. // Statics
  84004. MorphTargetManager.Parse = function (serializationObject, scene) {
  84005. var result = new MorphTargetManager(scene);
  84006. result._uniqueId = serializationObject.id;
  84007. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  84008. var targetData = _a[_i];
  84009. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  84010. }
  84011. return result;
  84012. };
  84013. return MorphTargetManager;
  84014. }());
  84015. BABYLON.MorphTargetManager = MorphTargetManager;
  84016. })(BABYLON || (BABYLON = {}));
  84017. //# sourceMappingURL=babylon.morphTargetManager.js.map
  84018. "use strict";
  84019. var BABYLON;
  84020. (function (BABYLON) {
  84021. var Octree = /** @class */ (function () {
  84022. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  84023. if (maxDepth === void 0) { maxDepth = 2; }
  84024. this.maxDepth = maxDepth;
  84025. this.dynamicContent = new Array();
  84026. this._maxBlockCapacity = maxBlockCapacity || 64;
  84027. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  84028. this._creationFunc = creationFunc;
  84029. }
  84030. // Methods
  84031. Octree.prototype.update = function (worldMin, worldMax, entries) {
  84032. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  84033. };
  84034. Octree.prototype.addMesh = function (entry) {
  84035. for (var index = 0; index < this.blocks.length; index++) {
  84036. var block = this.blocks[index];
  84037. block.addEntry(entry);
  84038. }
  84039. };
  84040. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  84041. this._selectionContent.reset();
  84042. for (var index = 0; index < this.blocks.length; index++) {
  84043. var block = this.blocks[index];
  84044. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  84045. }
  84046. if (allowDuplicate) {
  84047. this._selectionContent.concat(this.dynamicContent);
  84048. }
  84049. else {
  84050. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84051. }
  84052. return this._selectionContent;
  84053. };
  84054. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  84055. this._selectionContent.reset();
  84056. for (var index = 0; index < this.blocks.length; index++) {
  84057. var block = this.blocks[index];
  84058. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  84059. }
  84060. if (allowDuplicate) {
  84061. this._selectionContent.concat(this.dynamicContent);
  84062. }
  84063. else {
  84064. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84065. }
  84066. return this._selectionContent;
  84067. };
  84068. Octree.prototype.intersectsRay = function (ray) {
  84069. this._selectionContent.reset();
  84070. for (var index = 0; index < this.blocks.length; index++) {
  84071. var block = this.blocks[index];
  84072. block.intersectsRay(ray, this._selectionContent);
  84073. }
  84074. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  84075. return this._selectionContent;
  84076. };
  84077. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  84078. target.blocks = new Array();
  84079. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  84080. // Segmenting space
  84081. for (var x = 0; x < 2; x++) {
  84082. for (var y = 0; y < 2; y++) {
  84083. for (var z = 0; z < 2; z++) {
  84084. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  84085. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  84086. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  84087. block.addEntries(entries);
  84088. target.blocks.push(block);
  84089. }
  84090. }
  84091. }
  84092. };
  84093. Octree.CreationFuncForMeshes = function (entry, block) {
  84094. var boundingInfo = entry.getBoundingInfo();
  84095. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84096. block.entries.push(entry);
  84097. }
  84098. };
  84099. Octree.CreationFuncForSubMeshes = function (entry, block) {
  84100. var boundingInfo = entry.getBoundingInfo();
  84101. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  84102. block.entries.push(entry);
  84103. }
  84104. };
  84105. return Octree;
  84106. }());
  84107. BABYLON.Octree = Octree;
  84108. })(BABYLON || (BABYLON = {}));
  84109. //# sourceMappingURL=babylon.octree.js.map
  84110. "use strict";
  84111. var BABYLON;
  84112. (function (BABYLON) {
  84113. var OctreeBlock = /** @class */ (function () {
  84114. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  84115. this.entries = new Array();
  84116. this._boundingVectors = new Array();
  84117. this._capacity = capacity;
  84118. this._depth = depth;
  84119. this._maxDepth = maxDepth;
  84120. this._creationFunc = creationFunc;
  84121. this._minPoint = minPoint;
  84122. this._maxPoint = maxPoint;
  84123. this._boundingVectors.push(minPoint.clone());
  84124. this._boundingVectors.push(maxPoint.clone());
  84125. this._boundingVectors.push(minPoint.clone());
  84126. this._boundingVectors[2].x = maxPoint.x;
  84127. this._boundingVectors.push(minPoint.clone());
  84128. this._boundingVectors[3].y = maxPoint.y;
  84129. this._boundingVectors.push(minPoint.clone());
  84130. this._boundingVectors[4].z = maxPoint.z;
  84131. this._boundingVectors.push(maxPoint.clone());
  84132. this._boundingVectors[5].z = minPoint.z;
  84133. this._boundingVectors.push(maxPoint.clone());
  84134. this._boundingVectors[6].x = minPoint.x;
  84135. this._boundingVectors.push(maxPoint.clone());
  84136. this._boundingVectors[7].y = minPoint.y;
  84137. }
  84138. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  84139. // Property
  84140. get: function () {
  84141. return this._capacity;
  84142. },
  84143. enumerable: true,
  84144. configurable: true
  84145. });
  84146. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  84147. get: function () {
  84148. return this._minPoint;
  84149. },
  84150. enumerable: true,
  84151. configurable: true
  84152. });
  84153. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  84154. get: function () {
  84155. return this._maxPoint;
  84156. },
  84157. enumerable: true,
  84158. configurable: true
  84159. });
  84160. // Methods
  84161. OctreeBlock.prototype.addEntry = function (entry) {
  84162. if (this.blocks) {
  84163. for (var index = 0; index < this.blocks.length; index++) {
  84164. var block = this.blocks[index];
  84165. block.addEntry(entry);
  84166. }
  84167. return;
  84168. }
  84169. this._creationFunc(entry, this);
  84170. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  84171. this.createInnerBlocks();
  84172. }
  84173. };
  84174. OctreeBlock.prototype.addEntries = function (entries) {
  84175. for (var index = 0; index < entries.length; index++) {
  84176. var mesh = entries[index];
  84177. this.addEntry(mesh);
  84178. }
  84179. };
  84180. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  84181. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  84182. if (this.blocks) {
  84183. for (var index = 0; index < this.blocks.length; index++) {
  84184. var block = this.blocks[index];
  84185. block.select(frustumPlanes, selection, allowDuplicate);
  84186. }
  84187. return;
  84188. }
  84189. if (allowDuplicate) {
  84190. selection.concat(this.entries);
  84191. }
  84192. else {
  84193. selection.concatWithNoDuplicate(this.entries);
  84194. }
  84195. }
  84196. };
  84197. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  84198. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  84199. if (this.blocks) {
  84200. for (var index = 0; index < this.blocks.length; index++) {
  84201. var block = this.blocks[index];
  84202. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  84203. }
  84204. return;
  84205. }
  84206. if (allowDuplicate) {
  84207. selection.concat(this.entries);
  84208. }
  84209. else {
  84210. selection.concatWithNoDuplicate(this.entries);
  84211. }
  84212. }
  84213. };
  84214. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  84215. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  84216. if (this.blocks) {
  84217. for (var index = 0; index < this.blocks.length; index++) {
  84218. var block = this.blocks[index];
  84219. block.intersectsRay(ray, selection);
  84220. }
  84221. return;
  84222. }
  84223. selection.concatWithNoDuplicate(this.entries);
  84224. }
  84225. };
  84226. OctreeBlock.prototype.createInnerBlocks = function () {
  84227. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  84228. };
  84229. return OctreeBlock;
  84230. }());
  84231. BABYLON.OctreeBlock = OctreeBlock;
  84232. })(BABYLON || (BABYLON = {}));
  84233. //# sourceMappingURL=babylon.octreeBlock.js.map
  84234. "use strict";
  84235. var BABYLON;
  84236. (function (BABYLON) {
  84237. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  84238. __extends(VRDistortionCorrectionPostProcess, _super);
  84239. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  84240. var _this = _super.call(this, name, "vrDistortionCorrection", [
  84241. 'LensCenter',
  84242. 'Scale',
  84243. 'ScaleIn',
  84244. 'HmdWarpParam'
  84245. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  84246. _this._isRightEye = isRightEye;
  84247. _this._distortionFactors = vrMetrics.distortionK;
  84248. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  84249. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  84250. _this.adaptScaleToCurrentViewport = true;
  84251. _this.onSizeChangedObservable.add(function () {
  84252. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  84253. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  84254. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  84255. });
  84256. _this.onApplyObservable.add(function (effect) {
  84257. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  84258. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  84259. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  84260. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  84261. });
  84262. return _this;
  84263. }
  84264. return VRDistortionCorrectionPostProcess;
  84265. }(BABYLON.PostProcess));
  84266. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  84267. })(BABYLON || (BABYLON = {}));
  84268. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  84269. "use strict";
  84270. var BABYLON;
  84271. (function (BABYLON) {
  84272. var AnaglyphPostProcess = /** @class */ (function (_super) {
  84273. __extends(AnaglyphPostProcess, _super);
  84274. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  84275. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  84276. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84277. _this.onApplyObservable.add(function (effect) {
  84278. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  84279. });
  84280. return _this;
  84281. }
  84282. return AnaglyphPostProcess;
  84283. }(BABYLON.PostProcess));
  84284. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  84285. })(BABYLON || (BABYLON = {}));
  84286. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  84287. "use strict";
  84288. var BABYLON;
  84289. (function (BABYLON) {
  84290. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  84291. __extends(StereoscopicInterlacePostProcess, _super);
  84292. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  84293. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  84294. _this._passedProcess = rigCameras[0]._rigPostProcess;
  84295. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  84296. _this.onSizeChangedObservable.add(function () {
  84297. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  84298. });
  84299. _this.onApplyObservable.add(function (effect) {
  84300. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  84301. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  84302. });
  84303. return _this;
  84304. }
  84305. return StereoscopicInterlacePostProcess;
  84306. }(BABYLON.PostProcess));
  84307. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  84308. })(BABYLON || (BABYLON = {}));
  84309. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  84310. "use strict";
  84311. var BABYLON;
  84312. (function (BABYLON) {
  84313. /**
  84314. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  84315. * Screen rotation is taken into account.
  84316. */
  84317. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  84318. function FreeCameraDeviceOrientationInput() {
  84319. var _this = this;
  84320. this._screenOrientationAngle = 0;
  84321. this._screenQuaternion = new BABYLON.Quaternion();
  84322. this._alpha = 0;
  84323. this._beta = 0;
  84324. this._gamma = 0;
  84325. this._orientationChanged = function () {
  84326. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  84327. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  84328. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  84329. };
  84330. this._deviceOrientation = function (evt) {
  84331. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  84332. _this._beta = evt.beta !== null ? evt.beta : 0;
  84333. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  84334. };
  84335. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  84336. this._orientationChanged();
  84337. }
  84338. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  84339. get: function () {
  84340. return this._camera;
  84341. },
  84342. set: function (camera) {
  84343. this._camera = camera;
  84344. if (this._camera != null && !this._camera.rotationQuaternion) {
  84345. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  84346. }
  84347. },
  84348. enumerable: true,
  84349. configurable: true
  84350. });
  84351. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  84352. window.addEventListener("orientationchange", this._orientationChanged);
  84353. window.addEventListener("deviceorientation", this._deviceOrientation);
  84354. //In certain cases, the attach control is called AFTER orientation was changed,
  84355. //So this is needed.
  84356. this._orientationChanged();
  84357. };
  84358. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  84359. window.removeEventListener("orientationchange", this._orientationChanged);
  84360. window.removeEventListener("deviceorientation", this._deviceOrientation);
  84361. };
  84362. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  84363. //if no device orientation provided, don't update the rotation.
  84364. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  84365. if (!this._alpha)
  84366. return;
  84367. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  84368. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  84369. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  84370. //Mirror on XY Plane
  84371. this._camera.rotationQuaternion.z *= -1;
  84372. this._camera.rotationQuaternion.w *= -1;
  84373. };
  84374. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  84375. return "FreeCameraDeviceOrientationInput";
  84376. };
  84377. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  84378. return "deviceOrientation";
  84379. };
  84380. return FreeCameraDeviceOrientationInput;
  84381. }());
  84382. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  84383. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  84384. })(BABYLON || (BABYLON = {}));
  84385. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  84386. "use strict";
  84387. var BABYLON;
  84388. (function (BABYLON) {
  84389. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  84390. function ArcRotateCameraVRDeviceOrientationInput() {
  84391. this.alphaCorrection = 1;
  84392. this.betaCorrection = 1;
  84393. this.gammaCorrection = 1;
  84394. this._alpha = 0;
  84395. this._gamma = 0;
  84396. this._dirty = false;
  84397. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  84398. }
  84399. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  84400. this.camera.attachControl(element, noPreventDefault);
  84401. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  84402. };
  84403. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  84404. if (evt.alpha !== null) {
  84405. this._alpha = +evt.alpha | 0;
  84406. }
  84407. if (evt.gamma !== null) {
  84408. this._gamma = +evt.gamma | 0;
  84409. }
  84410. this._dirty = true;
  84411. };
  84412. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  84413. if (this._dirty) {
  84414. this._dirty = false;
  84415. if (this._gamma < 0) {
  84416. this._gamma = 180 + this._gamma;
  84417. }
  84418. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  84419. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  84420. }
  84421. };
  84422. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  84423. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  84424. };
  84425. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  84426. return "ArcRotateCameraVRDeviceOrientationInput";
  84427. };
  84428. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  84429. return "VRDeviceOrientation";
  84430. };
  84431. return ArcRotateCameraVRDeviceOrientationInput;
  84432. }());
  84433. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  84434. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  84435. })(BABYLON || (BABYLON = {}));
  84436. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  84437. "use strict";
  84438. var BABYLON;
  84439. (function (BABYLON) {
  84440. var VRCameraMetrics = /** @class */ (function () {
  84441. function VRCameraMetrics() {
  84442. this.compensateDistortion = true;
  84443. }
  84444. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  84445. get: function () {
  84446. return this.hResolution / (2 * this.vResolution);
  84447. },
  84448. enumerable: true,
  84449. configurable: true
  84450. });
  84451. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  84452. get: function () {
  84453. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  84454. },
  84455. enumerable: true,
  84456. configurable: true
  84457. });
  84458. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  84459. get: function () {
  84460. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  84461. var h = (4 * meters) / this.hScreenSize;
  84462. return BABYLON.Matrix.Translation(h, 0, 0);
  84463. },
  84464. enumerable: true,
  84465. configurable: true
  84466. });
  84467. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  84468. get: function () {
  84469. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  84470. var h = (4 * meters) / this.hScreenSize;
  84471. return BABYLON.Matrix.Translation(-h, 0, 0);
  84472. },
  84473. enumerable: true,
  84474. configurable: true
  84475. });
  84476. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  84477. get: function () {
  84478. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  84479. },
  84480. enumerable: true,
  84481. configurable: true
  84482. });
  84483. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  84484. get: function () {
  84485. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  84486. },
  84487. enumerable: true,
  84488. configurable: true
  84489. });
  84490. VRCameraMetrics.GetDefault = function () {
  84491. var result = new VRCameraMetrics();
  84492. result.hResolution = 1280;
  84493. result.vResolution = 800;
  84494. result.hScreenSize = 0.149759993;
  84495. result.vScreenSize = 0.0935999975;
  84496. result.vScreenCenter = 0.0467999987;
  84497. result.eyeToScreenDistance = 0.0410000011;
  84498. result.lensSeparationDistance = 0.0635000020;
  84499. result.interpupillaryDistance = 0.0640000030;
  84500. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  84501. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  84502. result.postProcessScaleFactor = 1.714605507808412;
  84503. result.lensCenterOffset = 0.151976421;
  84504. return result;
  84505. };
  84506. return VRCameraMetrics;
  84507. }());
  84508. BABYLON.VRCameraMetrics = VRCameraMetrics;
  84509. })(BABYLON || (BABYLON = {}));
  84510. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  84511. "use strict";
  84512. var BABYLON;
  84513. (function (BABYLON) {
  84514. /**
  84515. * This represents a WebVR camera.
  84516. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  84517. * @example http://doc.babylonjs.com/how_to/webvr_camera
  84518. */
  84519. var WebVRFreeCamera = /** @class */ (function (_super) {
  84520. __extends(WebVRFreeCamera, _super);
  84521. /**
  84522. * Instantiates a WebVRFreeCamera.
  84523. * @param name The name of the WebVRFreeCamera
  84524. * @param position The starting anchor position for the camera
  84525. * @param scene The scene the camera belongs to
  84526. * @param webVROptions a set of customizable options for the webVRCamera
  84527. */
  84528. function WebVRFreeCamera(name, position, scene, webVROptions) {
  84529. if (webVROptions === void 0) { webVROptions = {}; }
  84530. var _this = _super.call(this, name, position, scene) || this;
  84531. _this.webVROptions = webVROptions;
  84532. /**
  84533. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  84534. */
  84535. _this._vrDevice = null;
  84536. /**
  84537. * The rawPose of the vrDevice.
  84538. */
  84539. _this.rawPose = null;
  84540. _this._specsVersion = "1.1";
  84541. _this._attached = false;
  84542. _this._descendants = [];
  84543. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  84544. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  84545. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  84546. _this._standingMatrix = null;
  84547. /**
  84548. * Represents device position in babylon space.
  84549. */
  84550. _this.devicePosition = BABYLON.Vector3.Zero();
  84551. /**
  84552. * Represents device rotation in babylon space.
  84553. */
  84554. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  84555. /**
  84556. * The scale of the device to be used when translating from device space to babylon space.
  84557. */
  84558. _this.deviceScaleFactor = 1;
  84559. _this._deviceToWorld = BABYLON.Matrix.Identity();
  84560. _this._worldToDevice = BABYLON.Matrix.Identity();
  84561. /**
  84562. * References to the webVR controllers for the vrDevice.
  84563. */
  84564. _this.controllers = [];
  84565. /**
  84566. * Emits an event when a controller is attached.
  84567. */
  84568. _this.onControllersAttachedObservable = new BABYLON.Observable();
  84569. /**
  84570. * Emits an event when a controller's mesh has been loaded;
  84571. */
  84572. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  84573. /**
  84574. * If the rig cameras be used as parent instead of this camera.
  84575. */
  84576. _this.rigParenting = true;
  84577. _this._defaultHeight = undefined;
  84578. _this._workingVector = BABYLON.Vector3.Zero();
  84579. _this._oneVector = BABYLON.Vector3.One();
  84580. _this._workingMatrix = BABYLON.Matrix.Identity();
  84581. _this._cache.position = BABYLON.Vector3.Zero();
  84582. if (webVROptions.defaultHeight) {
  84583. _this._defaultHeight = webVROptions.defaultHeight;
  84584. _this.position.y = _this._defaultHeight;
  84585. }
  84586. _this.minZ = 0.1;
  84587. //legacy support - the compensation boolean was removed.
  84588. if (arguments.length === 5) {
  84589. _this.webVROptions = arguments[4];
  84590. }
  84591. // default webVR options
  84592. if (_this.webVROptions.trackPosition == undefined) {
  84593. _this.webVROptions.trackPosition = true;
  84594. }
  84595. if (_this.webVROptions.controllerMeshes == undefined) {
  84596. _this.webVROptions.controllerMeshes = true;
  84597. }
  84598. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  84599. _this.webVROptions.defaultLightingOnControllers = true;
  84600. }
  84601. _this.rotationQuaternion = new BABYLON.Quaternion();
  84602. if (_this.webVROptions && _this.webVROptions.positionScale) {
  84603. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  84604. }
  84605. //enable VR
  84606. var engine = _this.getEngine();
  84607. _this._onVREnabled = function (success) { if (success) {
  84608. _this.initControllers();
  84609. } };
  84610. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  84611. engine.initWebVR().add(function (event) {
  84612. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  84613. return;
  84614. }
  84615. _this._vrDevice = event.vrDisplay;
  84616. //reset the rig parameters.
  84617. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  84618. if (_this._attached) {
  84619. _this.getEngine().enableVR();
  84620. }
  84621. });
  84622. if (typeof (VRFrameData) !== "undefined")
  84623. _this._frameData = new VRFrameData();
  84624. /**
  84625. * The idea behind the following lines:
  84626. * objects that have the camera as parent should actually have the rig cameras as a parent.
  84627. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  84628. * the second will not show it correctly.
  84629. *
  84630. * To solve this - each object that has the camera as parent will be added to a protected array.
  84631. * When the rig camera renders, it will take this array and set all of those to be its children.
  84632. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  84633. * Amazing!
  84634. */
  84635. scene.onBeforeCameraRenderObservable.add(function (camera) {
  84636. if (camera.parent === _this && _this.rigParenting) {
  84637. _this._descendants = _this.getDescendants(true, function (n) {
  84638. // don't take the cameras or the controllers!
  84639. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  84640. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  84641. return !isController && !isRigCamera;
  84642. });
  84643. _this._descendants.forEach(function (node) {
  84644. node.parent = camera;
  84645. });
  84646. }
  84647. });
  84648. scene.onAfterCameraRenderObservable.add(function (camera) {
  84649. if (camera.parent === _this && _this.rigParenting) {
  84650. _this._descendants.forEach(function (node) {
  84651. node.parent = _this;
  84652. });
  84653. }
  84654. });
  84655. return _this;
  84656. }
  84657. /**
  84658. * Gets the device distance from the ground in meters.
  84659. * @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.
  84660. */
  84661. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  84662. if (this._standingMatrix) {
  84663. // Add standing matrix offset to get real offset from ground in room
  84664. this._standingMatrix.getTranslationToRef(this._workingVector);
  84665. return this._deviceRoomPosition.y + this._workingVector.y;
  84666. }
  84667. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  84668. return this._defaultHeight || 0;
  84669. };
  84670. /**
  84671. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  84672. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  84673. */
  84674. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  84675. var _this = this;
  84676. if (callback === void 0) { callback = function (bool) { }; }
  84677. // Use standing matrix if available
  84678. this.getEngine().initWebVRAsync().then(function (result) {
  84679. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  84680. callback(false);
  84681. }
  84682. else {
  84683. _this._standingMatrix = new BABYLON.Matrix();
  84684. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  84685. if (!_this.getScene().useRightHandedSystem) {
  84686. [2, 6, 8, 9, 14].forEach(function (num) {
  84687. if (_this._standingMatrix) {
  84688. _this._standingMatrix.m[num] *= -1;
  84689. }
  84690. });
  84691. }
  84692. callback(true);
  84693. }
  84694. });
  84695. };
  84696. /**
  84697. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  84698. * @returns A promise with a boolean set to if the standing matrix is supported.
  84699. */
  84700. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  84701. var _this = this;
  84702. return new Promise(function (res, rej) {
  84703. _this.useStandingMatrix(function (supported) {
  84704. res(supported);
  84705. });
  84706. });
  84707. };
  84708. /**
  84709. * Disposes the camera
  84710. */
  84711. WebVRFreeCamera.prototype.dispose = function () {
  84712. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  84713. _super.prototype.dispose.call(this);
  84714. };
  84715. /**
  84716. * Gets a vrController by name.
  84717. * @param name The name of the controller to retreive
  84718. * @returns the controller matching the name specified or null if not found
  84719. */
  84720. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  84721. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  84722. var gp = _a[_i];
  84723. if (gp.hand === name) {
  84724. return gp;
  84725. }
  84726. }
  84727. return null;
  84728. };
  84729. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  84730. /**
  84731. * The controller corrisponding to the users left hand.
  84732. */
  84733. get: function () {
  84734. if (!this._leftController) {
  84735. this._leftController = this.getControllerByName("left");
  84736. }
  84737. return this._leftController;
  84738. },
  84739. enumerable: true,
  84740. configurable: true
  84741. });
  84742. ;
  84743. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  84744. /**
  84745. * The controller corrisponding to the users right hand.
  84746. */
  84747. get: function () {
  84748. if (!this._rightController) {
  84749. this._rightController = this.getControllerByName("right");
  84750. }
  84751. return this._rightController;
  84752. },
  84753. enumerable: true,
  84754. configurable: true
  84755. });
  84756. ;
  84757. /**
  84758. * Casts a ray forward from the vrCamera's gaze.
  84759. * @param length Length of the ray (default: 100)
  84760. * @returns the ray corrisponding to the gaze
  84761. */
  84762. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  84763. if (length === void 0) { length = 100; }
  84764. if (this.leftCamera) {
  84765. // Use left eye to avoid computation to compute center on every call
  84766. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  84767. }
  84768. else {
  84769. return _super.prototype.getForwardRay.call(this, length);
  84770. }
  84771. };
  84772. /**
  84773. * Updates the camera based on device's frame data
  84774. */
  84775. WebVRFreeCamera.prototype._checkInputs = function () {
  84776. if (this._vrDevice && this._vrDevice.isPresenting) {
  84777. this._vrDevice.getFrameData(this._frameData);
  84778. this.updateFromDevice(this._frameData.pose);
  84779. }
  84780. _super.prototype._checkInputs.call(this);
  84781. };
  84782. /**
  84783. * Updates the poseControlled values based on the input device pose.
  84784. * @param poseData Pose coming from the device
  84785. */
  84786. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  84787. if (poseData && poseData.orientation) {
  84788. this.rawPose = poseData;
  84789. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  84790. if (this.getScene().useRightHandedSystem) {
  84791. this._deviceRoomRotationQuaternion.z *= -1;
  84792. this._deviceRoomRotationQuaternion.w *= -1;
  84793. }
  84794. if (this.webVROptions.trackPosition && this.rawPose.position) {
  84795. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  84796. if (this.getScene().useRightHandedSystem) {
  84797. this._deviceRoomPosition.z *= -1;
  84798. }
  84799. }
  84800. }
  84801. };
  84802. /**
  84803. * WebVR's attach control will start broadcasting frames to the device.
  84804. * Note that in certain browsers (chrome for example) this function must be called
  84805. * within a user-interaction callback. Example:
  84806. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  84807. *
  84808. * @param element html element to attach the vrDevice to
  84809. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  84810. */
  84811. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  84812. _super.prototype.attachControl.call(this, element, noPreventDefault);
  84813. this._attached = true;
  84814. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  84815. if (this._vrDevice) {
  84816. this.getEngine().enableVR();
  84817. }
  84818. };
  84819. /**
  84820. * Detaches the camera from the html element and disables VR
  84821. *
  84822. * @param element html element to detach from
  84823. */
  84824. WebVRFreeCamera.prototype.detachControl = function (element) {
  84825. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  84826. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  84827. _super.prototype.detachControl.call(this, element);
  84828. this._attached = false;
  84829. this.getEngine().disableVR();
  84830. };
  84831. /**
  84832. * @returns the name of this class
  84833. */
  84834. WebVRFreeCamera.prototype.getClassName = function () {
  84835. return "WebVRFreeCamera";
  84836. };
  84837. /**
  84838. * Calls resetPose on the vrDisplay
  84839. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  84840. */
  84841. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  84842. //uses the vrDisplay's "resetPose()".
  84843. //pitch and roll won't be affected.
  84844. this._vrDevice.resetPose();
  84845. };
  84846. /**
  84847. * Updates the rig cameras (left and right eye)
  84848. */
  84849. WebVRFreeCamera.prototype._updateRigCameras = function () {
  84850. var camLeft = this._rigCameras[0];
  84851. var camRight = this._rigCameras[1];
  84852. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  84853. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  84854. camLeft.position.copyFrom(this._deviceRoomPosition);
  84855. camRight.position.copyFrom(this._deviceRoomPosition);
  84856. };
  84857. /**
  84858. * Updates the cached values of the camera
  84859. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  84860. */
  84861. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  84862. var _this = this;
  84863. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  84864. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  84865. if (!this.updateCacheCalled) {
  84866. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  84867. this.updateCacheCalled = true;
  84868. this.update();
  84869. }
  84870. // Set working vector to the device position in room space rotated by the new rotation
  84871. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  84872. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  84873. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  84874. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  84875. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  84876. // Add translation from anchor position
  84877. this._deviceToWorld.getTranslationToRef(this._workingVector);
  84878. this._workingVector.addInPlace(this.position);
  84879. this._workingVector.subtractInPlace(this._cache.position);
  84880. this._deviceToWorld.setTranslation(this._workingVector);
  84881. // Set an inverted matrix to be used when updating the camera
  84882. this._deviceToWorld.invertToRef(this._worldToDevice);
  84883. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  84884. this.controllers.forEach(function (controller) {
  84885. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  84886. controller.update();
  84887. });
  84888. }
  84889. if (!ignoreParentClass) {
  84890. _super.prototype._updateCache.call(this);
  84891. }
  84892. this.updateCacheCalled = false;
  84893. };
  84894. /**
  84895. * Updates the current device position and rotation in the babylon world
  84896. */
  84897. WebVRFreeCamera.prototype.update = function () {
  84898. // Get current device position in babylon world
  84899. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  84900. // Get current device rotation in babylon world
  84901. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  84902. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  84903. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  84904. _super.prototype.update.call(this);
  84905. };
  84906. /**
  84907. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  84908. * @returns an identity matrix
  84909. */
  84910. WebVRFreeCamera.prototype._getViewMatrix = function () {
  84911. return BABYLON.Matrix.Identity();
  84912. };
  84913. /**
  84914. * This function is called by the two RIG cameras.
  84915. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  84916. */
  84917. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  84918. var _this = this;
  84919. // Update the parent camera prior to using a child camera to avoid desynchronization
  84920. var parentCamera = this._cameraRigParams["parentCamera"];
  84921. parentCamera._updateCache();
  84922. //WebVR 1.1
  84923. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  84924. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  84925. if (!this.getScene().useRightHandedSystem) {
  84926. [2, 6, 8, 9, 14].forEach(function (num) {
  84927. _this._webvrViewMatrix.m[num] *= -1;
  84928. });
  84929. }
  84930. // update the camera rotation matrix
  84931. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  84932. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  84933. // Computing target and final matrix
  84934. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  84935. // should the view matrix be updated with scale and position offset?
  84936. if (parentCamera.deviceScaleFactor !== 1) {
  84937. this._webvrViewMatrix.invert();
  84938. // scale the position, if set
  84939. if (parentCamera.deviceScaleFactor) {
  84940. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  84941. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  84942. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  84943. }
  84944. this._webvrViewMatrix.invert();
  84945. }
  84946. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  84947. return this._webvrViewMatrix;
  84948. };
  84949. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  84950. var _this = this;
  84951. var parentCamera = this.parent;
  84952. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  84953. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  84954. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  84955. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  84956. //babylon compatible matrix
  84957. if (!this.getScene().useRightHandedSystem) {
  84958. [8, 9, 10, 11].forEach(function (num) {
  84959. _this._projectionMatrix.m[num] *= -1;
  84960. });
  84961. }
  84962. return this._projectionMatrix;
  84963. };
  84964. /**
  84965. * Initializes the controllers and their meshes
  84966. */
  84967. WebVRFreeCamera.prototype.initControllers = function () {
  84968. var _this = this;
  84969. this.controllers = [];
  84970. var manager = this.getScene().gamepadManager;
  84971. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  84972. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  84973. var webVrController = gamepad;
  84974. if (webVrController.defaultModel) {
  84975. webVrController.defaultModel.setEnabled(false);
  84976. }
  84977. if (webVrController.hand === "right") {
  84978. _this._rightController = null;
  84979. }
  84980. if (webVrController.hand === "left") {
  84981. _this._leftController = null;
  84982. }
  84983. var controllerIndex = _this.controllers.indexOf(webVrController);
  84984. if (controllerIndex !== -1) {
  84985. _this.controllers.splice(controllerIndex, 1);
  84986. }
  84987. }
  84988. });
  84989. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  84990. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  84991. var webVrController_1 = gamepad;
  84992. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  84993. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  84994. if (_this.webVROptions.controllerMeshes) {
  84995. if (webVrController_1.defaultModel) {
  84996. webVrController_1.defaultModel.setEnabled(true);
  84997. }
  84998. else {
  84999. // Load the meshes
  85000. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  85001. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  85002. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  85003. if (_this.webVROptions.defaultLightingOnControllers) {
  85004. if (!_this._lightOnControllers) {
  85005. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  85006. }
  85007. var activateLightOnSubMeshes_1 = function (mesh, light) {
  85008. var children = mesh.getChildren();
  85009. if (children.length !== 0) {
  85010. children.forEach(function (mesh) {
  85011. light.includedOnlyMeshes.push(mesh);
  85012. activateLightOnSubMeshes_1(mesh, light);
  85013. });
  85014. }
  85015. };
  85016. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  85017. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  85018. }
  85019. });
  85020. }
  85021. }
  85022. webVrController_1.attachToPoseControlledCamera(_this);
  85023. // since this is async - sanity check. Is the controller already stored?
  85024. if (_this.controllers.indexOf(webVrController_1) === -1) {
  85025. //add to the controllers array
  85026. _this.controllers.push(webVrController_1);
  85027. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  85028. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  85029. // So we're overriding setting left & right manually to be sure
  85030. var firstViveWandDetected = false;
  85031. for (var i = 0; i < _this.controllers.length; i++) {
  85032. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  85033. if (!firstViveWandDetected) {
  85034. firstViveWandDetected = true;
  85035. _this.controllers[i].hand = "left";
  85036. }
  85037. else {
  85038. _this.controllers[i].hand = "right";
  85039. }
  85040. }
  85041. }
  85042. //did we find enough controllers? Great! let the developer know.
  85043. if (_this.controllers.length >= 2) {
  85044. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  85045. }
  85046. }
  85047. }
  85048. });
  85049. };
  85050. return WebVRFreeCamera;
  85051. }(BABYLON.FreeCamera));
  85052. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  85053. })(BABYLON || (BABYLON = {}));
  85054. //# sourceMappingURL=babylon.webVRCamera.js.map
  85055. "use strict";
  85056. var BABYLON;
  85057. (function (BABYLON) {
  85058. // We're mainly based on the logic defined into the FreeCamera code
  85059. /**
  85060. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  85061. * being tilted forward or back and left or right.
  85062. */
  85063. var DeviceOrientationCamera = /** @class */ (function (_super) {
  85064. __extends(DeviceOrientationCamera, _super);
  85065. /**
  85066. * Creates a new device orientation camera
  85067. * @param name The name of the camera
  85068. * @param position The start position camera
  85069. * @param scene The scene the camera belongs to
  85070. */
  85071. function DeviceOrientationCamera(name, position, scene) {
  85072. var _this = _super.call(this, name, position, scene) || this;
  85073. _this._quaternionCache = new BABYLON.Quaternion();
  85074. _this.inputs.addDeviceOrientation();
  85075. return _this;
  85076. }
  85077. /**
  85078. * Gets the current instance class name ("DeviceOrientationCamera").
  85079. * This helps avoiding instanceof at run time.
  85080. * @returns the class name
  85081. */
  85082. DeviceOrientationCamera.prototype.getClassName = function () {
  85083. return "DeviceOrientationCamera";
  85084. };
  85085. /**
  85086. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  85087. */
  85088. DeviceOrientationCamera.prototype._checkInputs = function () {
  85089. _super.prototype._checkInputs.call(this);
  85090. this._quaternionCache.copyFrom(this.rotationQuaternion);
  85091. if (this._initialQuaternion) {
  85092. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85093. }
  85094. };
  85095. /**
  85096. * Reset the camera to its default orientation on the specified axis only.
  85097. * @param axis The axis to reset
  85098. */
  85099. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  85100. var _this = this;
  85101. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  85102. //can only work if this camera has a rotation quaternion already.
  85103. if (!this.rotationQuaternion)
  85104. return;
  85105. if (!this._initialQuaternion) {
  85106. this._initialQuaternion = new BABYLON.Quaternion();
  85107. }
  85108. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  85109. ['x', 'y', 'z'].forEach(function (axisName) {
  85110. if (!axis[axisName]) {
  85111. _this._initialQuaternion[axisName] = 0;
  85112. }
  85113. else {
  85114. _this._initialQuaternion[axisName] *= -1;
  85115. }
  85116. });
  85117. this._initialQuaternion.normalize();
  85118. //force rotation update
  85119. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  85120. };
  85121. return DeviceOrientationCamera;
  85122. }(BABYLON.FreeCamera));
  85123. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  85124. })(BABYLON || (BABYLON = {}));
  85125. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  85126. "use strict";
  85127. var BABYLON;
  85128. (function (BABYLON) {
  85129. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  85130. __extends(VRDeviceOrientationFreeCamera, _super);
  85131. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85132. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85133. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85134. var _this = _super.call(this, name, position, scene) || this;
  85135. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85136. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85137. return _this;
  85138. }
  85139. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  85140. return "VRDeviceOrientationFreeCamera";
  85141. };
  85142. return VRDeviceOrientationFreeCamera;
  85143. }(BABYLON.DeviceOrientationCamera));
  85144. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  85145. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  85146. __extends(VRDeviceOrientationGamepadCamera, _super);
  85147. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  85148. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85149. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85150. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  85151. _this.inputs.addGamepad();
  85152. return _this;
  85153. }
  85154. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  85155. return "VRDeviceOrientationGamepadCamera";
  85156. };
  85157. return VRDeviceOrientationGamepadCamera;
  85158. }(VRDeviceOrientationFreeCamera));
  85159. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  85160. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  85161. __extends(VRDeviceOrientationArcRotateCamera, _super);
  85162. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  85163. if (compensateDistortion === void 0) { compensateDistortion = true; }
  85164. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  85165. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85166. vrCameraMetrics.compensateDistortion = compensateDistortion;
  85167. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  85168. _this.inputs.addVRDeviceOrientation();
  85169. return _this;
  85170. }
  85171. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  85172. return "VRDeviceOrientationArcRotateCamera";
  85173. };
  85174. return VRDeviceOrientationArcRotateCamera;
  85175. }(BABYLON.ArcRotateCamera));
  85176. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  85177. })(BABYLON || (BABYLON = {}));
  85178. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  85179. "use strict";
  85180. var BABYLON;
  85181. (function (BABYLON) {
  85182. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  85183. __extends(AnaglyphFreeCamera, _super);
  85184. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  85185. var _this = _super.call(this, name, position, scene) || this;
  85186. _this.interaxialDistance = interaxialDistance;
  85187. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85188. return _this;
  85189. }
  85190. AnaglyphFreeCamera.prototype.getClassName = function () {
  85191. return "AnaglyphFreeCamera";
  85192. };
  85193. return AnaglyphFreeCamera;
  85194. }(BABYLON.FreeCamera));
  85195. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  85196. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  85197. __extends(AnaglyphArcRotateCamera, _super);
  85198. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  85199. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85200. _this.interaxialDistance = interaxialDistance;
  85201. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85202. return _this;
  85203. }
  85204. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  85205. return "AnaglyphArcRotateCamera";
  85206. };
  85207. return AnaglyphArcRotateCamera;
  85208. }(BABYLON.ArcRotateCamera));
  85209. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  85210. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  85211. __extends(AnaglyphGamepadCamera, _super);
  85212. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  85213. var _this = _super.call(this, name, position, scene) || this;
  85214. _this.interaxialDistance = interaxialDistance;
  85215. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85216. return _this;
  85217. }
  85218. AnaglyphGamepadCamera.prototype.getClassName = function () {
  85219. return "AnaglyphGamepadCamera";
  85220. };
  85221. return AnaglyphGamepadCamera;
  85222. }(BABYLON.GamepadCamera));
  85223. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  85224. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  85225. __extends(AnaglyphUniversalCamera, _super);
  85226. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  85227. var _this = _super.call(this, name, position, scene) || this;
  85228. _this.interaxialDistance = interaxialDistance;
  85229. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  85230. return _this;
  85231. }
  85232. AnaglyphUniversalCamera.prototype.getClassName = function () {
  85233. return "AnaglyphUniversalCamera";
  85234. };
  85235. return AnaglyphUniversalCamera;
  85236. }(BABYLON.UniversalCamera));
  85237. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  85238. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  85239. __extends(StereoscopicFreeCamera, _super);
  85240. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85241. var _this = _super.call(this, name, position, scene) || this;
  85242. _this.interaxialDistance = interaxialDistance;
  85243. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85244. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85245. return _this;
  85246. }
  85247. StereoscopicFreeCamera.prototype.getClassName = function () {
  85248. return "StereoscopicFreeCamera";
  85249. };
  85250. return StereoscopicFreeCamera;
  85251. }(BABYLON.FreeCamera));
  85252. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  85253. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  85254. __extends(StereoscopicArcRotateCamera, _super);
  85255. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  85256. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  85257. _this.interaxialDistance = interaxialDistance;
  85258. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85259. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85260. return _this;
  85261. }
  85262. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  85263. return "StereoscopicArcRotateCamera";
  85264. };
  85265. return StereoscopicArcRotateCamera;
  85266. }(BABYLON.ArcRotateCamera));
  85267. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  85268. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  85269. __extends(StereoscopicGamepadCamera, _super);
  85270. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85271. var _this = _super.call(this, name, position, scene) || this;
  85272. _this.interaxialDistance = interaxialDistance;
  85273. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85274. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85275. return _this;
  85276. }
  85277. StereoscopicGamepadCamera.prototype.getClassName = function () {
  85278. return "StereoscopicGamepadCamera";
  85279. };
  85280. return StereoscopicGamepadCamera;
  85281. }(BABYLON.GamepadCamera));
  85282. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  85283. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  85284. __extends(StereoscopicUniversalCamera, _super);
  85285. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  85286. var _this = _super.call(this, name, position, scene) || this;
  85287. _this.interaxialDistance = interaxialDistance;
  85288. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  85289. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  85290. return _this;
  85291. }
  85292. StereoscopicUniversalCamera.prototype.getClassName = function () {
  85293. return "StereoscopicUniversalCamera";
  85294. };
  85295. return StereoscopicUniversalCamera;
  85296. }(BABYLON.UniversalCamera));
  85297. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  85298. })(BABYLON || (BABYLON = {}));
  85299. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  85300. "use strict";
  85301. var BABYLON;
  85302. (function (BABYLON) {
  85303. var VRExperienceHelperGazer = /** @class */ (function () {
  85304. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  85305. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  85306. this.scene = scene;
  85307. this._pointerDownOnMeshAsked = false;
  85308. this._isActionableMesh = false;
  85309. this._teleportationRequestInitiated = false;
  85310. this._teleportationBackRequestInitiated = false;
  85311. this._dpadPressed = true;
  85312. this._activePointer = false;
  85313. this._id = VRExperienceHelperGazer._idCounter++;
  85314. // Gaze tracker
  85315. if (!gazeTrackerToClone) {
  85316. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  85317. this._gazeTracker.bakeCurrentTransformIntoVertices();
  85318. this._gazeTracker.isPickable = false;
  85319. this._gazeTracker.isVisible = false;
  85320. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  85321. targetMat.specularColor = BABYLON.Color3.Black();
  85322. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  85323. targetMat.backFaceCulling = false;
  85324. this._gazeTracker.material = targetMat;
  85325. }
  85326. else {
  85327. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  85328. }
  85329. }
  85330. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  85331. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  85332. };
  85333. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  85334. this._pointerDownOnMeshAsked = true;
  85335. if (this._currentMeshSelected && this._currentHit) {
  85336. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  85337. }
  85338. };
  85339. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  85340. if (this._currentMeshSelected && this._currentHit) {
  85341. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  85342. }
  85343. this._pointerDownOnMeshAsked = false;
  85344. };
  85345. VRExperienceHelperGazer.prototype._activatePointer = function () {
  85346. this._activePointer = true;
  85347. };
  85348. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  85349. this._activePointer = false;
  85350. };
  85351. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  85352. };
  85353. VRExperienceHelperGazer.prototype.dispose = function () {
  85354. this._interactionsEnabled = false;
  85355. this._teleportationEnabled = false;
  85356. };
  85357. VRExperienceHelperGazer._idCounter = 0;
  85358. return VRExperienceHelperGazer;
  85359. }());
  85360. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  85361. __extends(VRExperienceHelperControllerGazer, _super);
  85362. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  85363. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  85364. _this.webVRController = webVRController;
  85365. // Laser pointer
  85366. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  85367. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  85368. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  85369. laserPointerMaterial.alpha = 0.6;
  85370. _this._laserPointer.material = laserPointerMaterial;
  85371. _this._laserPointer.rotation.x = Math.PI / 2;
  85372. _this._laserPointer.position.z = -0.5;
  85373. _this._laserPointer.isVisible = false;
  85374. if (!webVRController.mesh) {
  85375. // Create an empty mesh that is used prior to loading the high quality model
  85376. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  85377. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  85378. preloadPointerPose.rotation.x = -0.7;
  85379. preloadMesh.addChild(preloadPointerPose);
  85380. webVRController.attachToMesh(preloadMesh);
  85381. }
  85382. _this._setLaserPointerParent(webVRController.mesh);
  85383. return _this;
  85384. }
  85385. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  85386. return this.webVRController.getForwardRay(length);
  85387. };
  85388. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  85389. _super.prototype._activatePointer.call(this);
  85390. this._laserPointer.isVisible = true;
  85391. };
  85392. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  85393. _super.prototype._deactivatePointer.call(this);
  85394. this._laserPointer.isVisible = false;
  85395. };
  85396. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  85397. this._laserPointer.material.emissiveColor = color;
  85398. };
  85399. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  85400. var makeNotPick = function (root) {
  85401. root.name += " laserPointer";
  85402. root.getChildMeshes().forEach(function (c) {
  85403. makeNotPick(c);
  85404. });
  85405. };
  85406. makeNotPick(mesh);
  85407. var childMeshes = mesh.getChildMeshes();
  85408. this.webVRController._pointingPoseNode = null;
  85409. for (var i = 0; i < childMeshes.length; i++) {
  85410. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  85411. mesh = childMeshes[i];
  85412. this.webVRController._pointingPoseNode = mesh;
  85413. break;
  85414. }
  85415. }
  85416. this._laserPointer.parent = mesh;
  85417. };
  85418. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  85419. this._laserPointer.scaling.y = distance;
  85420. this._laserPointer.position.z = -distance / 2;
  85421. };
  85422. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  85423. _super.prototype.dispose.call(this);
  85424. this._laserPointer.dispose();
  85425. };
  85426. return VRExperienceHelperControllerGazer;
  85427. }(VRExperienceHelperGazer));
  85428. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  85429. __extends(VRExperienceHelperCameraGazer, _super);
  85430. function VRExperienceHelperCameraGazer(getCamera, scene) {
  85431. var _this = _super.call(this, scene) || this;
  85432. _this.getCamera = getCamera;
  85433. return _this;
  85434. }
  85435. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  85436. var camera = this.getCamera();
  85437. if (camera) {
  85438. return camera.getForwardRay(length);
  85439. }
  85440. else {
  85441. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  85442. }
  85443. };
  85444. return VRExperienceHelperCameraGazer;
  85445. }(VRExperienceHelperGazer));
  85446. /**
  85447. * Helps to quickly add VR support to an existing scene.
  85448. * See http://doc.babylonjs.com/how_to/webvr_helper
  85449. */
  85450. var VRExperienceHelper = /** @class */ (function () {
  85451. /**
  85452. * Instantiates a VRExperienceHelper.
  85453. * Helps to quickly add VR support to an existing scene.
  85454. * @param scene The scene the VRExperienceHelper belongs to.
  85455. * @param webVROptions Options to modify the vr experience helper's behavior.
  85456. */
  85457. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  85458. if (webVROptions === void 0) { webVROptions = {}; }
  85459. var _this = this;
  85460. this.webVROptions = webVROptions;
  85461. // Can the system support WebVR, even if a headset isn't plugged in?
  85462. this._webVRsupported = false;
  85463. // If WebVR is supported, is a headset plugged in and are we ready to present?
  85464. this._webVRready = false;
  85465. // Are we waiting for the requestPresent callback to complete?
  85466. this._webVRrequesting = false;
  85467. // Are we presenting to the headset right now?
  85468. this._webVRpresenting = false;
  85469. // Are we presenting in the fullscreen fallback?
  85470. this._fullscreenVRpresenting = false;
  85471. /**
  85472. * Observable raised when entering VR.
  85473. */
  85474. this.onEnteringVRObservable = new BABYLON.Observable();
  85475. /**
  85476. * Observable raised when exiting VR.
  85477. */
  85478. this.onExitingVRObservable = new BABYLON.Observable();
  85479. /**
  85480. * Observable raised when controller mesh is loaded.
  85481. */
  85482. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85483. this._useCustomVRButton = false;
  85484. this._teleportationRequested = false;
  85485. this._teleportActive = false;
  85486. this._floorMeshesCollection = [];
  85487. this._rotationAllowed = true;
  85488. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  85489. this._rotationRightAsked = false;
  85490. this._rotationLeftAsked = false;
  85491. this._isDefaultTeleportationTarget = true;
  85492. this._teleportationFillColor = "#444444";
  85493. this._teleportationBorderColor = "#FFFFFF";
  85494. this._rotationAngle = 0;
  85495. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  85496. this._padSensibilityUp = 0.65;
  85497. this._padSensibilityDown = 0.35;
  85498. this.leftController = null;
  85499. this.rightController = null;
  85500. /**
  85501. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  85502. */
  85503. this.onNewMeshSelected = new BABYLON.Observable();
  85504. /**
  85505. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  85506. */
  85507. this.onNewMeshPicked = new BABYLON.Observable();
  85508. /**
  85509. * Observable raised before camera teleportation
  85510. */
  85511. this.onBeforeCameraTeleport = new BABYLON.Observable();
  85512. /**
  85513. * Observable raised after camera teleportation
  85514. */
  85515. this.onAfterCameraTeleport = new BABYLON.Observable();
  85516. /**
  85517. * Observable raised when current selected mesh gets unselected
  85518. */
  85519. this.onSelectedMeshUnselected = new BABYLON.Observable();
  85520. /**
  85521. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  85522. */
  85523. this.teleportationEnabled = true;
  85524. this._teleportationInitialized = false;
  85525. this._interactionsEnabled = false;
  85526. this._interactionsRequested = false;
  85527. this._displayGaze = true;
  85528. this._displayLaserPointer = true;
  85529. this._onResize = function () {
  85530. _this.moveButtonToBottomRight();
  85531. if (_this._fullscreenVRpresenting && _this._webVRready) {
  85532. _this.exitVR();
  85533. }
  85534. };
  85535. this._onFullscreenChange = function () {
  85536. if (document.fullscreen !== undefined) {
  85537. _this._fullscreenVRpresenting = document.fullscreen;
  85538. }
  85539. else if (document.mozFullScreen !== undefined) {
  85540. _this._fullscreenVRpresenting = document.mozFullScreen;
  85541. }
  85542. else if (document.webkitIsFullScreen !== undefined) {
  85543. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  85544. }
  85545. else if (document.msIsFullScreen !== undefined) {
  85546. _this._fullscreenVRpresenting = document.msIsFullScreen;
  85547. }
  85548. if (!_this._fullscreenVRpresenting && _this._canvas) {
  85549. _this.exitVR();
  85550. if (!_this._useCustomVRButton) {
  85551. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  85552. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  85553. }
  85554. }
  85555. };
  85556. this.beforeRender = function () {
  85557. if (_this.leftController && _this.leftController._activePointer) {
  85558. _this._castRayAndSelectObject(_this.leftController);
  85559. }
  85560. if (_this.rightController && _this.rightController._activePointer) {
  85561. _this._castRayAndSelectObject(_this.rightController);
  85562. }
  85563. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  85564. _this._castRayAndSelectObject(_this._cameraGazer);
  85565. }
  85566. else {
  85567. _this._cameraGazer._gazeTracker.isVisible = false;
  85568. }
  85569. };
  85570. this._onNewGamepadConnected = function (gamepad) {
  85571. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  85572. if (gamepad.leftStick) {
  85573. gamepad.onleftstickchanged(function (stickValues) {
  85574. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  85575. // Listening to classic/xbox gamepad only if no VR controller is active
  85576. if ((!_this.leftController && !_this.rightController) ||
  85577. ((_this.leftController && !_this.leftController._activePointer) &&
  85578. (_this.rightController && !_this.rightController._activePointer))) {
  85579. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  85580. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  85581. }
  85582. }
  85583. });
  85584. }
  85585. if (gamepad.rightStick) {
  85586. gamepad.onrightstickchanged(function (stickValues) {
  85587. if (_this._teleportationInitialized) {
  85588. _this._checkRotate(stickValues, _this._cameraGazer);
  85589. }
  85590. });
  85591. }
  85592. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  85593. gamepad.onbuttondown(function (buttonPressed) {
  85594. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  85595. _this._cameraGazer._selectionPointerDown();
  85596. }
  85597. });
  85598. gamepad.onbuttonup(function (buttonPressed) {
  85599. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  85600. _this._cameraGazer._selectionPointerUp();
  85601. }
  85602. });
  85603. }
  85604. }
  85605. else {
  85606. var webVRController = gamepad;
  85607. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  85608. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  85609. _this.rightController = controller;
  85610. }
  85611. else {
  85612. _this.leftController = controller;
  85613. }
  85614. _this._tryEnableInteractionOnController(controller);
  85615. }
  85616. };
  85617. // 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
  85618. this._tryEnableInteractionOnController = function (controller) {
  85619. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  85620. _this._enableInteractionOnController(controller);
  85621. }
  85622. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  85623. _this._enableTeleportationOnController(controller);
  85624. }
  85625. };
  85626. this._onNewGamepadDisconnected = function (gamepad) {
  85627. if (gamepad instanceof BABYLON.WebVRController) {
  85628. if (gamepad.hand === "left" && _this.leftController != null) {
  85629. _this.leftController.dispose();
  85630. _this.leftController = null;
  85631. }
  85632. if (gamepad.hand === "right" && _this.rightController != null) {
  85633. _this.rightController.dispose();
  85634. _this.rightController = null;
  85635. }
  85636. }
  85637. };
  85638. this._workingVector = BABYLON.Vector3.Zero();
  85639. this._workingQuaternion = BABYLON.Quaternion.Identity();
  85640. this._workingMatrix = BABYLON.Matrix.Identity();
  85641. this._scene = scene;
  85642. this._canvas = scene.getEngine().getRenderingCanvas();
  85643. // Parse options
  85644. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  85645. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  85646. }
  85647. if (webVROptions.createDeviceOrientationCamera === undefined) {
  85648. webVROptions.createDeviceOrientationCamera = true;
  85649. }
  85650. if (webVROptions.defaultHeight === undefined) {
  85651. webVROptions.defaultHeight = 1.7;
  85652. }
  85653. if (webVROptions.useCustomVRButton) {
  85654. this._useCustomVRButton = true;
  85655. if (webVROptions.customVRButton) {
  85656. this._btnVR = webVROptions.customVRButton;
  85657. }
  85658. }
  85659. if (webVROptions.rayLength) {
  85660. this._rayLength = webVROptions.rayLength;
  85661. }
  85662. this._defaultHeight = webVROptions.defaultHeight;
  85663. if (webVROptions.positionScale) {
  85664. this._rayLength *= webVROptions.positionScale;
  85665. this._defaultHeight *= webVROptions.positionScale;
  85666. }
  85667. // Set position
  85668. if (this._scene.activeCamera) {
  85669. this._position = this._scene.activeCamera.position.clone();
  85670. }
  85671. else {
  85672. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  85673. }
  85674. // Set non-vr camera
  85675. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  85676. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  85677. // Copy data from existing camera
  85678. if (this._scene.activeCamera) {
  85679. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  85680. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  85681. // Set rotation from previous camera
  85682. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  85683. var targetCamera = this._scene.activeCamera;
  85684. if (targetCamera.rotationQuaternion) {
  85685. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  85686. }
  85687. else {
  85688. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  85689. }
  85690. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  85691. }
  85692. }
  85693. this._scene.activeCamera = this._deviceOrientationCamera;
  85694. if (this._canvas) {
  85695. this._scene.activeCamera.attachControl(this._canvas);
  85696. }
  85697. }
  85698. else {
  85699. this._existingCamera = this._scene.activeCamera;
  85700. }
  85701. // Create VR cameras
  85702. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  85703. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  85704. }
  85705. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  85706. this._webVRCamera.useStandingMatrix();
  85707. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  85708. // Create default button
  85709. if (!this._useCustomVRButton) {
  85710. this._btnVR = document.createElement("BUTTON");
  85711. this._btnVR.className = "babylonVRicon";
  85712. this._btnVR.id = "babylonVRiconbtn";
  85713. this._btnVR.title = "Click to switch to VR";
  85714. 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) }";
  85715. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  85716. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  85717. // css += ".babylonVRicon.vrdisplaysupported { }";
  85718. // css += ".babylonVRicon.vrdisplayready { }";
  85719. // css += ".babylonVRicon.vrdisplayrequesting { }";
  85720. var style = document.createElement('style');
  85721. style.appendChild(document.createTextNode(css));
  85722. document.getElementsByTagName('head')[0].appendChild(style);
  85723. this.moveButtonToBottomRight();
  85724. }
  85725. // VR button click event
  85726. if (this._btnVR) {
  85727. this._btnVR.addEventListener("click", function () {
  85728. if (!_this.isInVRMode) {
  85729. _this.enterVR();
  85730. }
  85731. else {
  85732. _this.exitVR();
  85733. }
  85734. });
  85735. }
  85736. // Window events
  85737. window.addEventListener("resize", this._onResize);
  85738. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  85739. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  85740. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  85741. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  85742. // Display vr button when headset is connected
  85743. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  85744. this.displayVRButton();
  85745. }
  85746. else {
  85747. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  85748. if (e.vrDisplay) {
  85749. _this.displayVRButton();
  85750. }
  85751. });
  85752. }
  85753. // Exiting VR mode using 'ESC' key on desktop
  85754. this._onKeyDown = function (event) {
  85755. if (event.keyCode === 27 && _this.isInVRMode) {
  85756. _this.exitVR();
  85757. }
  85758. };
  85759. document.addEventListener("keydown", this._onKeyDown);
  85760. // Exiting VR mode double tapping the touch screen
  85761. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  85762. if (_this.isInVRMode) {
  85763. _this.exitVR();
  85764. if (_this._fullscreenVRpresenting) {
  85765. _this._scene.getEngine().switchFullscreen(true);
  85766. }
  85767. }
  85768. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  85769. // Listen for WebVR display changes
  85770. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  85771. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  85772. this._onVRRequestPresentStart = function () {
  85773. _this._webVRrequesting = true;
  85774. _this.updateButtonVisibility();
  85775. };
  85776. this._onVRRequestPresentComplete = function (success) {
  85777. _this._webVRrequesting = false;
  85778. _this.updateButtonVisibility();
  85779. };
  85780. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  85781. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  85782. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  85783. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  85784. scene.onDisposeObservable.add(function () {
  85785. _this.dispose();
  85786. });
  85787. // Gamepad connection events
  85788. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  85789. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  85790. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  85791. this.updateButtonVisibility();
  85792. //create easing functions
  85793. this._circleEase = new BABYLON.CircleEase();
  85794. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  85795. }
  85796. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  85797. /** Return this.onEnteringVRObservable
  85798. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  85799. */
  85800. get: function () {
  85801. return this.onEnteringVRObservable;
  85802. },
  85803. enumerable: true,
  85804. configurable: true
  85805. });
  85806. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  85807. /** Return this.onExitingVRObservable
  85808. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  85809. */
  85810. get: function () {
  85811. return this.onExitingVRObservable;
  85812. },
  85813. enumerable: true,
  85814. configurable: true
  85815. });
  85816. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  85817. /** Return this.onControllerMeshLoadedObservable
  85818. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  85819. */
  85820. get: function () {
  85821. return this.onControllerMeshLoadedObservable;
  85822. },
  85823. enumerable: true,
  85824. configurable: true
  85825. });
  85826. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  85827. /**
  85828. * The mesh used to display where the user is going to teleport.
  85829. */
  85830. get: function () {
  85831. return this._teleportationTarget;
  85832. },
  85833. /**
  85834. * Sets the mesh to be used to display where the user is going to teleport.
  85835. */
  85836. set: function (value) {
  85837. if (value) {
  85838. value.name = "teleportationTarget";
  85839. this._isDefaultTeleportationTarget = false;
  85840. this._teleportationTarget = value;
  85841. }
  85842. },
  85843. enumerable: true,
  85844. configurable: true
  85845. });
  85846. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  85847. /**
  85848. * The mesh used to display where the user is selecting,
  85849. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  85850. * See http://doc.babylonjs.com/resources/baking_transformations
  85851. */
  85852. get: function () {
  85853. return this._cameraGazer._gazeTracker;
  85854. },
  85855. set: function (value) {
  85856. if (value) {
  85857. this._cameraGazer._gazeTracker = value;
  85858. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  85859. this._cameraGazer._gazeTracker.isPickable = false;
  85860. this._cameraGazer._gazeTracker.isVisible = false;
  85861. this._cameraGazer._gazeTracker.name = "gazeTracker";
  85862. if (this.leftController) {
  85863. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  85864. }
  85865. if (this.rightController) {
  85866. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  85867. }
  85868. }
  85869. },
  85870. enumerable: true,
  85871. configurable: true
  85872. });
  85873. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  85874. /**
  85875. * If the ray of the gaze should be displayed.
  85876. */
  85877. get: function () {
  85878. return this._displayGaze;
  85879. },
  85880. /**
  85881. * Sets if the ray of the gaze should be displayed.
  85882. */
  85883. set: function (value) {
  85884. this._displayGaze = value;
  85885. if (!value) {
  85886. this._cameraGazer._gazeTracker.isVisible = false;
  85887. if (this.leftController) {
  85888. this.leftController._gazeTracker.isVisible = false;
  85889. }
  85890. if (this.rightController) {
  85891. this.rightController._gazeTracker.isVisible = false;
  85892. }
  85893. }
  85894. },
  85895. enumerable: true,
  85896. configurable: true
  85897. });
  85898. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  85899. /**
  85900. * If the ray of the LaserPointer should be displayed.
  85901. */
  85902. get: function () {
  85903. return this._displayLaserPointer;
  85904. },
  85905. /**
  85906. * Sets if the ray of the LaserPointer should be displayed.
  85907. */
  85908. set: function (value) {
  85909. this._displayLaserPointer = value;
  85910. if (!value) {
  85911. if (this.rightController) {
  85912. this.rightController._deactivatePointer();
  85913. this.rightController._gazeTracker.isVisible = false;
  85914. }
  85915. if (this.leftController) {
  85916. this.leftController._deactivatePointer();
  85917. this.leftController._gazeTracker.isVisible = false;
  85918. }
  85919. }
  85920. else {
  85921. if (this.rightController) {
  85922. this.rightController._activatePointer();
  85923. }
  85924. else if (this.leftController) {
  85925. this.leftController._activatePointer();
  85926. }
  85927. }
  85928. },
  85929. enumerable: true,
  85930. configurable: true
  85931. });
  85932. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  85933. /**
  85934. * The deviceOrientationCamera used as the camera when not in VR.
  85935. */
  85936. get: function () {
  85937. return this._deviceOrientationCamera;
  85938. },
  85939. enumerable: true,
  85940. configurable: true
  85941. });
  85942. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  85943. /**
  85944. * Based on the current WebVR support, returns the current VR camera used.
  85945. */
  85946. get: function () {
  85947. if (this._webVRready) {
  85948. return this._webVRCamera;
  85949. }
  85950. else {
  85951. return this._scene.activeCamera;
  85952. }
  85953. },
  85954. enumerable: true,
  85955. configurable: true
  85956. });
  85957. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  85958. /**
  85959. * The webVRCamera which is used when in VR.
  85960. */
  85961. get: function () {
  85962. return this._webVRCamera;
  85963. },
  85964. enumerable: true,
  85965. configurable: true
  85966. });
  85967. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  85968. /**
  85969. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  85970. */
  85971. get: function () {
  85972. return this._vrDeviceOrientationCamera;
  85973. },
  85974. enumerable: true,
  85975. configurable: true
  85976. });
  85977. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  85978. get: function () {
  85979. var result = this._cameraGazer._teleportationRequestInitiated
  85980. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  85981. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  85982. return result;
  85983. },
  85984. enumerable: true,
  85985. configurable: true
  85986. });
  85987. // Raised when one of the controller has loaded successfully its associated default mesh
  85988. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  85989. if (this.leftController && this.leftController.webVRController == webVRController) {
  85990. if (webVRController.mesh) {
  85991. this.leftController._setLaserPointerParent(webVRController.mesh);
  85992. }
  85993. }
  85994. if (this.rightController && this.rightController.webVRController == webVRController) {
  85995. if (webVRController.mesh) {
  85996. this.rightController._setLaserPointerParent(webVRController.mesh);
  85997. }
  85998. }
  85999. try {
  86000. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  86001. }
  86002. catch (err) {
  86003. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  86004. }
  86005. };
  86006. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  86007. /**
  86008. * Gets a value indicating if we are currently in VR mode.
  86009. */
  86010. get: function () {
  86011. return this._webVRpresenting || this._fullscreenVRpresenting;
  86012. },
  86013. enumerable: true,
  86014. configurable: true
  86015. });
  86016. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  86017. var vrDisplay = this._scene.getEngine().getVRDevice();
  86018. if (vrDisplay) {
  86019. var wasPresenting = this._webVRpresenting;
  86020. // A VR display is connected
  86021. this._webVRpresenting = vrDisplay.isPresenting;
  86022. if (wasPresenting && !this._webVRpresenting)
  86023. this.exitVR();
  86024. }
  86025. else {
  86026. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  86027. }
  86028. this.updateButtonVisibility();
  86029. };
  86030. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  86031. this._webVRsupported = eventArgs.vrSupported;
  86032. this._webVRready = !!eventArgs.vrDisplay;
  86033. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  86034. this.updateButtonVisibility();
  86035. };
  86036. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  86037. if (this._canvas && !this._useCustomVRButton) {
  86038. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  86039. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  86040. }
  86041. };
  86042. VRExperienceHelper.prototype.displayVRButton = function () {
  86043. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  86044. document.body.appendChild(this._btnVR);
  86045. this._btnVRDisplayed = true;
  86046. }
  86047. };
  86048. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  86049. if (!this._btnVR || this._useCustomVRButton) {
  86050. return;
  86051. }
  86052. this._btnVR.className = "babylonVRicon";
  86053. if (this.isInVRMode) {
  86054. this._btnVR.className += " vrdisplaypresenting";
  86055. }
  86056. else {
  86057. if (this._webVRready)
  86058. this._btnVR.className += " vrdisplayready";
  86059. if (this._webVRsupported)
  86060. this._btnVR.className += " vrdisplaysupported";
  86061. if (this._webVRrequesting)
  86062. this._btnVR.className += " vrdisplayrequesting";
  86063. }
  86064. };
  86065. /**
  86066. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  86067. * Otherwise, will use the fullscreen API.
  86068. */
  86069. VRExperienceHelper.prototype.enterVR = function () {
  86070. if (this.onEnteringVRObservable) {
  86071. try {
  86072. this.onEnteringVRObservable.notifyObservers(this);
  86073. }
  86074. catch (err) {
  86075. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  86076. }
  86077. }
  86078. if (this._scene.activeCamera) {
  86079. this._position = this._scene.activeCamera.position.clone();
  86080. // make sure that we return to the last active camera
  86081. this._existingCamera = this._scene.activeCamera;
  86082. }
  86083. if (this._webVRrequesting)
  86084. return;
  86085. // If WebVR is supported and a headset is connected
  86086. if (this._webVRready) {
  86087. if (!this._webVRpresenting) {
  86088. this._webVRCamera.position = this._position;
  86089. this._scene.activeCamera = this._webVRCamera;
  86090. }
  86091. }
  86092. else if (this._vrDeviceOrientationCamera) {
  86093. this._vrDeviceOrientationCamera.position = this._position;
  86094. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  86095. this._scene.getEngine().switchFullscreen(true);
  86096. this.updateButtonVisibility();
  86097. }
  86098. if (this._scene.activeCamera && this._canvas) {
  86099. this._scene.activeCamera.attachControl(this._canvas);
  86100. }
  86101. if (this._interactionsEnabled) {
  86102. this._scene.registerBeforeRender(this.beforeRender);
  86103. }
  86104. };
  86105. /**
  86106. * Attempt to exit VR, or fullscreen.
  86107. */
  86108. VRExperienceHelper.prototype.exitVR = function () {
  86109. if (this.onExitingVRObservable) {
  86110. try {
  86111. this.onExitingVRObservable.notifyObservers(this);
  86112. }
  86113. catch (err) {
  86114. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  86115. }
  86116. }
  86117. if (this._webVRpresenting) {
  86118. this._scene.getEngine().disableVR();
  86119. }
  86120. if (this._scene.activeCamera) {
  86121. this._position = this._scene.activeCamera.position.clone();
  86122. }
  86123. if (this._deviceOrientationCamera) {
  86124. this._deviceOrientationCamera.position = this._position;
  86125. this._scene.activeCamera = this._deviceOrientationCamera;
  86126. if (this._canvas) {
  86127. this._scene.activeCamera.attachControl(this._canvas);
  86128. }
  86129. }
  86130. else if (this._existingCamera) {
  86131. this._existingCamera.position = this._position;
  86132. this._scene.activeCamera = this._existingCamera;
  86133. }
  86134. this.updateButtonVisibility();
  86135. if (this._interactionsEnabled) {
  86136. this._scene.unregisterBeforeRender(this.beforeRender);
  86137. }
  86138. };
  86139. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  86140. /**
  86141. * The position of the vr experience helper.
  86142. */
  86143. get: function () {
  86144. return this._position;
  86145. },
  86146. /**
  86147. * Sets the position of the vr experience helper.
  86148. */
  86149. set: function (value) {
  86150. this._position = value;
  86151. if (this._scene.activeCamera) {
  86152. this._scene.activeCamera.position = value;
  86153. }
  86154. },
  86155. enumerable: true,
  86156. configurable: true
  86157. });
  86158. /**
  86159. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  86160. */
  86161. VRExperienceHelper.prototype.enableInteractions = function () {
  86162. var _this = this;
  86163. if (!this._interactionsEnabled) {
  86164. this._interactionsRequested = true;
  86165. if (this.leftController) {
  86166. this._enableInteractionOnController(this.leftController);
  86167. }
  86168. if (this.rightController) {
  86169. this._enableInteractionOnController(this.rightController);
  86170. }
  86171. this.raySelectionPredicate = function (mesh) {
  86172. return mesh.isVisible;
  86173. };
  86174. this.meshSelectionPredicate = function (mesh) {
  86175. return true;
  86176. };
  86177. this._raySelectionPredicate = function (mesh) {
  86178. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  86179. && mesh.name.indexOf("teleportationTarget") === -1
  86180. && mesh.name.indexOf("torusTeleportation") === -1
  86181. && mesh.name.indexOf("laserPointer") === -1)) {
  86182. return _this.raySelectionPredicate(mesh);
  86183. }
  86184. return false;
  86185. };
  86186. this._interactionsEnabled = true;
  86187. }
  86188. };
  86189. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  86190. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  86191. if (this._floorMeshesCollection[i].id === mesh.id) {
  86192. return true;
  86193. }
  86194. }
  86195. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  86196. return true;
  86197. }
  86198. return false;
  86199. };
  86200. /**
  86201. * Adds a floor mesh to be used for teleportation.
  86202. * @param floorMesh the mesh to be used for teleportation.
  86203. */
  86204. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  86205. if (!this._floorMeshesCollection) {
  86206. return;
  86207. }
  86208. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  86209. return;
  86210. }
  86211. this._floorMeshesCollection.push(floorMesh);
  86212. };
  86213. /**
  86214. * Removes a floor mesh from being used for teleportation.
  86215. * @param floorMesh the mesh to be removed.
  86216. */
  86217. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  86218. if (!this._floorMeshesCollection) {
  86219. return;
  86220. }
  86221. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  86222. if (meshIndex !== -1) {
  86223. this._floorMeshesCollection.splice(meshIndex, 1);
  86224. }
  86225. };
  86226. /**
  86227. * Enables interactions and teleportation using the VR controllers and gaze.
  86228. * @param vrTeleportationOptions options to modify teleportation behavior.
  86229. */
  86230. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  86231. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  86232. if (!this._teleportationInitialized) {
  86233. this._teleportationRequested = true;
  86234. this.enableInteractions();
  86235. if (vrTeleportationOptions.floorMeshName) {
  86236. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  86237. }
  86238. if (vrTeleportationOptions.floorMeshes) {
  86239. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  86240. }
  86241. if (this.leftController != null) {
  86242. this._enableTeleportationOnController(this.leftController);
  86243. }
  86244. if (this.rightController != null) {
  86245. this._enableTeleportationOnController(this.rightController);
  86246. }
  86247. // Creates an image processing post process for the vignette not relying
  86248. // on the main scene configuration for image processing to reduce setup and spaces
  86249. // (gamma/linear) conflicts.
  86250. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  86251. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  86252. imageProcessingConfiguration.vignetteEnabled = true;
  86253. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  86254. this._webVRCamera.detachPostProcess(this._postProcessMove);
  86255. this._teleportationInitialized = true;
  86256. if (this._isDefaultTeleportationTarget) {
  86257. this._createTeleportationCircles();
  86258. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  86259. }
  86260. }
  86261. };
  86262. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  86263. var _this = this;
  86264. var controllerMesh = controller.webVRController.mesh;
  86265. if (controllerMesh) {
  86266. controller._interactionsEnabled = true;
  86267. controller._activatePointer();
  86268. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  86269. // Enabling / disabling laserPointer
  86270. if (_this._displayLaserPointer && stateObject.value === 1) {
  86271. if (controller._activePointer) {
  86272. controller._deactivatePointer();
  86273. }
  86274. else {
  86275. controller._activatePointer();
  86276. }
  86277. if (_this.displayGaze) {
  86278. controller._gazeTracker.isVisible = controller._activePointer;
  86279. }
  86280. }
  86281. });
  86282. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  86283. if (!controller._pointerDownOnMeshAsked) {
  86284. if (stateObject.value > _this._padSensibilityUp) {
  86285. controller._selectionPointerDown();
  86286. }
  86287. }
  86288. else if (stateObject.value < _this._padSensibilityDown) {
  86289. controller._selectionPointerUp();
  86290. }
  86291. });
  86292. }
  86293. };
  86294. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  86295. // Dont teleport if another gaze already requested teleportation
  86296. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  86297. return;
  86298. }
  86299. if (!gazer._teleportationRequestInitiated) {
  86300. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  86301. gazer._activatePointer();
  86302. gazer._teleportationRequestInitiated = true;
  86303. }
  86304. }
  86305. else {
  86306. // Listening to the proper controller values changes to confirm teleportation
  86307. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  86308. if (this._teleportActive) {
  86309. this._teleportCamera(this._haloCenter);
  86310. }
  86311. gazer._teleportationRequestInitiated = false;
  86312. }
  86313. }
  86314. };
  86315. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  86316. // Only rotate when user is not currently selecting a teleportation location
  86317. if (gazer._teleportationRequestInitiated) {
  86318. return;
  86319. }
  86320. if (!this._rotationLeftAsked) {
  86321. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  86322. this._rotationLeftAsked = true;
  86323. if (this._rotationAllowed) {
  86324. this._rotateCamera(false);
  86325. }
  86326. }
  86327. }
  86328. else {
  86329. if (stateObject.x > -this._padSensibilityDown) {
  86330. this._rotationLeftAsked = false;
  86331. }
  86332. }
  86333. if (!this._rotationRightAsked) {
  86334. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  86335. this._rotationRightAsked = true;
  86336. if (this._rotationAllowed) {
  86337. this._rotateCamera(true);
  86338. }
  86339. }
  86340. }
  86341. else {
  86342. if (stateObject.x < this._padSensibilityDown) {
  86343. this._rotationRightAsked = false;
  86344. }
  86345. }
  86346. };
  86347. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  86348. // Only teleport backwards when user is not currently selecting a teleportation location
  86349. if (gazer._teleportationRequestInitiated) {
  86350. return;
  86351. }
  86352. // Teleport backwards
  86353. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  86354. if (!gazer._teleportationBackRequestInitiated) {
  86355. if (!this.currentVRCamera) {
  86356. return;
  86357. }
  86358. // Get rotation and position of the current camera
  86359. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  86360. var position = this.currentVRCamera.position;
  86361. // If the camera has device position, use that instead
  86362. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  86363. rotation = this.currentVRCamera.deviceRotationQuaternion;
  86364. position = this.currentVRCamera.devicePosition;
  86365. }
  86366. // Get matrix with only the y rotation of the device rotation
  86367. rotation.toEulerAnglesToRef(this._workingVector);
  86368. this._workingVector.z = 0;
  86369. this._workingVector.x = 0;
  86370. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  86371. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  86372. // Rotate backwards ray by device rotation to cast at the ground behind the user
  86373. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  86374. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  86375. var ray = new BABYLON.Ray(position, this._workingVector);
  86376. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  86377. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  86378. this._teleportCamera(hit.pickedPoint);
  86379. }
  86380. gazer._teleportationBackRequestInitiated = true;
  86381. }
  86382. }
  86383. else {
  86384. gazer._teleportationBackRequestInitiated = false;
  86385. }
  86386. };
  86387. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  86388. var _this = this;
  86389. var controllerMesh = controller.webVRController.mesh;
  86390. if (controllerMesh) {
  86391. if (!controller._interactionsEnabled) {
  86392. this._enableInteractionOnController(controller);
  86393. }
  86394. controller._interactionsEnabled = true;
  86395. controller._teleportationEnabled = true;
  86396. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86397. controller._dpadPressed = false;
  86398. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  86399. controller._dpadPressed = stateObject.pressed;
  86400. if (!controller._dpadPressed) {
  86401. _this._rotationLeftAsked = false;
  86402. _this._rotationRightAsked = false;
  86403. controller._teleportationBackRequestInitiated = false;
  86404. }
  86405. });
  86406. }
  86407. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  86408. if (_this.teleportationEnabled) {
  86409. _this._checkTeleportBackwards(stateObject, controller);
  86410. _this._checkTeleportWithRay(stateObject, controller);
  86411. }
  86412. _this._checkRotate(stateObject, controller);
  86413. });
  86414. }
  86415. };
  86416. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  86417. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  86418. this._teleportationTarget.isPickable = false;
  86419. var length = 512;
  86420. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  86421. dynamicTexture.hasAlpha = true;
  86422. var context = dynamicTexture.getContext();
  86423. var centerX = length / 2;
  86424. var centerY = length / 2;
  86425. var radius = 200;
  86426. context.beginPath();
  86427. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  86428. context.fillStyle = this._teleportationFillColor;
  86429. context.fill();
  86430. context.lineWidth = 10;
  86431. context.strokeStyle = this._teleportationBorderColor;
  86432. context.stroke();
  86433. context.closePath();
  86434. dynamicTexture.update();
  86435. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  86436. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  86437. this._teleportationTarget.material = teleportationCircleMaterial;
  86438. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  86439. torus.isPickable = false;
  86440. torus.parent = this._teleportationTarget;
  86441. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  86442. var keys = [];
  86443. keys.push({
  86444. frame: 0,
  86445. value: 0
  86446. });
  86447. keys.push({
  86448. frame: 30,
  86449. value: 0.4
  86450. });
  86451. keys.push({
  86452. frame: 60,
  86453. value: 0
  86454. });
  86455. animationInnerCircle.setKeys(keys);
  86456. var easingFunction = new BABYLON.SineEase();
  86457. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  86458. animationInnerCircle.setEasingFunction(easingFunction);
  86459. torus.animations = [];
  86460. torus.animations.push(animationInnerCircle);
  86461. this._scene.beginAnimation(torus, 0, 60, true);
  86462. this._hideTeleportationTarget();
  86463. };
  86464. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  86465. this._teleportActive = true;
  86466. if (this._teleportationInitialized) {
  86467. this._teleportationTarget.isVisible = true;
  86468. if (this._isDefaultTeleportationTarget) {
  86469. this._teleportationTarget.getChildren()[0].isVisible = true;
  86470. }
  86471. }
  86472. };
  86473. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  86474. this._teleportActive = false;
  86475. if (this._teleportationInitialized) {
  86476. this._teleportationTarget.isVisible = false;
  86477. if (this._isDefaultTeleportationTarget) {
  86478. this._teleportationTarget.getChildren()[0].isVisible = false;
  86479. }
  86480. }
  86481. };
  86482. VRExperienceHelper.prototype._rotateCamera = function (right) {
  86483. var _this = this;
  86484. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86485. return;
  86486. }
  86487. if (right) {
  86488. this._rotationAngle++;
  86489. }
  86490. else {
  86491. this._rotationAngle--;
  86492. }
  86493. this.currentVRCamera.animations = [];
  86494. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  86495. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86496. var animationRotationKeys = [];
  86497. animationRotationKeys.push({
  86498. frame: 0,
  86499. value: this.currentVRCamera.rotationQuaternion
  86500. });
  86501. animationRotationKeys.push({
  86502. frame: 6,
  86503. value: target
  86504. });
  86505. animationRotation.setKeys(animationRotationKeys);
  86506. animationRotation.setEasingFunction(this._circleEase);
  86507. this.currentVRCamera.animations.push(animationRotation);
  86508. this._postProcessMove.animations = [];
  86509. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86510. var vignetteWeightKeys = [];
  86511. vignetteWeightKeys.push({
  86512. frame: 0,
  86513. value: 0
  86514. });
  86515. vignetteWeightKeys.push({
  86516. frame: 3,
  86517. value: 4
  86518. });
  86519. vignetteWeightKeys.push({
  86520. frame: 6,
  86521. value: 0
  86522. });
  86523. animationPP.setKeys(vignetteWeightKeys);
  86524. animationPP.setEasingFunction(this._circleEase);
  86525. this._postProcessMove.animations.push(animationPP);
  86526. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86527. var vignetteStretchKeys = [];
  86528. vignetteStretchKeys.push({
  86529. frame: 0,
  86530. value: 0
  86531. });
  86532. vignetteStretchKeys.push({
  86533. frame: 3,
  86534. value: 10
  86535. });
  86536. vignetteStretchKeys.push({
  86537. frame: 6,
  86538. value: 0
  86539. });
  86540. animationPP2.setKeys(vignetteStretchKeys);
  86541. animationPP2.setEasingFunction(this._circleEase);
  86542. this._postProcessMove.animations.push(animationPP2);
  86543. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86544. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86545. this._postProcessMove.samples = 4;
  86546. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86547. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  86548. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86549. });
  86550. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  86551. };
  86552. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  86553. if (hit.pickedPoint) {
  86554. if (gazer._teleportationRequestInitiated) {
  86555. this._displayTeleportationTarget();
  86556. this._haloCenter.copyFrom(hit.pickedPoint);
  86557. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  86558. }
  86559. var pickNormal = hit.getNormal(true, false);
  86560. if (pickNormal) {
  86561. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86562. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86563. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  86564. }
  86565. this._teleportationTarget.position.y += 0.1;
  86566. }
  86567. };
  86568. VRExperienceHelper.prototype._teleportCamera = function (location) {
  86569. var _this = this;
  86570. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86571. return;
  86572. }
  86573. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  86574. // offset of the headset from the anchor.
  86575. if (this.webVRCamera.leftCamera) {
  86576. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  86577. this._workingVector.subtractInPlace(this.webVRCamera.position);
  86578. location.subtractToRef(this._workingVector, this._workingVector);
  86579. }
  86580. else {
  86581. this._workingVector.copyFrom(location);
  86582. }
  86583. // Add height to account for user's height offset
  86584. if (this.isInVRMode) {
  86585. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  86586. }
  86587. else {
  86588. this._workingVector.y += this._defaultHeight;
  86589. }
  86590. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  86591. // Create animation from the camera's position to the new location
  86592. this.currentVRCamera.animations = [];
  86593. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86594. var animationCameraTeleportationKeys = [{
  86595. frame: 0,
  86596. value: this.currentVRCamera.position
  86597. },
  86598. {
  86599. frame: 11,
  86600. value: this._workingVector
  86601. }
  86602. ];
  86603. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  86604. animationCameraTeleportation.setEasingFunction(this._circleEase);
  86605. this.currentVRCamera.animations.push(animationCameraTeleportation);
  86606. this._postProcessMove.animations = [];
  86607. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86608. var vignetteWeightKeys = [];
  86609. vignetteWeightKeys.push({
  86610. frame: 0,
  86611. value: 0
  86612. });
  86613. vignetteWeightKeys.push({
  86614. frame: 5,
  86615. value: 8
  86616. });
  86617. vignetteWeightKeys.push({
  86618. frame: 11,
  86619. value: 0
  86620. });
  86621. animationPP.setKeys(vignetteWeightKeys);
  86622. this._postProcessMove.animations.push(animationPP);
  86623. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  86624. var vignetteStretchKeys = [];
  86625. vignetteStretchKeys.push({
  86626. frame: 0,
  86627. value: 0
  86628. });
  86629. vignetteStretchKeys.push({
  86630. frame: 5,
  86631. value: 10
  86632. });
  86633. vignetteStretchKeys.push({
  86634. frame: 11,
  86635. value: 0
  86636. });
  86637. animationPP2.setKeys(vignetteStretchKeys);
  86638. this._postProcessMove.animations.push(animationPP2);
  86639. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  86640. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  86641. this._webVRCamera.attachPostProcess(this._postProcessMove);
  86642. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  86643. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  86644. });
  86645. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  86646. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  86647. });
  86648. this._hideTeleportationTarget();
  86649. };
  86650. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  86651. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  86652. return;
  86653. }
  86654. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  86655. // Moving the gazeTracker on the mesh face targetted
  86656. if (hit && hit.pickedPoint) {
  86657. if (this._displayGaze) {
  86658. var multiplier = 1;
  86659. gazer._gazeTracker.isVisible = true;
  86660. if (gazer._isActionableMesh) {
  86661. multiplier = 3;
  86662. }
  86663. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  86664. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  86665. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  86666. var pickNormal = hit.getNormal();
  86667. // To avoid z-fighting
  86668. var deltaFighting = 0.002;
  86669. if (pickNormal) {
  86670. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  86671. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  86672. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  86673. }
  86674. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  86675. if (gazer._gazeTracker.position.x < 0) {
  86676. gazer._gazeTracker.position.x += deltaFighting;
  86677. }
  86678. else {
  86679. gazer._gazeTracker.position.x -= deltaFighting;
  86680. }
  86681. if (gazer._gazeTracker.position.y < 0) {
  86682. gazer._gazeTracker.position.y += deltaFighting;
  86683. }
  86684. else {
  86685. gazer._gazeTracker.position.y -= deltaFighting;
  86686. }
  86687. if (gazer._gazeTracker.position.z < 0) {
  86688. gazer._gazeTracker.position.z += deltaFighting;
  86689. }
  86690. else {
  86691. gazer._gazeTracker.position.z -= deltaFighting;
  86692. }
  86693. }
  86694. // Changing the size of the laser pointer based on the distance from the targetted point
  86695. gazer._updatePointerDistance(hit.distance);
  86696. }
  86697. else {
  86698. gazer._gazeTracker.isVisible = false;
  86699. }
  86700. if (hit && hit.pickedMesh) {
  86701. gazer._currentHit = hit;
  86702. if (gazer._pointerDownOnMeshAsked) {
  86703. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  86704. }
  86705. // The object selected is the floor, we're in a teleportation scenario
  86706. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  86707. // Moving the teleportation area to this targetted point
  86708. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  86709. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  86710. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86711. }
  86712. gazer._currentMeshSelected = null;
  86713. if (gazer._teleportationRequestInitiated) {
  86714. this._moveTeleportationSelectorTo(hit, gazer);
  86715. }
  86716. return;
  86717. }
  86718. // If not, we're in a selection scenario
  86719. //this._teleportationAllowed = false;
  86720. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  86721. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  86722. this.onNewMeshPicked.notifyObservers(hit);
  86723. gazer._currentMeshSelected = hit.pickedMesh;
  86724. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  86725. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  86726. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  86727. gazer._isActionableMesh = true;
  86728. }
  86729. else {
  86730. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86731. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86732. gazer._isActionableMesh = false;
  86733. }
  86734. try {
  86735. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  86736. }
  86737. catch (err) {
  86738. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  86739. }
  86740. }
  86741. else {
  86742. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86743. gazer._currentMeshSelected = null;
  86744. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86745. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86746. }
  86747. }
  86748. }
  86749. else {
  86750. gazer._currentHit = null;
  86751. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  86752. gazer._currentMeshSelected = null;
  86753. //this._teleportationAllowed = false;
  86754. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86755. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  86756. }
  86757. };
  86758. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  86759. if (mesh) {
  86760. this.onSelectedMeshUnselected.notifyObservers(mesh);
  86761. }
  86762. };
  86763. /**
  86764. * Sets the color of the laser ray from the vr controllers.
  86765. * @param color new color for the ray.
  86766. */
  86767. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  86768. if (this.leftController) {
  86769. this.leftController._setLaserPointerColor(color);
  86770. }
  86771. if (this.rightController) {
  86772. this.rightController._setLaserPointerColor(color);
  86773. }
  86774. };
  86775. /**
  86776. * Sets the color of the ray from the vr headsets gaze.
  86777. * @param color new color for the ray.
  86778. */
  86779. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  86780. if (!this._cameraGazer._gazeTracker.material) {
  86781. return;
  86782. }
  86783. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  86784. if (this.leftController) {
  86785. this.leftController._gazeTracker.material.emissiveColor = color;
  86786. }
  86787. if (this.rightController) {
  86788. this.rightController._gazeTracker.material.emissiveColor = color;
  86789. }
  86790. };
  86791. /**
  86792. * Exits VR and disposes of the vr experience helper
  86793. */
  86794. VRExperienceHelper.prototype.dispose = function () {
  86795. if (this.isInVRMode) {
  86796. this.exitVR();
  86797. }
  86798. if (this._postProcessMove) {
  86799. this._postProcessMove.dispose();
  86800. }
  86801. if (this._webVRCamera) {
  86802. this._webVRCamera.dispose();
  86803. }
  86804. if (this._vrDeviceOrientationCamera) {
  86805. this._vrDeviceOrientationCamera.dispose();
  86806. }
  86807. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  86808. document.body.removeChild(this._btnVR);
  86809. }
  86810. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  86811. this._deviceOrientationCamera.dispose();
  86812. }
  86813. if (this._cameraGazer) {
  86814. this._cameraGazer.dispose();
  86815. }
  86816. if (this.leftController) {
  86817. this.leftController.dispose();
  86818. }
  86819. if (this.rightController) {
  86820. this.rightController.dispose();
  86821. }
  86822. if (this._teleportationTarget) {
  86823. this._teleportationTarget.dispose();
  86824. }
  86825. this._floorMeshesCollection = [];
  86826. document.removeEventListener("keydown", this._onKeyDown);
  86827. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86828. window.removeEventListener("resize", this._onResize);
  86829. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  86830. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  86831. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  86832. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  86833. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  86834. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  86835. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  86836. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  86837. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  86838. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  86839. this._scene.unregisterBeforeRender(this.beforeRender);
  86840. };
  86841. /**
  86842. * Gets the name of the VRExperienceHelper class
  86843. * @returns "VRExperienceHelper"
  86844. */
  86845. VRExperienceHelper.prototype.getClassName = function () {
  86846. return "VRExperienceHelper";
  86847. };
  86848. return VRExperienceHelper;
  86849. }());
  86850. BABYLON.VRExperienceHelper = VRExperienceHelper;
  86851. })(BABYLON || (BABYLON = {}));
  86852. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  86853. "use strict";
  86854. // Mainly based on these 2 articles :
  86855. // 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
  86856. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  86857. var BABYLON;
  86858. (function (BABYLON) {
  86859. var JoystickAxis;
  86860. (function (JoystickAxis) {
  86861. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  86862. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  86863. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  86864. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  86865. var VirtualJoystick = /** @class */ (function () {
  86866. function VirtualJoystick(leftJoystick) {
  86867. var _this = this;
  86868. if (leftJoystick) {
  86869. this._leftJoystick = true;
  86870. }
  86871. else {
  86872. this._leftJoystick = false;
  86873. }
  86874. VirtualJoystick._globalJoystickIndex++;
  86875. // By default left & right arrow keys are moving the X
  86876. // and up & down keys are moving the Y
  86877. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  86878. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  86879. this.reverseLeftRight = false;
  86880. this.reverseUpDown = false;
  86881. // collections of pointers
  86882. this._touches = new BABYLON.StringDictionary();
  86883. this.deltaPosition = BABYLON.Vector3.Zero();
  86884. this._joystickSensibility = 25;
  86885. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  86886. this._onResize = function (evt) {
  86887. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  86888. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  86889. if (VirtualJoystick.vjCanvas) {
  86890. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  86891. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  86892. }
  86893. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  86894. };
  86895. // injecting a canvas element on top of the canvas 3D game
  86896. if (!VirtualJoystick.vjCanvas) {
  86897. window.addEventListener("resize", this._onResize, false);
  86898. VirtualJoystick.vjCanvas = document.createElement("canvas");
  86899. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  86900. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  86901. VirtualJoystick.vjCanvas.width = window.innerWidth;
  86902. VirtualJoystick.vjCanvas.height = window.innerHeight;
  86903. VirtualJoystick.vjCanvas.style.width = "100%";
  86904. VirtualJoystick.vjCanvas.style.height = "100%";
  86905. VirtualJoystick.vjCanvas.style.position = "absolute";
  86906. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  86907. VirtualJoystick.vjCanvas.style.top = "0px";
  86908. VirtualJoystick.vjCanvas.style.left = "0px";
  86909. VirtualJoystick.vjCanvas.style.zIndex = "5";
  86910. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  86911. // Support for jQuery PEP polyfill
  86912. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  86913. var context = VirtualJoystick.vjCanvas.getContext('2d');
  86914. if (!context) {
  86915. throw new Error("Unable to create canvas for virtual joystick");
  86916. }
  86917. VirtualJoystick.vjCanvasContext = context;
  86918. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  86919. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  86920. document.body.appendChild(VirtualJoystick.vjCanvas);
  86921. }
  86922. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  86923. this.pressed = false;
  86924. // default joystick color
  86925. this._joystickColor = "cyan";
  86926. this._joystickPointerID = -1;
  86927. // current joystick position
  86928. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  86929. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  86930. // origin joystick position
  86931. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  86932. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  86933. this._onPointerDownHandlerRef = function (evt) {
  86934. _this._onPointerDown(evt);
  86935. };
  86936. this._onPointerMoveHandlerRef = function (evt) {
  86937. _this._onPointerMove(evt);
  86938. };
  86939. this._onPointerUpHandlerRef = function (evt) {
  86940. _this._onPointerUp(evt);
  86941. };
  86942. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  86943. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  86944. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  86945. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  86946. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  86947. evt.preventDefault(); // Disables system menu
  86948. }, false);
  86949. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  86950. }
  86951. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  86952. this._joystickSensibility = newJoystickSensibility;
  86953. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  86954. };
  86955. VirtualJoystick.prototype._onPointerDown = function (e) {
  86956. var positionOnScreenCondition;
  86957. e.preventDefault();
  86958. if (this._leftJoystick === true) {
  86959. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  86960. }
  86961. else {
  86962. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  86963. }
  86964. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  86965. // First contact will be dedicated to the virtual joystick
  86966. this._joystickPointerID = e.pointerId;
  86967. this._joystickPointerStartPos.x = e.clientX;
  86968. this._joystickPointerStartPos.y = e.clientY;
  86969. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  86970. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  86971. this._deltaJoystickVector.x = 0;
  86972. this._deltaJoystickVector.y = 0;
  86973. this.pressed = true;
  86974. this._touches.add(e.pointerId.toString(), e);
  86975. }
  86976. else {
  86977. // You can only trigger the action buttons with a joystick declared
  86978. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  86979. this._action();
  86980. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  86981. }
  86982. }
  86983. };
  86984. VirtualJoystick.prototype._onPointerMove = function (e) {
  86985. // If the current pointer is the one associated to the joystick (first touch contact)
  86986. if (this._joystickPointerID == e.pointerId) {
  86987. this._joystickPointerPos.x = e.clientX;
  86988. this._joystickPointerPos.y = e.clientY;
  86989. this._deltaJoystickVector = this._joystickPointerPos.clone();
  86990. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  86991. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  86992. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  86993. switch (this._axisTargetedByLeftAndRight) {
  86994. case JoystickAxis.X:
  86995. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  86996. break;
  86997. case JoystickAxis.Y:
  86998. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  86999. break;
  87000. case JoystickAxis.Z:
  87001. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  87002. break;
  87003. }
  87004. var directionUpDown = this.reverseUpDown ? 1 : -1;
  87005. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  87006. switch (this._axisTargetedByUpAndDown) {
  87007. case JoystickAxis.X:
  87008. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  87009. break;
  87010. case JoystickAxis.Y:
  87011. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  87012. break;
  87013. case JoystickAxis.Z:
  87014. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  87015. break;
  87016. }
  87017. }
  87018. else {
  87019. var data = this._touches.get(e.pointerId.toString());
  87020. if (data) {
  87021. data.x = e.clientX;
  87022. data.y = e.clientY;
  87023. }
  87024. }
  87025. };
  87026. VirtualJoystick.prototype._onPointerUp = function (e) {
  87027. if (this._joystickPointerID == e.pointerId) {
  87028. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  87029. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  87030. this._joystickPointerID = -1;
  87031. this.pressed = false;
  87032. }
  87033. else {
  87034. var touch = this._touches.get(e.pointerId.toString());
  87035. if (touch) {
  87036. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87037. }
  87038. }
  87039. this._deltaJoystickVector.x = 0;
  87040. this._deltaJoystickVector.y = 0;
  87041. this._touches.remove(e.pointerId.toString());
  87042. };
  87043. /**
  87044. * Change the color of the virtual joystick
  87045. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  87046. */
  87047. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  87048. this._joystickColor = newColor;
  87049. };
  87050. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  87051. this._action = action;
  87052. };
  87053. // Define which axis you'd like to control for left & right
  87054. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  87055. switch (axis) {
  87056. case JoystickAxis.X:
  87057. case JoystickAxis.Y:
  87058. case JoystickAxis.Z:
  87059. this._axisTargetedByLeftAndRight = axis;
  87060. break;
  87061. default:
  87062. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  87063. break;
  87064. }
  87065. };
  87066. // Define which axis you'd like to control for up & down
  87067. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  87068. switch (axis) {
  87069. case JoystickAxis.X:
  87070. case JoystickAxis.Y:
  87071. case JoystickAxis.Z:
  87072. this._axisTargetedByUpAndDown = axis;
  87073. break;
  87074. default:
  87075. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  87076. break;
  87077. }
  87078. };
  87079. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  87080. var _this = this;
  87081. if (this.pressed) {
  87082. this._touches.forEach(function (key, touch) {
  87083. if (touch.pointerId === _this._joystickPointerID) {
  87084. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  87085. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  87086. VirtualJoystick.vjCanvasContext.beginPath();
  87087. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87088. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87089. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  87090. VirtualJoystick.vjCanvasContext.stroke();
  87091. VirtualJoystick.vjCanvasContext.closePath();
  87092. VirtualJoystick.vjCanvasContext.beginPath();
  87093. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87094. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  87095. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  87096. VirtualJoystick.vjCanvasContext.stroke();
  87097. VirtualJoystick.vjCanvasContext.closePath();
  87098. VirtualJoystick.vjCanvasContext.beginPath();
  87099. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  87100. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  87101. VirtualJoystick.vjCanvasContext.stroke();
  87102. VirtualJoystick.vjCanvasContext.closePath();
  87103. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  87104. }
  87105. else {
  87106. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  87107. VirtualJoystick.vjCanvasContext.beginPath();
  87108. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  87109. VirtualJoystick.vjCanvasContext.beginPath();
  87110. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  87111. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  87112. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  87113. VirtualJoystick.vjCanvasContext.stroke();
  87114. VirtualJoystick.vjCanvasContext.closePath();
  87115. touch.prevX = touch.x;
  87116. touch.prevY = touch.y;
  87117. }
  87118. ;
  87119. });
  87120. }
  87121. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  87122. };
  87123. VirtualJoystick.prototype.releaseCanvas = function () {
  87124. if (VirtualJoystick.vjCanvas) {
  87125. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  87126. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  87127. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  87128. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  87129. window.removeEventListener("resize", this._onResize);
  87130. document.body.removeChild(VirtualJoystick.vjCanvas);
  87131. VirtualJoystick.vjCanvas = null;
  87132. }
  87133. };
  87134. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  87135. VirtualJoystick._globalJoystickIndex = 0;
  87136. return VirtualJoystick;
  87137. }());
  87138. BABYLON.VirtualJoystick = VirtualJoystick;
  87139. })(BABYLON || (BABYLON = {}));
  87140. //# sourceMappingURL=babylon.virtualJoystick.js.map
  87141. "use strict";
  87142. var BABYLON;
  87143. (function (BABYLON) {
  87144. // We're mainly based on the logic defined into the FreeCamera code
  87145. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  87146. __extends(VirtualJoysticksCamera, _super);
  87147. function VirtualJoysticksCamera(name, position, scene) {
  87148. var _this = _super.call(this, name, position, scene) || this;
  87149. _this.inputs.addVirtualJoystick();
  87150. return _this;
  87151. }
  87152. VirtualJoysticksCamera.prototype.getClassName = function () {
  87153. return "VirtualJoysticksCamera";
  87154. };
  87155. return VirtualJoysticksCamera;
  87156. }(BABYLON.FreeCamera));
  87157. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  87158. })(BABYLON || (BABYLON = {}));
  87159. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  87160. "use strict";
  87161. var BABYLON;
  87162. (function (BABYLON) {
  87163. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  87164. function FreeCameraVirtualJoystickInput() {
  87165. }
  87166. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  87167. return this._leftjoystick;
  87168. };
  87169. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  87170. return this._rightjoystick;
  87171. };
  87172. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  87173. if (this._leftjoystick) {
  87174. var camera = this.camera;
  87175. var speed = camera._computeLocalCameraSpeed() * 50;
  87176. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  87177. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  87178. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  87179. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  87180. if (!this._leftjoystick.pressed) {
  87181. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  87182. }
  87183. if (!this._rightjoystick.pressed) {
  87184. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  87185. }
  87186. }
  87187. };
  87188. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  87189. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  87190. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  87191. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  87192. this._leftjoystick.setJoystickSensibility(0.15);
  87193. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  87194. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  87195. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  87196. this._rightjoystick.reverseUpDown = true;
  87197. this._rightjoystick.setJoystickSensibility(0.05);
  87198. this._rightjoystick.setJoystickColor("yellow");
  87199. };
  87200. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  87201. this._leftjoystick.releaseCanvas();
  87202. this._rightjoystick.releaseCanvas();
  87203. };
  87204. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  87205. return "FreeCameraVirtualJoystickInput";
  87206. };
  87207. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  87208. return "virtualJoystick";
  87209. };
  87210. return FreeCameraVirtualJoystickInput;
  87211. }());
  87212. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  87213. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  87214. })(BABYLON || (BABYLON = {}));
  87215. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  87216. "use strict";
  87217. var BABYLON;
  87218. (function (BABYLON) {
  87219. var SimplificationSettings = /** @class */ (function () {
  87220. function SimplificationSettings(quality, distance, optimizeMesh) {
  87221. this.quality = quality;
  87222. this.distance = distance;
  87223. this.optimizeMesh = optimizeMesh;
  87224. }
  87225. return SimplificationSettings;
  87226. }());
  87227. BABYLON.SimplificationSettings = SimplificationSettings;
  87228. var SimplificationQueue = /** @class */ (function () {
  87229. function SimplificationQueue() {
  87230. this.running = false;
  87231. this._simplificationArray = [];
  87232. }
  87233. SimplificationQueue.prototype.addTask = function (task) {
  87234. this._simplificationArray.push(task);
  87235. };
  87236. SimplificationQueue.prototype.executeNext = function () {
  87237. var task = this._simplificationArray.pop();
  87238. if (task) {
  87239. this.running = true;
  87240. this.runSimplification(task);
  87241. }
  87242. else {
  87243. this.running = false;
  87244. }
  87245. };
  87246. SimplificationQueue.prototype.runSimplification = function (task) {
  87247. var _this = this;
  87248. if (task.parallelProcessing) {
  87249. //parallel simplifier
  87250. task.settings.forEach(function (setting) {
  87251. var simplifier = _this.getSimplifier(task);
  87252. simplifier.simplify(setting, function (newMesh) {
  87253. task.mesh.addLODLevel(setting.distance, newMesh);
  87254. newMesh.isVisible = true;
  87255. //check if it is the last
  87256. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  87257. //all done, run the success callback.
  87258. task.successCallback();
  87259. }
  87260. _this.executeNext();
  87261. });
  87262. });
  87263. }
  87264. else {
  87265. //single simplifier.
  87266. var simplifier = this.getSimplifier(task);
  87267. var runDecimation = function (setting, callback) {
  87268. simplifier.simplify(setting, function (newMesh) {
  87269. task.mesh.addLODLevel(setting.distance, newMesh);
  87270. newMesh.isVisible = true;
  87271. //run the next quality level
  87272. callback();
  87273. });
  87274. };
  87275. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  87276. runDecimation(task.settings[loop.index], function () {
  87277. loop.executeNext();
  87278. });
  87279. }, function () {
  87280. //execution ended, run the success callback.
  87281. if (task.successCallback) {
  87282. task.successCallback();
  87283. }
  87284. _this.executeNext();
  87285. });
  87286. }
  87287. };
  87288. SimplificationQueue.prototype.getSimplifier = function (task) {
  87289. switch (task.simplificationType) {
  87290. case SimplificationType.QUADRATIC:
  87291. default:
  87292. return new QuadraticErrorSimplification(task.mesh);
  87293. }
  87294. };
  87295. return SimplificationQueue;
  87296. }());
  87297. BABYLON.SimplificationQueue = SimplificationQueue;
  87298. /**
  87299. * The implemented types of simplification.
  87300. * At the moment only Quadratic Error Decimation is implemented.
  87301. */
  87302. var SimplificationType;
  87303. (function (SimplificationType) {
  87304. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  87305. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  87306. var DecimationTriangle = /** @class */ (function () {
  87307. function DecimationTriangle(vertices) {
  87308. this.vertices = vertices;
  87309. this.error = new Array(4);
  87310. this.deleted = false;
  87311. this.isDirty = false;
  87312. this.deletePending = false;
  87313. this.borderFactor = 0;
  87314. }
  87315. return DecimationTriangle;
  87316. }());
  87317. BABYLON.DecimationTriangle = DecimationTriangle;
  87318. var DecimationVertex = /** @class */ (function () {
  87319. function DecimationVertex(position, id) {
  87320. this.position = position;
  87321. this.id = id;
  87322. this.isBorder = true;
  87323. this.q = new QuadraticMatrix();
  87324. this.triangleCount = 0;
  87325. this.triangleStart = 0;
  87326. this.originalOffsets = [];
  87327. }
  87328. DecimationVertex.prototype.updatePosition = function (newPosition) {
  87329. this.position.copyFrom(newPosition);
  87330. };
  87331. return DecimationVertex;
  87332. }());
  87333. BABYLON.DecimationVertex = DecimationVertex;
  87334. var QuadraticMatrix = /** @class */ (function () {
  87335. function QuadraticMatrix(data) {
  87336. this.data = new Array(10);
  87337. for (var i = 0; i < 10; ++i) {
  87338. if (data && data[i]) {
  87339. this.data[i] = data[i];
  87340. }
  87341. else {
  87342. this.data[i] = 0;
  87343. }
  87344. }
  87345. }
  87346. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  87347. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  87348. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  87349. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  87350. return det;
  87351. };
  87352. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  87353. for (var i = 0; i < 10; ++i) {
  87354. this.data[i] += matrix.data[i];
  87355. }
  87356. };
  87357. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  87358. for (var i = 0; i < 10; ++i) {
  87359. this.data[i] += data[i];
  87360. }
  87361. };
  87362. QuadraticMatrix.prototype.add = function (matrix) {
  87363. var m = new QuadraticMatrix();
  87364. for (var i = 0; i < 10; ++i) {
  87365. m.data[i] = this.data[i] + matrix.data[i];
  87366. }
  87367. return m;
  87368. };
  87369. QuadraticMatrix.FromData = function (a, b, c, d) {
  87370. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  87371. };
  87372. //returning an array to avoid garbage collection
  87373. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  87374. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  87375. };
  87376. return QuadraticMatrix;
  87377. }());
  87378. BABYLON.QuadraticMatrix = QuadraticMatrix;
  87379. var Reference = /** @class */ (function () {
  87380. function Reference(vertexId, triangleId) {
  87381. this.vertexId = vertexId;
  87382. this.triangleId = triangleId;
  87383. }
  87384. return Reference;
  87385. }());
  87386. BABYLON.Reference = Reference;
  87387. /**
  87388. * An implementation of the Quadratic Error simplification algorithm.
  87389. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  87390. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  87391. * @author RaananW
  87392. */
  87393. var QuadraticErrorSimplification = /** @class */ (function () {
  87394. function QuadraticErrorSimplification(_mesh) {
  87395. this._mesh = _mesh;
  87396. this.syncIterations = 5000;
  87397. this.aggressiveness = 7;
  87398. this.decimationIterations = 100;
  87399. this.boundingBoxEpsilon = BABYLON.Epsilon;
  87400. }
  87401. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  87402. var _this = this;
  87403. this.initDecimatedMesh();
  87404. //iterating through the submeshes array, one after the other.
  87405. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  87406. _this.initWithMesh(loop.index, function () {
  87407. _this.runDecimation(settings, loop.index, function () {
  87408. loop.executeNext();
  87409. });
  87410. }, settings.optimizeMesh);
  87411. }, function () {
  87412. setTimeout(function () {
  87413. successCallback(_this._reconstructedMesh);
  87414. }, 0);
  87415. });
  87416. };
  87417. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  87418. var _this = this;
  87419. var targetCount = ~~(this.triangles.length * settings.quality);
  87420. var deletedTriangles = 0;
  87421. var triangleCount = this.triangles.length;
  87422. var iterationFunction = function (iteration, callback) {
  87423. setTimeout(function () {
  87424. if (iteration % 5 === 0) {
  87425. _this.updateMesh(iteration === 0);
  87426. }
  87427. for (var i = 0; i < _this.triangles.length; ++i) {
  87428. _this.triangles[i].isDirty = false;
  87429. }
  87430. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  87431. var trianglesIterator = function (i) {
  87432. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  87433. var t = _this.triangles[tIdx];
  87434. if (!t)
  87435. return;
  87436. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  87437. return;
  87438. }
  87439. for (var j = 0; j < 3; ++j) {
  87440. if (t.error[j] < threshold) {
  87441. var deleted0 = [];
  87442. var deleted1 = [];
  87443. var v0 = t.vertices[j];
  87444. var v1 = t.vertices[(j + 1) % 3];
  87445. if (v0.isBorder || v1.isBorder)
  87446. continue;
  87447. var p = BABYLON.Vector3.Zero();
  87448. var n = BABYLON.Vector3.Zero();
  87449. var uv = BABYLON.Vector2.Zero();
  87450. var color = new BABYLON.Color4(0, 0, 0, 1);
  87451. _this.calculateError(v0, v1, p, n, uv, color);
  87452. var delTr = new Array();
  87453. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  87454. continue;
  87455. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  87456. continue;
  87457. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  87458. continue;
  87459. var uniqueArray = new Array();
  87460. delTr.forEach(function (deletedT) {
  87461. if (uniqueArray.indexOf(deletedT) === -1) {
  87462. deletedT.deletePending = true;
  87463. uniqueArray.push(deletedT);
  87464. }
  87465. });
  87466. if (uniqueArray.length % 2 !== 0) {
  87467. continue;
  87468. }
  87469. v0.q = v1.q.add(v0.q);
  87470. v0.updatePosition(p);
  87471. var tStart = _this.references.length;
  87472. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  87473. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  87474. var tCount = _this.references.length - tStart;
  87475. if (tCount <= v0.triangleCount) {
  87476. if (tCount) {
  87477. for (var c = 0; c < tCount; c++) {
  87478. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  87479. }
  87480. }
  87481. }
  87482. else {
  87483. v0.triangleStart = tStart;
  87484. }
  87485. v0.triangleCount = tCount;
  87486. break;
  87487. }
  87488. }
  87489. };
  87490. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  87491. }, 0);
  87492. };
  87493. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  87494. if (triangleCount - deletedTriangles <= targetCount)
  87495. loop.breakLoop();
  87496. else {
  87497. iterationFunction(loop.index, function () {
  87498. loop.executeNext();
  87499. });
  87500. }
  87501. }, function () {
  87502. setTimeout(function () {
  87503. //reconstruct this part of the mesh
  87504. _this.reconstructMesh(submeshIndex);
  87505. successCallback();
  87506. }, 0);
  87507. });
  87508. };
  87509. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  87510. var _this = this;
  87511. this.vertices = [];
  87512. this.triangles = [];
  87513. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  87514. var indices = this._mesh.getIndices();
  87515. var submesh = this._mesh.subMeshes[submeshIndex];
  87516. var findInVertices = function (positionToSearch) {
  87517. if (optimizeMesh) {
  87518. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  87519. if (_this.vertices[ii].position.equals(positionToSearch)) {
  87520. return _this.vertices[ii];
  87521. }
  87522. }
  87523. }
  87524. return null;
  87525. };
  87526. var vertexReferences = [];
  87527. var vertexInit = function (i) {
  87528. if (!positionData) {
  87529. return;
  87530. }
  87531. var offset = i + submesh.verticesStart;
  87532. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  87533. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  87534. vertex.originalOffsets.push(offset);
  87535. if (vertex.id === _this.vertices.length) {
  87536. _this.vertices.push(vertex);
  87537. }
  87538. vertexReferences.push(vertex.id);
  87539. };
  87540. //var totalVertices = mesh.getTotalVertices();
  87541. var totalVertices = submesh.verticesCount;
  87542. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  87543. var indicesInit = function (i) {
  87544. if (!indices) {
  87545. return;
  87546. }
  87547. var offset = (submesh.indexStart / 3) + i;
  87548. var pos = (offset * 3);
  87549. var i0 = indices[pos + 0];
  87550. var i1 = indices[pos + 1];
  87551. var i2 = indices[pos + 2];
  87552. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  87553. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  87554. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  87555. var triangle = new DecimationTriangle([v0, v1, v2]);
  87556. triangle.originalOffset = pos;
  87557. _this.triangles.push(triangle);
  87558. };
  87559. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  87560. _this.init(callback);
  87561. });
  87562. });
  87563. };
  87564. QuadraticErrorSimplification.prototype.init = function (callback) {
  87565. var _this = this;
  87566. var triangleInit1 = function (i) {
  87567. var t = _this.triangles[i];
  87568. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  87569. for (var j = 0; j < 3; j++) {
  87570. 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))));
  87571. }
  87572. };
  87573. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  87574. var triangleInit2 = function (i) {
  87575. var t = _this.triangles[i];
  87576. for (var j = 0; j < 3; ++j) {
  87577. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  87578. }
  87579. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87580. };
  87581. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  87582. callback();
  87583. });
  87584. });
  87585. };
  87586. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  87587. var newTriangles = [];
  87588. var i;
  87589. for (i = 0; i < this.vertices.length; ++i) {
  87590. this.vertices[i].triangleCount = 0;
  87591. }
  87592. var t;
  87593. var j;
  87594. for (i = 0; i < this.triangles.length; ++i) {
  87595. if (!this.triangles[i].deleted) {
  87596. t = this.triangles[i];
  87597. for (j = 0; j < 3; ++j) {
  87598. t.vertices[j].triangleCount = 1;
  87599. }
  87600. newTriangles.push(t);
  87601. }
  87602. }
  87603. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  87604. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  87605. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  87606. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  87607. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  87608. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  87609. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  87610. var vertexCount = 0;
  87611. for (i = 0; i < this.vertices.length; ++i) {
  87612. var vertex = this.vertices[i];
  87613. vertex.id = vertexCount;
  87614. if (vertex.triangleCount) {
  87615. vertex.originalOffsets.forEach(function (originalOffset) {
  87616. if (!normalData) {
  87617. return;
  87618. }
  87619. newPositionData.push(vertex.position.x);
  87620. newPositionData.push(vertex.position.y);
  87621. newPositionData.push(vertex.position.z);
  87622. newNormalData.push(normalData[originalOffset * 3]);
  87623. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  87624. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  87625. if (uvs && uvs.length) {
  87626. newUVsData.push(uvs[(originalOffset * 2)]);
  87627. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  87628. }
  87629. else if (colorsData && colorsData.length) {
  87630. newColorsData.push(colorsData[(originalOffset * 4)]);
  87631. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  87632. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  87633. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  87634. }
  87635. ++vertexCount;
  87636. });
  87637. }
  87638. }
  87639. var startingIndex = this._reconstructedMesh.getTotalIndices();
  87640. var startingVertex = this._reconstructedMesh.getTotalVertices();
  87641. var submeshesArray = this._reconstructedMesh.subMeshes;
  87642. this._reconstructedMesh.subMeshes = [];
  87643. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  87644. var originalIndices = this._mesh.getIndices();
  87645. for (i = 0; i < newTriangles.length; ++i) {
  87646. t = newTriangles[i]; //now get the new referencing point for each vertex
  87647. [0, 1, 2].forEach(function (idx) {
  87648. var id = originalIndices[t.originalOffset + idx];
  87649. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  87650. if (offset < 0)
  87651. offset = 0;
  87652. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  87653. });
  87654. }
  87655. //overwriting the old vertex buffers and indices.
  87656. this._reconstructedMesh.setIndices(newIndicesArray);
  87657. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  87658. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  87659. if (newUVsData.length > 0)
  87660. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  87661. if (newColorsData.length > 0)
  87662. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  87663. //create submesh
  87664. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  87665. if (submeshIndex > 0) {
  87666. this._reconstructedMesh.subMeshes = [];
  87667. submeshesArray.forEach(function (submesh) {
  87668. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  87669. });
  87670. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  87671. }
  87672. };
  87673. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  87674. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  87675. this._reconstructedMesh.material = this._mesh.material;
  87676. this._reconstructedMesh.parent = this._mesh.parent;
  87677. this._reconstructedMesh.isVisible = false;
  87678. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  87679. };
  87680. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  87681. for (var i = 0; i < vertex1.triangleCount; ++i) {
  87682. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  87683. if (t.deleted)
  87684. continue;
  87685. var s = this.references[vertex1.triangleStart + i].vertexId;
  87686. var v1 = t.vertices[(s + 1) % 3];
  87687. var v2 = t.vertices[(s + 2) % 3];
  87688. if ((v1 === vertex2 || v2 === vertex2)) {
  87689. deletedArray[i] = true;
  87690. delTr.push(t);
  87691. continue;
  87692. }
  87693. var d1 = v1.position.subtract(point);
  87694. d1 = d1.normalize();
  87695. var d2 = v2.position.subtract(point);
  87696. d2 = d2.normalize();
  87697. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  87698. return true;
  87699. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  87700. deletedArray[i] = false;
  87701. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  87702. return true;
  87703. }
  87704. return false;
  87705. };
  87706. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  87707. var newDeleted = deletedTriangles;
  87708. for (var i = 0; i < vertex.triangleCount; ++i) {
  87709. var ref = this.references[vertex.triangleStart + i];
  87710. var t = this.triangles[ref.triangleId];
  87711. if (t.deleted)
  87712. continue;
  87713. if (deletedArray[i] && t.deletePending) {
  87714. t.deleted = true;
  87715. newDeleted++;
  87716. continue;
  87717. }
  87718. t.vertices[ref.vertexId] = origVertex;
  87719. t.isDirty = true;
  87720. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  87721. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  87722. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  87723. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  87724. this.references.push(ref);
  87725. }
  87726. return newDeleted;
  87727. };
  87728. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  87729. for (var i = 0; i < this.vertices.length; ++i) {
  87730. var vCount = [];
  87731. var vId = [];
  87732. var v = this.vertices[i];
  87733. var j;
  87734. for (j = 0; j < v.triangleCount; ++j) {
  87735. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  87736. for (var ii = 0; ii < 3; ii++) {
  87737. var ofs = 0;
  87738. var vv = triangle.vertices[ii];
  87739. while (ofs < vCount.length) {
  87740. if (vId[ofs] === vv.id)
  87741. break;
  87742. ++ofs;
  87743. }
  87744. if (ofs === vCount.length) {
  87745. vCount.push(1);
  87746. vId.push(vv.id);
  87747. }
  87748. else {
  87749. vCount[ofs]++;
  87750. }
  87751. }
  87752. }
  87753. for (j = 0; j < vCount.length; ++j) {
  87754. if (vCount[j] === 1) {
  87755. this.vertices[vId[j]].isBorder = true;
  87756. }
  87757. else {
  87758. this.vertices[vId[j]].isBorder = false;
  87759. }
  87760. }
  87761. }
  87762. };
  87763. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  87764. if (identifyBorders === void 0) { identifyBorders = false; }
  87765. var i;
  87766. if (!identifyBorders) {
  87767. var newTrianglesVector = [];
  87768. for (i = 0; i < this.triangles.length; ++i) {
  87769. if (!this.triangles[i].deleted) {
  87770. newTrianglesVector.push(this.triangles[i]);
  87771. }
  87772. }
  87773. this.triangles = newTrianglesVector;
  87774. }
  87775. for (i = 0; i < this.vertices.length; ++i) {
  87776. this.vertices[i].triangleCount = 0;
  87777. this.vertices[i].triangleStart = 0;
  87778. }
  87779. var t;
  87780. var j;
  87781. var v;
  87782. for (i = 0; i < this.triangles.length; ++i) {
  87783. t = this.triangles[i];
  87784. for (j = 0; j < 3; ++j) {
  87785. v = t.vertices[j];
  87786. v.triangleCount++;
  87787. }
  87788. }
  87789. var tStart = 0;
  87790. for (i = 0; i < this.vertices.length; ++i) {
  87791. this.vertices[i].triangleStart = tStart;
  87792. tStart += this.vertices[i].triangleCount;
  87793. this.vertices[i].triangleCount = 0;
  87794. }
  87795. var newReferences = new Array(this.triangles.length * 3);
  87796. for (i = 0; i < this.triangles.length; ++i) {
  87797. t = this.triangles[i];
  87798. for (j = 0; j < 3; ++j) {
  87799. v = t.vertices[j];
  87800. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  87801. v.triangleCount++;
  87802. }
  87803. }
  87804. this.references = newReferences;
  87805. if (identifyBorders) {
  87806. this.identifyBorder();
  87807. }
  87808. };
  87809. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  87810. var x = point.x;
  87811. var y = point.y;
  87812. var z = point.z;
  87813. 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
  87814. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  87815. };
  87816. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  87817. var q = vertex1.q.add(vertex2.q);
  87818. var border = vertex1.isBorder && vertex2.isBorder;
  87819. var error = 0;
  87820. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  87821. if (qDet !== 0 && !border) {
  87822. if (!pointResult) {
  87823. pointResult = BABYLON.Vector3.Zero();
  87824. }
  87825. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  87826. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  87827. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  87828. error = this.vertexError(q, pointResult);
  87829. }
  87830. else {
  87831. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  87832. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  87833. var error1 = this.vertexError(q, vertex1.position);
  87834. var error2 = this.vertexError(q, vertex2.position);
  87835. var error3 = this.vertexError(q, p3);
  87836. error = Math.min(error1, error2, error3);
  87837. if (error === error1) {
  87838. if (pointResult) {
  87839. pointResult.copyFrom(vertex1.position);
  87840. }
  87841. }
  87842. else if (error === error2) {
  87843. if (pointResult) {
  87844. pointResult.copyFrom(vertex2.position);
  87845. }
  87846. }
  87847. else {
  87848. if (pointResult) {
  87849. pointResult.copyFrom(p3);
  87850. }
  87851. }
  87852. }
  87853. return error;
  87854. };
  87855. return QuadraticErrorSimplification;
  87856. }());
  87857. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  87858. })(BABYLON || (BABYLON = {}));
  87859. //# sourceMappingURL=babylon.meshSimplification.js.map
  87860. "use strict";
  87861. var BABYLON;
  87862. (function (BABYLON) {
  87863. var MeshLODLevel = /** @class */ (function () {
  87864. function MeshLODLevel(distance, mesh) {
  87865. this.distance = distance;
  87866. this.mesh = mesh;
  87867. }
  87868. return MeshLODLevel;
  87869. }());
  87870. BABYLON.MeshLODLevel = MeshLODLevel;
  87871. })(BABYLON || (BABYLON = {}));
  87872. //# sourceMappingURL=babylon.meshLODLevel.js.map
  87873. "use strict";
  87874. var BABYLON;
  87875. (function (BABYLON) {
  87876. /**
  87877. * Defines the root class used to create scene optimization to use with SceneOptimizer
  87878. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87879. */
  87880. var SceneOptimization = /** @class */ (function () {
  87881. /**
  87882. * Creates the SceneOptimization object
  87883. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87884. * @param desc defines the description associated with the optimization
  87885. */
  87886. function SceneOptimization(
  87887. /**
  87888. * Defines the priority of this optimization (0 by default which means first in the list)
  87889. */
  87890. priority) {
  87891. if (priority === void 0) { priority = 0; }
  87892. this.priority = priority;
  87893. }
  87894. /**
  87895. * Gets a string describing the action executed by the current optimization
  87896. * @returns description string
  87897. */
  87898. SceneOptimization.prototype.getDescription = function () {
  87899. return "";
  87900. };
  87901. /**
  87902. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87903. * @param scene defines the current scene where to apply this optimization
  87904. * @param optimizer defines the current optimizer
  87905. * @returns true if everything that can be done was applied
  87906. */
  87907. SceneOptimization.prototype.apply = function (scene, optimizer) {
  87908. return true;
  87909. };
  87910. ;
  87911. return SceneOptimization;
  87912. }());
  87913. BABYLON.SceneOptimization = SceneOptimization;
  87914. /**
  87915. * Defines an optimization used to reduce the size of render target textures
  87916. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87917. */
  87918. var TextureOptimization = /** @class */ (function (_super) {
  87919. __extends(TextureOptimization, _super);
  87920. /**
  87921. * Creates the TextureOptimization object
  87922. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87923. * @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
  87924. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  87925. */
  87926. function TextureOptimization(
  87927. /**
  87928. * Defines the priority of this optimization (0 by default which means first in the list)
  87929. */
  87930. priority,
  87931. /**
  87932. * 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
  87933. */
  87934. maximumSize,
  87935. /**
  87936. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  87937. */
  87938. step) {
  87939. if (priority === void 0) { priority = 0; }
  87940. if (maximumSize === void 0) { maximumSize = 1024; }
  87941. if (step === void 0) { step = 0.5; }
  87942. var _this = _super.call(this, priority) || this;
  87943. _this.priority = priority;
  87944. _this.maximumSize = maximumSize;
  87945. _this.step = step;
  87946. return _this;
  87947. }
  87948. /**
  87949. * Gets a string describing the action executed by the current optimization
  87950. * @returns description string
  87951. */
  87952. TextureOptimization.prototype.getDescription = function () {
  87953. return "Reducing render target texture size to " + this.maximumSize;
  87954. };
  87955. /**
  87956. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  87957. * @param scene defines the current scene where to apply this optimization
  87958. * @param optimizer defines the current optimizer
  87959. * @returns true if everything that can be done was applied
  87960. */
  87961. TextureOptimization.prototype.apply = function (scene, optimizer) {
  87962. var allDone = true;
  87963. for (var index = 0; index < scene.textures.length; index++) {
  87964. var texture = scene.textures[index];
  87965. if (!texture.canRescale || texture.getContext) {
  87966. continue;
  87967. }
  87968. var currentSize = texture.getSize();
  87969. var maxDimension = Math.max(currentSize.width, currentSize.height);
  87970. if (maxDimension > this.maximumSize) {
  87971. texture.scale(this.step);
  87972. allDone = false;
  87973. }
  87974. }
  87975. return allDone;
  87976. };
  87977. return TextureOptimization;
  87978. }(SceneOptimization));
  87979. BABYLON.TextureOptimization = TextureOptimization;
  87980. /**
  87981. * Defines an optimization used to increase or decrease the rendering resolution
  87982. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  87983. */
  87984. var HardwareScalingOptimization = /** @class */ (function (_super) {
  87985. __extends(HardwareScalingOptimization, _super);
  87986. /**
  87987. * Creates the HardwareScalingOptimization object
  87988. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  87989. * @param maximumScale defines the maximum scale to use (2 by default)
  87990. * @param step defines the step to use between two passes (0.5 by default)
  87991. */
  87992. function HardwareScalingOptimization(
  87993. /**
  87994. * Defines the priority of this optimization (0 by default which means first in the list)
  87995. */
  87996. priority,
  87997. /**
  87998. * Defines the maximum scale to use (2 by default)
  87999. */
  88000. maximumScale,
  88001. /**
  88002. * Defines the step to use between two passes (0.5 by default)
  88003. */
  88004. step) {
  88005. if (priority === void 0) { priority = 0; }
  88006. if (maximumScale === void 0) { maximumScale = 2; }
  88007. if (step === void 0) { step = 0.25; }
  88008. var _this = _super.call(this, priority) || this;
  88009. _this.priority = priority;
  88010. _this.maximumScale = maximumScale;
  88011. _this.step = step;
  88012. _this._currentScale = -1;
  88013. _this._directionOffset = 1;
  88014. return _this;
  88015. }
  88016. /**
  88017. * Gets a string describing the action executed by the current optimization
  88018. * @return description string
  88019. */
  88020. HardwareScalingOptimization.prototype.getDescription = function () {
  88021. return "Setting hardware scaling level to " + this._currentScale;
  88022. };
  88023. /**
  88024. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88025. * @param scene defines the current scene where to apply this optimization
  88026. * @param optimizer defines the current optimizer
  88027. * @returns true if everything that can be done was applied
  88028. */
  88029. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  88030. if (this._currentScale === -1) {
  88031. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  88032. if (this._currentScale > this.maximumScale) {
  88033. this._directionOffset = -1;
  88034. }
  88035. }
  88036. this._currentScale += this._directionOffset * this.step;
  88037. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  88038. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  88039. };
  88040. ;
  88041. return HardwareScalingOptimization;
  88042. }(SceneOptimization));
  88043. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  88044. /**
  88045. * Defines an optimization used to remove shadows
  88046. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88047. */
  88048. var ShadowsOptimization = /** @class */ (function (_super) {
  88049. __extends(ShadowsOptimization, _super);
  88050. function ShadowsOptimization() {
  88051. return _super !== null && _super.apply(this, arguments) || this;
  88052. }
  88053. /**
  88054. * Gets a string describing the action executed by the current optimization
  88055. * @return description string
  88056. */
  88057. ShadowsOptimization.prototype.getDescription = function () {
  88058. return "Turning shadows on/off";
  88059. };
  88060. /**
  88061. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88062. * @param scene defines the current scene where to apply this optimization
  88063. * @param optimizer defines the current optimizer
  88064. * @returns true if everything that can be done was applied
  88065. */
  88066. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  88067. scene.shadowsEnabled = optimizer.isInImprovementMode;
  88068. return true;
  88069. };
  88070. ;
  88071. return ShadowsOptimization;
  88072. }(SceneOptimization));
  88073. BABYLON.ShadowsOptimization = ShadowsOptimization;
  88074. /**
  88075. * Defines an optimization used to turn post-processes off
  88076. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88077. */
  88078. var PostProcessesOptimization = /** @class */ (function (_super) {
  88079. __extends(PostProcessesOptimization, _super);
  88080. function PostProcessesOptimization() {
  88081. return _super !== null && _super.apply(this, arguments) || this;
  88082. }
  88083. /**
  88084. * Gets a string describing the action executed by the current optimization
  88085. * @return description string
  88086. */
  88087. PostProcessesOptimization.prototype.getDescription = function () {
  88088. return "Turning post-processes on/off";
  88089. };
  88090. /**
  88091. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88092. * @param scene defines the current scene where to apply this optimization
  88093. * @param optimizer defines the current optimizer
  88094. * @returns true if everything that can be done was applied
  88095. */
  88096. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  88097. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  88098. return true;
  88099. };
  88100. ;
  88101. return PostProcessesOptimization;
  88102. }(SceneOptimization));
  88103. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  88104. /**
  88105. * Defines an optimization used to turn lens flares off
  88106. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88107. */
  88108. var LensFlaresOptimization = /** @class */ (function (_super) {
  88109. __extends(LensFlaresOptimization, _super);
  88110. function LensFlaresOptimization() {
  88111. return _super !== null && _super.apply(this, arguments) || this;
  88112. }
  88113. /**
  88114. * Gets a string describing the action executed by the current optimization
  88115. * @return description string
  88116. */
  88117. LensFlaresOptimization.prototype.getDescription = function () {
  88118. return "Turning lens flares on/off";
  88119. };
  88120. /**
  88121. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88122. * @param scene defines the current scene where to apply this optimization
  88123. * @param optimizer defines the current optimizer
  88124. * @returns true if everything that can be done was applied
  88125. */
  88126. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  88127. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  88128. return true;
  88129. };
  88130. ;
  88131. return LensFlaresOptimization;
  88132. }(SceneOptimization));
  88133. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  88134. /**
  88135. * Defines an optimization based on user defined callback.
  88136. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88137. */
  88138. var CustomOptimization = /** @class */ (function (_super) {
  88139. __extends(CustomOptimization, _super);
  88140. function CustomOptimization() {
  88141. return _super !== null && _super.apply(this, arguments) || this;
  88142. }
  88143. /**
  88144. * Gets a string describing the action executed by the current optimization
  88145. * @returns description string
  88146. */
  88147. CustomOptimization.prototype.getDescription = function () {
  88148. if (this.onGetDescription) {
  88149. return this.onGetDescription();
  88150. }
  88151. return "Running user defined callback";
  88152. };
  88153. /**
  88154. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88155. * @param scene defines the current scene where to apply this optimization
  88156. * @param optimizer defines the current optimizer
  88157. * @returns true if everything that can be done was applied
  88158. */
  88159. CustomOptimization.prototype.apply = function (scene, optimizer) {
  88160. if (this.onApply) {
  88161. return this.onApply(scene, optimizer);
  88162. }
  88163. return true;
  88164. };
  88165. ;
  88166. return CustomOptimization;
  88167. }(SceneOptimization));
  88168. BABYLON.CustomOptimization = CustomOptimization;
  88169. /**
  88170. * Defines an optimization used to turn particles off
  88171. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88172. */
  88173. var ParticlesOptimization = /** @class */ (function (_super) {
  88174. __extends(ParticlesOptimization, _super);
  88175. function ParticlesOptimization() {
  88176. return _super !== null && _super.apply(this, arguments) || this;
  88177. }
  88178. /**
  88179. * Gets a string describing the action executed by the current optimization
  88180. * @return description string
  88181. */
  88182. ParticlesOptimization.prototype.getDescription = function () {
  88183. return "Turning particles on/off";
  88184. };
  88185. /**
  88186. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88187. * @param scene defines the current scene where to apply this optimization
  88188. * @param optimizer defines the current optimizer
  88189. * @returns true if everything that can be done was applied
  88190. */
  88191. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  88192. scene.particlesEnabled = optimizer.isInImprovementMode;
  88193. return true;
  88194. };
  88195. ;
  88196. return ParticlesOptimization;
  88197. }(SceneOptimization));
  88198. BABYLON.ParticlesOptimization = ParticlesOptimization;
  88199. /**
  88200. * Defines an optimization used to turn render targets off
  88201. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88202. */
  88203. var RenderTargetsOptimization = /** @class */ (function (_super) {
  88204. __extends(RenderTargetsOptimization, _super);
  88205. function RenderTargetsOptimization() {
  88206. return _super !== null && _super.apply(this, arguments) || this;
  88207. }
  88208. /**
  88209. * Gets a string describing the action executed by the current optimization
  88210. * @return description string
  88211. */
  88212. RenderTargetsOptimization.prototype.getDescription = function () {
  88213. return "Turning render targets off";
  88214. };
  88215. /**
  88216. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88217. * @param scene defines the current scene where to apply this optimization
  88218. * @param optimizer defines the current optimizer
  88219. * @returns true if everything that can be done was applied
  88220. */
  88221. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  88222. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  88223. return true;
  88224. };
  88225. ;
  88226. return RenderTargetsOptimization;
  88227. }(SceneOptimization));
  88228. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  88229. /**
  88230. * Defines an optimization used to merge meshes with compatible materials
  88231. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88232. */
  88233. var MergeMeshesOptimization = /** @class */ (function (_super) {
  88234. __extends(MergeMeshesOptimization, _super);
  88235. function MergeMeshesOptimization() {
  88236. var _this = _super !== null && _super.apply(this, arguments) || this;
  88237. _this._canBeMerged = function (abstractMesh) {
  88238. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  88239. return false;
  88240. }
  88241. var mesh = abstractMesh;
  88242. if (!mesh.isVisible || !mesh.isEnabled()) {
  88243. return false;
  88244. }
  88245. if (mesh.instances.length > 0) {
  88246. return false;
  88247. }
  88248. if (mesh.skeleton || mesh.hasLODLevels) {
  88249. return false;
  88250. }
  88251. if (mesh.parent) {
  88252. return false;
  88253. }
  88254. return true;
  88255. };
  88256. return _this;
  88257. }
  88258. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  88259. /**
  88260. * Gets or sets a boolean which defines if optimization octree has to be updated
  88261. */
  88262. get: function () {
  88263. return MergeMeshesOptimization._UpdateSelectionTree;
  88264. },
  88265. /**
  88266. * Gets or sets a boolean which defines if optimization octree has to be updated
  88267. */
  88268. set: function (value) {
  88269. MergeMeshesOptimization._UpdateSelectionTree = value;
  88270. },
  88271. enumerable: true,
  88272. configurable: true
  88273. });
  88274. /**
  88275. * Gets a string describing the action executed by the current optimization
  88276. * @return description string
  88277. */
  88278. MergeMeshesOptimization.prototype.getDescription = function () {
  88279. return "Merging similar meshes together";
  88280. };
  88281. /**
  88282. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  88283. * @param scene defines the current scene where to apply this optimization
  88284. * @param optimizer defines the current optimizer
  88285. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  88286. * @returns true if everything that can be done was applied
  88287. */
  88288. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  88289. var globalPool = scene.meshes.slice(0);
  88290. var globalLength = globalPool.length;
  88291. for (var index = 0; index < globalLength; index++) {
  88292. var currentPool = new Array();
  88293. var current = globalPool[index];
  88294. // Checks
  88295. if (!this._canBeMerged(current)) {
  88296. continue;
  88297. }
  88298. currentPool.push(current);
  88299. // Find compatible meshes
  88300. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  88301. var otherMesh = globalPool[subIndex];
  88302. if (!this._canBeMerged(otherMesh)) {
  88303. continue;
  88304. }
  88305. if (otherMesh.material !== current.material) {
  88306. continue;
  88307. }
  88308. if (otherMesh.checkCollisions !== current.checkCollisions) {
  88309. continue;
  88310. }
  88311. currentPool.push(otherMesh);
  88312. globalLength--;
  88313. globalPool.splice(subIndex, 1);
  88314. subIndex--;
  88315. }
  88316. if (currentPool.length < 2) {
  88317. continue;
  88318. }
  88319. // Merge meshes
  88320. BABYLON.Mesh.MergeMeshes(currentPool);
  88321. }
  88322. if (updateSelectionTree != undefined) {
  88323. if (updateSelectionTree) {
  88324. scene.createOrUpdateSelectionOctree();
  88325. }
  88326. }
  88327. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  88328. scene.createOrUpdateSelectionOctree();
  88329. }
  88330. return true;
  88331. };
  88332. ;
  88333. MergeMeshesOptimization._UpdateSelectionTree = false;
  88334. return MergeMeshesOptimization;
  88335. }(SceneOptimization));
  88336. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  88337. /**
  88338. * Defines a list of options used by SceneOptimizer
  88339. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88340. */
  88341. var SceneOptimizerOptions = /** @class */ (function () {
  88342. /**
  88343. * Creates a new list of options used by SceneOptimizer
  88344. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  88345. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  88346. */
  88347. function SceneOptimizerOptions(
  88348. /**
  88349. * Defines the target frame rate to reach (60 by default)
  88350. */
  88351. targetFrameRate,
  88352. /**
  88353. * Defines the interval between two checkes (2000ms by default)
  88354. */
  88355. trackerDuration) {
  88356. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  88357. if (trackerDuration === void 0) { trackerDuration = 2000; }
  88358. this.targetFrameRate = targetFrameRate;
  88359. this.trackerDuration = trackerDuration;
  88360. /**
  88361. * Gets the list of optimizations to apply
  88362. */
  88363. this.optimizations = new Array();
  88364. }
  88365. /**
  88366. * Add a new optimization
  88367. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  88368. * @returns the current SceneOptimizerOptions
  88369. */
  88370. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  88371. this.optimizations.push(optimization);
  88372. return this;
  88373. };
  88374. /**
  88375. * Add a new custom optimization
  88376. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  88377. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  88378. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  88379. * @returns the current SceneOptimizerOptions
  88380. */
  88381. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  88382. if (priority === void 0) { priority = 0; }
  88383. var optimization = new CustomOptimization(priority);
  88384. optimization.onApply = onApply;
  88385. optimization.onGetDescription = onGetDescription;
  88386. this.optimizations.push(optimization);
  88387. return this;
  88388. };
  88389. /**
  88390. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  88391. * @param targetFrameRate defines the target frame rate (60 by default)
  88392. * @returns a SceneOptimizerOptions object
  88393. */
  88394. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  88395. var result = new SceneOptimizerOptions(targetFrameRate);
  88396. var priority = 0;
  88397. result.addOptimization(new MergeMeshesOptimization(priority));
  88398. result.addOptimization(new ShadowsOptimization(priority));
  88399. result.addOptimization(new LensFlaresOptimization(priority));
  88400. // Next priority
  88401. priority++;
  88402. result.addOptimization(new PostProcessesOptimization(priority));
  88403. result.addOptimization(new ParticlesOptimization(priority));
  88404. // Next priority
  88405. priority++;
  88406. result.addOptimization(new TextureOptimization(priority, 1024));
  88407. return result;
  88408. };
  88409. /**
  88410. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  88411. * @param targetFrameRate defines the target frame rate (60 by default)
  88412. * @returns a SceneOptimizerOptions object
  88413. */
  88414. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  88415. var result = new SceneOptimizerOptions(targetFrameRate);
  88416. var priority = 0;
  88417. result.addOptimization(new MergeMeshesOptimization(priority));
  88418. result.addOptimization(new ShadowsOptimization(priority));
  88419. result.addOptimization(new LensFlaresOptimization(priority));
  88420. // Next priority
  88421. priority++;
  88422. result.addOptimization(new PostProcessesOptimization(priority));
  88423. result.addOptimization(new ParticlesOptimization(priority));
  88424. // Next priority
  88425. priority++;
  88426. result.addOptimization(new TextureOptimization(priority, 512));
  88427. // Next priority
  88428. priority++;
  88429. result.addOptimization(new RenderTargetsOptimization(priority));
  88430. // Next priority
  88431. priority++;
  88432. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  88433. return result;
  88434. };
  88435. /**
  88436. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  88437. * @param targetFrameRate defines the target frame rate (60 by default)
  88438. * @returns a SceneOptimizerOptions object
  88439. */
  88440. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  88441. var result = new SceneOptimizerOptions(targetFrameRate);
  88442. var priority = 0;
  88443. result.addOptimization(new MergeMeshesOptimization(priority));
  88444. result.addOptimization(new ShadowsOptimization(priority));
  88445. result.addOptimization(new LensFlaresOptimization(priority));
  88446. // Next priority
  88447. priority++;
  88448. result.addOptimization(new PostProcessesOptimization(priority));
  88449. result.addOptimization(new ParticlesOptimization(priority));
  88450. // Next priority
  88451. priority++;
  88452. result.addOptimization(new TextureOptimization(priority, 256));
  88453. // Next priority
  88454. priority++;
  88455. result.addOptimization(new RenderTargetsOptimization(priority));
  88456. // Next priority
  88457. priority++;
  88458. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  88459. return result;
  88460. };
  88461. return SceneOptimizerOptions;
  88462. }());
  88463. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  88464. /**
  88465. * Class used to run optimizations in order to reach a target frame rate
  88466. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  88467. */
  88468. var SceneOptimizer = /** @class */ (function () {
  88469. /**
  88470. * Creates a new SceneOptimizer
  88471. * @param scene defines the scene to work on
  88472. * @param options defines the options to use with the SceneOptimizer
  88473. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  88474. * @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)
  88475. */
  88476. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  88477. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  88478. if (improvementMode === void 0) { improvementMode = false; }
  88479. var _this = this;
  88480. this._isRunning = false;
  88481. this._currentPriorityLevel = 0;
  88482. this._targetFrameRate = 60;
  88483. this._trackerDuration = 2000;
  88484. this._currentFrameRate = 0;
  88485. this._improvementMode = false;
  88486. /**
  88487. * Defines an observable called when the optimizer reaches the target frame rate
  88488. */
  88489. this.onSuccessObservable = new BABYLON.Observable();
  88490. /**
  88491. * Defines an observable called when the optimizer enables an optimization
  88492. */
  88493. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  88494. /**
  88495. * Defines an observable called when the optimizer is not able to reach the target frame rate
  88496. */
  88497. this.onFailureObservable = new BABYLON.Observable();
  88498. if (!options) {
  88499. this._options = new SceneOptimizerOptions();
  88500. }
  88501. else {
  88502. this._options = options;
  88503. }
  88504. if (this._options.targetFrameRate) {
  88505. this._targetFrameRate = this._options.targetFrameRate;
  88506. }
  88507. if (this._options.trackerDuration) {
  88508. this._trackerDuration = this._options.trackerDuration;
  88509. }
  88510. if (autoGeneratePriorities) {
  88511. var priority = 0;
  88512. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  88513. var optim = _a[_i];
  88514. optim.priority = priority++;
  88515. }
  88516. }
  88517. this._improvementMode = improvementMode;
  88518. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88519. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  88520. _this._sceneDisposeObserver = null;
  88521. _this.dispose();
  88522. });
  88523. }
  88524. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  88525. /**
  88526. * Gets a boolean indicating if the optimizer is in improvement mode
  88527. */
  88528. get: function () {
  88529. return this._improvementMode;
  88530. },
  88531. enumerable: true,
  88532. configurable: true
  88533. });
  88534. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  88535. /**
  88536. * Gets the current priority level (0 at start)
  88537. */
  88538. get: function () {
  88539. return this._currentPriorityLevel;
  88540. },
  88541. enumerable: true,
  88542. configurable: true
  88543. });
  88544. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  88545. /**
  88546. * Gets the current frame rate checked by the SceneOptimizer
  88547. */
  88548. get: function () {
  88549. return this._currentFrameRate;
  88550. },
  88551. enumerable: true,
  88552. configurable: true
  88553. });
  88554. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  88555. /**
  88556. * Gets or sets the current target frame rate (60 by default)
  88557. */
  88558. get: function () {
  88559. return this._targetFrameRate;
  88560. },
  88561. /**
  88562. * Gets or sets the current target frame rate (60 by default)
  88563. */
  88564. set: function (value) {
  88565. this._targetFrameRate = value;
  88566. },
  88567. enumerable: true,
  88568. configurable: true
  88569. });
  88570. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  88571. /**
  88572. * Gets or sets the current interval between two checks (every 2000ms by default)
  88573. */
  88574. get: function () {
  88575. return this._trackerDuration;
  88576. },
  88577. /**
  88578. * Gets or sets the current interval between two checks (every 2000ms by default)
  88579. */
  88580. set: function (value) {
  88581. this._trackerDuration = value;
  88582. },
  88583. enumerable: true,
  88584. configurable: true
  88585. });
  88586. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  88587. /**
  88588. * Gets the list of active optimizations
  88589. */
  88590. get: function () {
  88591. return this._options.optimizations;
  88592. },
  88593. enumerable: true,
  88594. configurable: true
  88595. });
  88596. /**
  88597. * Stops the current optimizer
  88598. */
  88599. SceneOptimizer.prototype.stop = function () {
  88600. this._isRunning = false;
  88601. };
  88602. /**
  88603. * Reset the optimizer to initial step (current priority level = 0)
  88604. */
  88605. SceneOptimizer.prototype.reset = function () {
  88606. this._currentPriorityLevel = 0;
  88607. };
  88608. /**
  88609. * Start the optimizer. By default it will try to reach a specific framerate
  88610. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  88611. */
  88612. SceneOptimizer.prototype.start = function () {
  88613. var _this = this;
  88614. if (this._isRunning) {
  88615. return;
  88616. }
  88617. this._isRunning = true;
  88618. // Let's wait for the scene to be ready before running our check
  88619. this._scene.executeWhenReady(function () {
  88620. setTimeout(function () {
  88621. _this._checkCurrentState();
  88622. }, _this._trackerDuration);
  88623. });
  88624. };
  88625. SceneOptimizer.prototype._checkCurrentState = function () {
  88626. var _this = this;
  88627. if (!this._isRunning) {
  88628. return;
  88629. }
  88630. var scene = this._scene;
  88631. var options = this._options;
  88632. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  88633. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  88634. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  88635. this._isRunning = false;
  88636. this.onSuccessObservable.notifyObservers(this);
  88637. return;
  88638. }
  88639. // Apply current level of optimizations
  88640. var allDone = true;
  88641. var noOptimizationApplied = true;
  88642. for (var index = 0; index < options.optimizations.length; index++) {
  88643. var optimization = options.optimizations[index];
  88644. if (optimization.priority === this._currentPriorityLevel) {
  88645. noOptimizationApplied = false;
  88646. allDone = allDone && optimization.apply(scene, this);
  88647. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  88648. }
  88649. }
  88650. // If no optimization was applied, this is a failure :(
  88651. if (noOptimizationApplied) {
  88652. this._isRunning = false;
  88653. this.onFailureObservable.notifyObservers(this);
  88654. return;
  88655. }
  88656. // If all optimizations were done, move to next level
  88657. if (allDone) {
  88658. this._currentPriorityLevel++;
  88659. }
  88660. // Let's the system running for a specific amount of time before checking FPS
  88661. scene.executeWhenReady(function () {
  88662. setTimeout(function () {
  88663. _this._checkCurrentState();
  88664. }, _this._trackerDuration);
  88665. });
  88666. };
  88667. /**
  88668. * Release all resources
  88669. */
  88670. SceneOptimizer.prototype.dispose = function () {
  88671. this.stop();
  88672. this.onSuccessObservable.clear();
  88673. this.onFailureObservable.clear();
  88674. this.onNewOptimizationAppliedObservable.clear();
  88675. if (this._sceneDisposeObserver) {
  88676. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88677. }
  88678. };
  88679. /**
  88680. * Helper function to create a SceneOptimizer with one single line of code
  88681. * @param scene defines the scene to work on
  88682. * @param options defines the options to use with the SceneOptimizer
  88683. * @param onSuccess defines a callback to call on success
  88684. * @param onFailure defines a callback to call on failure
  88685. * @returns the new SceneOptimizer object
  88686. */
  88687. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  88688. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  88689. if (onSuccess) {
  88690. optimizer.onSuccessObservable.add(function () {
  88691. onSuccess();
  88692. });
  88693. }
  88694. if (onFailure) {
  88695. optimizer.onFailureObservable.add(function () {
  88696. onFailure();
  88697. });
  88698. }
  88699. optimizer.start();
  88700. return optimizer;
  88701. };
  88702. return SceneOptimizer;
  88703. }());
  88704. BABYLON.SceneOptimizer = SceneOptimizer;
  88705. })(BABYLON || (BABYLON = {}));
  88706. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  88707. "use strict";
  88708. var BABYLON;
  88709. (function (BABYLON) {
  88710. var OutlineRenderer = /** @class */ (function () {
  88711. function OutlineRenderer(scene) {
  88712. this.zOffset = 1;
  88713. this._scene = scene;
  88714. }
  88715. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  88716. var _this = this;
  88717. if (useOverlay === void 0) { useOverlay = false; }
  88718. var scene = this._scene;
  88719. var engine = this._scene.getEngine();
  88720. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  88721. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  88722. return;
  88723. }
  88724. var mesh = subMesh.getRenderingMesh();
  88725. var material = subMesh.getMaterial();
  88726. if (!material || !scene.activeCamera) {
  88727. return;
  88728. }
  88729. engine.enableEffect(this._effect);
  88730. // Logarithmic depth
  88731. if (material.useLogarithmicDepth) {
  88732. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  88733. }
  88734. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  88735. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  88736. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  88737. // Bones
  88738. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88739. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88740. }
  88741. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  88742. // Alpha test
  88743. if (material && material.needAlphaTesting()) {
  88744. var alphaTexture = material.getAlphaTestTexture();
  88745. if (alphaTexture) {
  88746. this._effect.setTexture("diffuseSampler", alphaTexture);
  88747. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  88748. }
  88749. }
  88750. engine.setZOffset(-this.zOffset);
  88751. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  88752. engine.setZOffset(0);
  88753. };
  88754. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  88755. var defines = [];
  88756. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  88757. var mesh = subMesh.getMesh();
  88758. var material = subMesh.getMaterial();
  88759. if (material) {
  88760. // Alpha test
  88761. if (material.needAlphaTesting()) {
  88762. defines.push("#define ALPHATEST");
  88763. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88764. attribs.push(BABYLON.VertexBuffer.UVKind);
  88765. defines.push("#define UV1");
  88766. }
  88767. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  88768. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88769. defines.push("#define UV2");
  88770. }
  88771. }
  88772. //Logarithmic depth
  88773. if (material.useLogarithmicDepth) {
  88774. defines.push("#define LOGARITHMICDEPTH");
  88775. }
  88776. }
  88777. // Bones
  88778. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88779. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88780. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88781. if (mesh.numBoneInfluencers > 4) {
  88782. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  88783. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  88784. }
  88785. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88786. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  88787. }
  88788. else {
  88789. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88790. }
  88791. // Instances
  88792. if (useInstances) {
  88793. defines.push("#define INSTANCES");
  88794. attribs.push("world0");
  88795. attribs.push("world1");
  88796. attribs.push("world2");
  88797. attribs.push("world3");
  88798. }
  88799. // Get correct effect
  88800. var join = defines.join("\n");
  88801. if (this._cachedDefines !== join) {
  88802. this._cachedDefines = join;
  88803. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  88804. }
  88805. return this._effect.isReady();
  88806. };
  88807. return OutlineRenderer;
  88808. }());
  88809. BABYLON.OutlineRenderer = OutlineRenderer;
  88810. })(BABYLON || (BABYLON = {}));
  88811. //# sourceMappingURL=babylon.outlineRenderer.js.map
  88812. "use strict";
  88813. var BABYLON;
  88814. (function (BABYLON) {
  88815. var FaceAdjacencies = /** @class */ (function () {
  88816. function FaceAdjacencies() {
  88817. this.edges = new Array();
  88818. this.edgesConnectedCount = 0;
  88819. }
  88820. return FaceAdjacencies;
  88821. }());
  88822. var EdgesRenderer = /** @class */ (function () {
  88823. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  88824. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  88825. if (epsilon === void 0) { epsilon = 0.95; }
  88826. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  88827. this.edgesWidthScalerForOrthographic = 1000.0;
  88828. this.edgesWidthScalerForPerspective = 50.0;
  88829. this._linesPositions = new Array();
  88830. this._linesNormals = new Array();
  88831. this._linesIndices = new Array();
  88832. this._buffers = {};
  88833. this._checkVerticesInsteadOfIndices = false;
  88834. this._source = source;
  88835. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  88836. this._epsilon = epsilon;
  88837. this._prepareRessources();
  88838. this._generateEdgesLines();
  88839. }
  88840. EdgesRenderer.prototype._prepareRessources = function () {
  88841. if (this._lineShader) {
  88842. return;
  88843. }
  88844. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  88845. attributes: ["position", "normal"],
  88846. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  88847. });
  88848. this._lineShader.disableDepthWrite = true;
  88849. this._lineShader.backFaceCulling = false;
  88850. };
  88851. EdgesRenderer.prototype._rebuild = function () {
  88852. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  88853. if (buffer) {
  88854. buffer._rebuild();
  88855. }
  88856. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  88857. if (buffer) {
  88858. buffer._rebuild();
  88859. }
  88860. var scene = this._source.getScene();
  88861. var engine = scene.getEngine();
  88862. this._ib = engine.createIndexBuffer(this._linesIndices);
  88863. };
  88864. EdgesRenderer.prototype.dispose = function () {
  88865. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  88866. if (buffer) {
  88867. buffer.dispose();
  88868. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  88869. }
  88870. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  88871. if (buffer) {
  88872. buffer.dispose();
  88873. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  88874. }
  88875. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  88876. this._lineShader.dispose();
  88877. };
  88878. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  88879. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  88880. return 0;
  88881. }
  88882. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  88883. return 1;
  88884. }
  88885. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  88886. return 2;
  88887. }
  88888. return -1;
  88889. };
  88890. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  88891. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  88892. return 0;
  88893. }
  88894. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  88895. return 1;
  88896. }
  88897. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  88898. return 2;
  88899. }
  88900. return -1;
  88901. };
  88902. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  88903. var needToCreateLine;
  88904. if (edge === undefined) {
  88905. needToCreateLine = true;
  88906. }
  88907. else {
  88908. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  88909. needToCreateLine = dotProduct < this._epsilon;
  88910. }
  88911. if (needToCreateLine) {
  88912. var offset = this._linesPositions.length / 3;
  88913. var normal = p0.subtract(p1);
  88914. normal.normalize();
  88915. // Positions
  88916. this._linesPositions.push(p0.x);
  88917. this._linesPositions.push(p0.y);
  88918. this._linesPositions.push(p0.z);
  88919. this._linesPositions.push(p0.x);
  88920. this._linesPositions.push(p0.y);
  88921. this._linesPositions.push(p0.z);
  88922. this._linesPositions.push(p1.x);
  88923. this._linesPositions.push(p1.y);
  88924. this._linesPositions.push(p1.z);
  88925. this._linesPositions.push(p1.x);
  88926. this._linesPositions.push(p1.y);
  88927. this._linesPositions.push(p1.z);
  88928. // Normals
  88929. this._linesNormals.push(p1.x);
  88930. this._linesNormals.push(p1.y);
  88931. this._linesNormals.push(p1.z);
  88932. this._linesNormals.push(-1);
  88933. this._linesNormals.push(p1.x);
  88934. this._linesNormals.push(p1.y);
  88935. this._linesNormals.push(p1.z);
  88936. this._linesNormals.push(1);
  88937. this._linesNormals.push(p0.x);
  88938. this._linesNormals.push(p0.y);
  88939. this._linesNormals.push(p0.z);
  88940. this._linesNormals.push(-1);
  88941. this._linesNormals.push(p0.x);
  88942. this._linesNormals.push(p0.y);
  88943. this._linesNormals.push(p0.z);
  88944. this._linesNormals.push(1);
  88945. // Indices
  88946. this._linesIndices.push(offset);
  88947. this._linesIndices.push(offset + 1);
  88948. this._linesIndices.push(offset + 2);
  88949. this._linesIndices.push(offset);
  88950. this._linesIndices.push(offset + 2);
  88951. this._linesIndices.push(offset + 3);
  88952. }
  88953. };
  88954. EdgesRenderer.prototype._generateEdgesLines = function () {
  88955. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88956. var indices = this._source.getIndices();
  88957. if (!indices || !positions) {
  88958. return;
  88959. }
  88960. // First let's find adjacencies
  88961. var adjacencies = new Array();
  88962. var faceNormals = new Array();
  88963. var index;
  88964. var faceAdjacencies;
  88965. // Prepare faces
  88966. for (index = 0; index < indices.length; index += 3) {
  88967. faceAdjacencies = new FaceAdjacencies();
  88968. var p0Index = indices[index];
  88969. var p1Index = indices[index + 1];
  88970. var p2Index = indices[index + 2];
  88971. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  88972. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  88973. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  88974. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  88975. faceNormal.normalize();
  88976. faceNormals.push(faceNormal);
  88977. adjacencies.push(faceAdjacencies);
  88978. }
  88979. // Scan
  88980. for (index = 0; index < adjacencies.length; index++) {
  88981. faceAdjacencies = adjacencies[index];
  88982. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  88983. var otherFaceAdjacencies = adjacencies[otherIndex];
  88984. if (faceAdjacencies.edgesConnectedCount === 3) {
  88985. break;
  88986. }
  88987. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  88988. continue;
  88989. }
  88990. var otherP0 = indices[otherIndex * 3];
  88991. var otherP1 = indices[otherIndex * 3 + 1];
  88992. var otherP2 = indices[otherIndex * 3 + 2];
  88993. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  88994. var otherEdgeIndex = 0;
  88995. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  88996. continue;
  88997. }
  88998. switch (edgeIndex) {
  88999. case 0:
  89000. if (this._checkVerticesInsteadOfIndices) {
  89001. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89002. }
  89003. else {
  89004. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  89005. }
  89006. break;
  89007. case 1:
  89008. if (this._checkVerticesInsteadOfIndices) {
  89009. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89010. }
  89011. else {
  89012. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  89013. }
  89014. break;
  89015. case 2:
  89016. if (this._checkVerticesInsteadOfIndices) {
  89017. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  89018. }
  89019. else {
  89020. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  89021. }
  89022. break;
  89023. }
  89024. if (otherEdgeIndex === -1) {
  89025. continue;
  89026. }
  89027. faceAdjacencies.edges[edgeIndex] = otherIndex;
  89028. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  89029. faceAdjacencies.edgesConnectedCount++;
  89030. otherFaceAdjacencies.edgesConnectedCount++;
  89031. if (faceAdjacencies.edgesConnectedCount === 3) {
  89032. break;
  89033. }
  89034. }
  89035. }
  89036. }
  89037. // Create lines
  89038. for (index = 0; index < adjacencies.length; index++) {
  89039. // 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
  89040. var current = adjacencies[index];
  89041. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  89042. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  89043. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  89044. }
  89045. // Merge into a single mesh
  89046. var engine = this._source.getScene().getEngine();
  89047. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  89048. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  89049. this._ib = engine.createIndexBuffer(this._linesIndices);
  89050. this._indicesCount = this._linesIndices.length;
  89051. };
  89052. EdgesRenderer.prototype.render = function () {
  89053. var scene = this._source.getScene();
  89054. if (!this._lineShader.isReady() || !scene.activeCamera) {
  89055. return;
  89056. }
  89057. var engine = scene.getEngine();
  89058. this._lineShader._preBind();
  89059. // VBOs
  89060. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  89061. scene.resetCachedMaterial();
  89062. this._lineShader.setColor4("color", this._source.edgesColor);
  89063. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  89064. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  89065. }
  89066. else {
  89067. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  89068. }
  89069. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  89070. this._lineShader.bind(this._source.getWorldMatrix());
  89071. // Draw order
  89072. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  89073. this._lineShader.unbind();
  89074. engine.setDepthWrite(true);
  89075. };
  89076. return EdgesRenderer;
  89077. }());
  89078. BABYLON.EdgesRenderer = EdgesRenderer;
  89079. })(BABYLON || (BABYLON = {}));
  89080. //# sourceMappingURL=babylon.edgesRenderer.js.map
  89081. "use strict";
  89082. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89083. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89084. s = arguments[i];
  89085. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89086. t[p] = s[p];
  89087. }
  89088. return t;
  89089. };
  89090. var BABYLON;
  89091. (function (BABYLON) {
  89092. /**
  89093. * The effect layer Helps adding post process effect blended with the main pass.
  89094. *
  89095. * This can be for instance use to generate glow or higlight effects on the scene.
  89096. *
  89097. * The effect layer class can not be used directly and is intented to inherited from to be
  89098. * customized per effects.
  89099. */
  89100. var EffectLayer = /** @class */ (function () {
  89101. /**
  89102. * Instantiates a new effect Layer and references it in the scene.
  89103. * @param name The name of the layer
  89104. * @param scene The scene to use the layer in
  89105. */
  89106. function EffectLayer(
  89107. /** The Friendly of the effect in the scene */
  89108. name, scene) {
  89109. this._vertexBuffers = {};
  89110. this._maxSize = 0;
  89111. this._mainTextureDesiredSize = { width: 0, height: 0 };
  89112. this._shouldRender = true;
  89113. this._postProcesses = [];
  89114. this._textures = [];
  89115. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  89116. /**
  89117. * The clear color of the texture used to generate the glow map.
  89118. */
  89119. this.neutralColor = new BABYLON.Color4();
  89120. /**
  89121. * Specifies wether the highlight layer is enabled or not.
  89122. */
  89123. this.isEnabled = true;
  89124. /**
  89125. * An event triggered when the effect layer has been disposed.
  89126. */
  89127. this.onDisposeObservable = new BABYLON.Observable();
  89128. /**
  89129. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  89130. */
  89131. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  89132. /**
  89133. * An event triggered when the generated texture is being merged in the scene.
  89134. */
  89135. this.onBeforeComposeObservable = new BABYLON.Observable();
  89136. /**
  89137. * An event triggered when the generated texture has been merged in the scene.
  89138. */
  89139. this.onAfterComposeObservable = new BABYLON.Observable();
  89140. /**
  89141. * An event triggered when the efffect layer changes its size.
  89142. */
  89143. this.onSizeChangedObservable = new BABYLON.Observable();
  89144. this.name = name;
  89145. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89146. this._engine = scene.getEngine();
  89147. this._maxSize = this._engine.getCaps().maxTextureSize;
  89148. this._scene.effectLayers.push(this);
  89149. // Generate Buffers
  89150. this._generateIndexBuffer();
  89151. this._genrateVertexBuffer();
  89152. }
  89153. Object.defineProperty(EffectLayer.prototype, "camera", {
  89154. /**
  89155. * Gets the camera attached to the layer.
  89156. */
  89157. get: function () {
  89158. return this._effectLayerOptions.camera;
  89159. },
  89160. enumerable: true,
  89161. configurable: true
  89162. });
  89163. /**
  89164. * Initializes the effect layer with the required options.
  89165. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  89166. */
  89167. EffectLayer.prototype._init = function (options) {
  89168. // Adapt options
  89169. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89170. this._setMainTextureSize();
  89171. this._createMainTexture();
  89172. this._createTextureAndPostProcesses();
  89173. this._mergeEffect = this._createMergeEffect();
  89174. };
  89175. /**
  89176. * Generates the index buffer of the full screen quad blending to the main canvas.
  89177. */
  89178. EffectLayer.prototype._generateIndexBuffer = function () {
  89179. // Indices
  89180. var indices = [];
  89181. indices.push(0);
  89182. indices.push(1);
  89183. indices.push(2);
  89184. indices.push(0);
  89185. indices.push(2);
  89186. indices.push(3);
  89187. this._indexBuffer = this._engine.createIndexBuffer(indices);
  89188. };
  89189. /**
  89190. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  89191. */
  89192. EffectLayer.prototype._genrateVertexBuffer = function () {
  89193. // VBO
  89194. var vertices = [];
  89195. vertices.push(1, 1);
  89196. vertices.push(-1, 1);
  89197. vertices.push(-1, -1);
  89198. vertices.push(1, -1);
  89199. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89200. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89201. };
  89202. /**
  89203. * Sets the main texture desired size which is the closest power of two
  89204. * of the engine canvas size.
  89205. */
  89206. EffectLayer.prototype._setMainTextureSize = function () {
  89207. if (this._effectLayerOptions.mainTextureFixedSize) {
  89208. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  89209. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  89210. }
  89211. else {
  89212. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  89213. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  89214. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  89215. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  89216. }
  89217. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  89218. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  89219. };
  89220. /**
  89221. * Creates the main texture for the effect layer.
  89222. */
  89223. EffectLayer.prototype._createMainTexture = function () {
  89224. var _this = this;
  89225. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  89226. width: this._mainTextureDesiredSize.width,
  89227. height: this._mainTextureDesiredSize.height
  89228. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89229. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  89230. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89231. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89232. this._mainTexture.anisotropicFilteringLevel = 1;
  89233. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89234. this._mainTexture.renderParticles = false;
  89235. this._mainTexture.renderList = null;
  89236. this._mainTexture.ignoreCameraViewport = true;
  89237. // Custom render function
  89238. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89239. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  89240. var index;
  89241. var engine = _this._scene.getEngine();
  89242. if (depthOnlySubMeshes.length) {
  89243. engine.setColorWrite(false);
  89244. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89245. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  89246. }
  89247. engine.setColorWrite(true);
  89248. }
  89249. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89250. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  89251. }
  89252. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89253. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  89254. }
  89255. for (index = 0; index < transparentSubMeshes.length; index++) {
  89256. _this._renderSubMesh(transparentSubMeshes.data[index]);
  89257. }
  89258. };
  89259. this._mainTexture.onClearObservable.add(function (engine) {
  89260. engine.clear(_this.neutralColor, true, true, true);
  89261. });
  89262. };
  89263. /**
  89264. * Checks for the readiness of the element composing the layer.
  89265. * @param subMesh the mesh to check for
  89266. * @param useInstances specify wether or not to use instances to render the mesh
  89267. * @param emissiveTexture the associated emissive texture used to generate the glow
  89268. * @return true if ready otherwise, false
  89269. */
  89270. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  89271. var material = subMesh.getMaterial();
  89272. if (!material) {
  89273. return false;
  89274. }
  89275. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  89276. return false;
  89277. }
  89278. var defines = [];
  89279. var attribs = [BABYLON.VertexBuffer.PositionKind];
  89280. var mesh = subMesh.getMesh();
  89281. var uv1 = false;
  89282. var uv2 = false;
  89283. // Alpha test
  89284. if (material && material.needAlphaTesting()) {
  89285. var alphaTexture = material.getAlphaTestTexture();
  89286. if (alphaTexture) {
  89287. defines.push("#define ALPHATEST");
  89288. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89289. alphaTexture.coordinatesIndex === 1) {
  89290. defines.push("#define DIFFUSEUV2");
  89291. uv2 = true;
  89292. }
  89293. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89294. defines.push("#define DIFFUSEUV1");
  89295. uv1 = true;
  89296. }
  89297. }
  89298. }
  89299. // Emissive
  89300. if (emissiveTexture) {
  89301. defines.push("#define EMISSIVE");
  89302. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  89303. emissiveTexture.coordinatesIndex === 1) {
  89304. defines.push("#define EMISSIVEUV2");
  89305. uv2 = true;
  89306. }
  89307. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  89308. defines.push("#define EMISSIVEUV1");
  89309. uv1 = true;
  89310. }
  89311. }
  89312. if (uv1) {
  89313. attribs.push(BABYLON.VertexBuffer.UVKind);
  89314. defines.push("#define UV1");
  89315. }
  89316. if (uv2) {
  89317. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  89318. defines.push("#define UV2");
  89319. }
  89320. // Bones
  89321. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  89322. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  89323. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  89324. if (mesh.numBoneInfluencers > 4) {
  89325. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  89326. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  89327. }
  89328. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  89329. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  89330. }
  89331. else {
  89332. defines.push("#define NUM_BONE_INFLUENCERS 0");
  89333. }
  89334. // Morph targets
  89335. var manager = mesh.morphTargetManager;
  89336. var morphInfluencers = 0;
  89337. if (manager) {
  89338. if (manager.numInfluencers > 0) {
  89339. defines.push("#define MORPHTARGETS");
  89340. morphInfluencers = manager.numInfluencers;
  89341. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  89342. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  89343. }
  89344. }
  89345. // Instances
  89346. if (useInstances) {
  89347. defines.push("#define INSTANCES");
  89348. attribs.push("world0");
  89349. attribs.push("world1");
  89350. attribs.push("world2");
  89351. attribs.push("world3");
  89352. }
  89353. // Get correct effect
  89354. var join = defines.join("\n");
  89355. if (this._cachedDefines !== join) {
  89356. this._cachedDefines = join;
  89357. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  89358. }
  89359. return this._effectLayerMapGenerationEffect.isReady();
  89360. };
  89361. /**
  89362. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  89363. */
  89364. EffectLayer.prototype.render = function () {
  89365. var currentEffect = this._mergeEffect;
  89366. // Check
  89367. if (!currentEffect.isReady())
  89368. return;
  89369. for (var i = 0; i < this._postProcesses.length; i++) {
  89370. if (!this._postProcesses[i].isReady()) {
  89371. return;
  89372. }
  89373. }
  89374. var engine = this._scene.getEngine();
  89375. this.onBeforeComposeObservable.notifyObservers(this);
  89376. // Render
  89377. engine.enableEffect(currentEffect);
  89378. engine.setState(false);
  89379. // VBOs
  89380. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89381. // Cache
  89382. var previousAlphaMode = engine.getAlphaMode();
  89383. // Go Blend.
  89384. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  89385. // Blends the map on the main canvas.
  89386. this._internalRender(currentEffect);
  89387. // Restore Alpha
  89388. engine.setAlphaMode(previousAlphaMode);
  89389. this.onAfterComposeObservable.notifyObservers(this);
  89390. // Handle size changes.
  89391. var size = this._mainTexture.getSize();
  89392. this._setMainTextureSize();
  89393. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  89394. // Recreate RTT and post processes on size change.
  89395. this.onSizeChangedObservable.notifyObservers(this);
  89396. this._disposeTextureAndPostProcesses();
  89397. this._createMainTexture();
  89398. this._createTextureAndPostProcesses();
  89399. }
  89400. };
  89401. /**
  89402. * Determine if a given mesh will be used in the current effect.
  89403. * @param mesh mesh to test
  89404. * @returns true if the mesh will be used
  89405. */
  89406. EffectLayer.prototype.hasMesh = function (mesh) {
  89407. return true;
  89408. };
  89409. /**
  89410. * Returns true if the layer contains information to display, otherwise false.
  89411. * @returns true if the glow layer should be rendered
  89412. */
  89413. EffectLayer.prototype.shouldRender = function () {
  89414. return this.isEnabled && this._shouldRender;
  89415. };
  89416. /**
  89417. * Returns true if the mesh should render, otherwise false.
  89418. * @param mesh The mesh to render
  89419. * @returns true if it should render otherwise false
  89420. */
  89421. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  89422. return true;
  89423. };
  89424. /**
  89425. * Returns true if the mesh should render, otherwise false.
  89426. * @param mesh The mesh to render
  89427. * @returns true if it should render otherwise false
  89428. */
  89429. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  89430. return true;
  89431. };
  89432. /**
  89433. * Renders the submesh passed in parameter to the generation map.
  89434. */
  89435. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  89436. var _this = this;
  89437. if (!this.shouldRender()) {
  89438. return;
  89439. }
  89440. var material = subMesh.getMaterial();
  89441. var mesh = subMesh.getRenderingMesh();
  89442. var scene = this._scene;
  89443. var engine = scene.getEngine();
  89444. if (!material) {
  89445. return;
  89446. }
  89447. // Do not block in blend mode.
  89448. if (material.needAlphaBlendingForMesh(mesh)) {
  89449. return;
  89450. }
  89451. // Culling
  89452. engine.setState(material.backFaceCulling);
  89453. // Managing instances
  89454. var batch = mesh._getInstancesRenderList(subMesh._id);
  89455. if (batch.mustReturn) {
  89456. return;
  89457. }
  89458. // Early Exit per mesh
  89459. if (!this._shouldRenderMesh(mesh)) {
  89460. return;
  89461. }
  89462. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  89463. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  89464. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  89465. engine.enableEffect(this._effectLayerMapGenerationEffect);
  89466. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  89467. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  89468. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  89469. // Alpha test
  89470. if (material && material.needAlphaTesting()) {
  89471. var alphaTexture = material.getAlphaTestTexture();
  89472. if (alphaTexture) {
  89473. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  89474. var textureMatrix = alphaTexture.getTextureMatrix();
  89475. if (textureMatrix) {
  89476. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  89477. }
  89478. }
  89479. }
  89480. // Glow emissive only
  89481. if (this._emissiveTextureAndColor.texture) {
  89482. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  89483. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  89484. }
  89485. // Bones
  89486. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89487. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89488. }
  89489. // Morph targets
  89490. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  89491. // Draw
  89492. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  89493. }
  89494. else {
  89495. // Need to reset refresh rate of the shadowMap
  89496. this._mainTexture.resetRefreshCounter();
  89497. }
  89498. };
  89499. /**
  89500. * Rebuild the required buffers.
  89501. * @ignore Internal use only.
  89502. */
  89503. EffectLayer.prototype._rebuild = function () {
  89504. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89505. if (vb) {
  89506. vb._rebuild();
  89507. }
  89508. this._generateIndexBuffer();
  89509. };
  89510. /**
  89511. * Dispose only the render target textures and post process.
  89512. */
  89513. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  89514. this._mainTexture.dispose();
  89515. for (var i = 0; i < this._postProcesses.length; i++) {
  89516. if (this._postProcesses[i]) {
  89517. this._postProcesses[i].dispose();
  89518. }
  89519. }
  89520. this._postProcesses = [];
  89521. for (var i = 0; i < this._textures.length; i++) {
  89522. if (this._textures[i]) {
  89523. this._textures[i].dispose();
  89524. }
  89525. }
  89526. this._textures = [];
  89527. };
  89528. /**
  89529. * Dispose the highlight layer and free resources.
  89530. */
  89531. EffectLayer.prototype.dispose = function () {
  89532. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89533. if (vertexBuffer) {
  89534. vertexBuffer.dispose();
  89535. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89536. }
  89537. if (this._indexBuffer) {
  89538. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89539. this._indexBuffer = null;
  89540. }
  89541. // Clean textures and post processes
  89542. this._disposeTextureAndPostProcesses();
  89543. // Remove from scene
  89544. var index = this._scene.effectLayers.indexOf(this, 0);
  89545. if (index > -1) {
  89546. this._scene.effectLayers.splice(index, 1);
  89547. }
  89548. // Callback
  89549. this.onDisposeObservable.notifyObservers(this);
  89550. this.onDisposeObservable.clear();
  89551. this.onBeforeRenderMainTextureObservable.clear();
  89552. this.onBeforeComposeObservable.clear();
  89553. this.onAfterComposeObservable.clear();
  89554. this.onSizeChangedObservable.clear();
  89555. };
  89556. /**
  89557. * Gets the class name of the effect layer
  89558. * @returns the string with the class name of the effect layer
  89559. */
  89560. EffectLayer.prototype.getClassName = function () {
  89561. return "EffectLayer";
  89562. };
  89563. /**
  89564. * Creates an effect layer from parsed effect layer data
  89565. * @param parsedEffectLayer defines effect layer data
  89566. * @param scene defines the current scene
  89567. * @param rootUrl defines the root URL containing the effect layer information
  89568. * @returns a parsed effect Layer
  89569. */
  89570. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  89571. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  89572. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  89573. };
  89574. __decorate([
  89575. BABYLON.serialize()
  89576. ], EffectLayer.prototype, "name", void 0);
  89577. __decorate([
  89578. BABYLON.serializeAsColor4()
  89579. ], EffectLayer.prototype, "neutralColor", void 0);
  89580. __decorate([
  89581. BABYLON.serialize()
  89582. ], EffectLayer.prototype, "isEnabled", void 0);
  89583. __decorate([
  89584. BABYLON.serializeAsCameraReference()
  89585. ], EffectLayer.prototype, "camera", null);
  89586. return EffectLayer;
  89587. }());
  89588. BABYLON.EffectLayer = EffectLayer;
  89589. })(BABYLON || (BABYLON = {}));
  89590. //# sourceMappingURL=babylon.effectLayer.js.map
  89591. "use strict";
  89592. var BABYLON;
  89593. (function (BABYLON) {
  89594. /**
  89595. * Special Glow Blur post process only blurring the alpha channel
  89596. * It enforces keeping the most luminous color in the color channel.
  89597. */
  89598. var GlowBlurPostProcess = /** @class */ (function (_super) {
  89599. __extends(GlowBlurPostProcess, _super);
  89600. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  89601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89602. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  89603. _this.direction = direction;
  89604. _this.kernel = kernel;
  89605. _this.onApplyObservable.add(function (effect) {
  89606. effect.setFloat2("screenSize", _this.width, _this.height);
  89607. effect.setVector2("direction", _this.direction);
  89608. effect.setFloat("blurWidth", _this.kernel);
  89609. });
  89610. return _this;
  89611. }
  89612. return GlowBlurPostProcess;
  89613. }(BABYLON.PostProcess));
  89614. /**
  89615. * The highlight layer Helps adding a glow effect around a mesh.
  89616. *
  89617. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  89618. * glowy meshes to your scene.
  89619. *
  89620. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  89621. */
  89622. var HighlightLayer = /** @class */ (function (_super) {
  89623. __extends(HighlightLayer, _super);
  89624. /**
  89625. * Instantiates a new highlight Layer and references it to the scene..
  89626. * @param name The name of the layer
  89627. * @param scene The scene to use the layer in
  89628. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  89629. */
  89630. function HighlightLayer(name, scene, options) {
  89631. var _this = _super.call(this, name, scene) || this;
  89632. _this.name = name;
  89633. /**
  89634. * Specifies whether or not the inner glow is ACTIVE in the layer.
  89635. */
  89636. _this.innerGlow = true;
  89637. /**
  89638. * Specifies whether or not the outer glow is ACTIVE in the layer.
  89639. */
  89640. _this.outerGlow = true;
  89641. /**
  89642. * An event triggered when the highlight layer is being blurred.
  89643. */
  89644. _this.onBeforeBlurObservable = new BABYLON.Observable();
  89645. /**
  89646. * An event triggered when the highlight layer has been blurred.
  89647. */
  89648. _this.onAfterBlurObservable = new BABYLON.Observable();
  89649. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  89650. _this._meshes = {};
  89651. _this._excludedMeshes = {};
  89652. _this.neutralColor = HighlightLayer.NeutralColor;
  89653. // Warn on stencil
  89654. if (!_this._engine.isStencilEnable) {
  89655. 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 }");
  89656. }
  89657. // Adapt options
  89658. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  89659. // Initialize the layer
  89660. _this._init({
  89661. alphaBlendingMode: _this._options.alphaBlendingMode,
  89662. camera: _this._options.camera,
  89663. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  89664. mainTextureRatio: _this._options.mainTextureRatio
  89665. });
  89666. // Do not render as long as no meshes have been added
  89667. _this._shouldRender = false;
  89668. return _this;
  89669. }
  89670. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  89671. /**
  89672. * Gets the horizontal size of the blur.
  89673. */
  89674. get: function () {
  89675. return this._horizontalBlurPostprocess.kernel;
  89676. },
  89677. /**
  89678. * Specifies the horizontal size of the blur.
  89679. */
  89680. set: function (value) {
  89681. this._horizontalBlurPostprocess.kernel = value;
  89682. },
  89683. enumerable: true,
  89684. configurable: true
  89685. });
  89686. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  89687. /**
  89688. * Gets the vertical size of the blur.
  89689. */
  89690. get: function () {
  89691. return this._verticalBlurPostprocess.kernel;
  89692. },
  89693. /**
  89694. * Specifies the vertical size of the blur.
  89695. */
  89696. set: function (value) {
  89697. this._verticalBlurPostprocess.kernel = value;
  89698. },
  89699. enumerable: true,
  89700. configurable: true
  89701. });
  89702. /**
  89703. * Get the effect name of the layer.
  89704. * @return The effect name
  89705. */
  89706. HighlightLayer.prototype.getEffectName = function () {
  89707. return HighlightLayer.EffectName;
  89708. };
  89709. /**
  89710. * Create the merge effect. This is the shader use to blit the information back
  89711. * to the main canvas at the end of the scene rendering.
  89712. */
  89713. HighlightLayer.prototype._createMergeEffect = function () {
  89714. // Effect
  89715. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  89716. };
  89717. /**
  89718. * Creates the render target textures and post processes used in the highlight layer.
  89719. */
  89720. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  89721. var _this = this;
  89722. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  89723. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  89724. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  89725. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  89726. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  89727. width: blurTextureWidth,
  89728. height: blurTextureHeight
  89729. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89730. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89731. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89732. this._blurTexture.anisotropicFilteringLevel = 16;
  89733. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89734. this._blurTexture.renderParticles = false;
  89735. this._blurTexture.ignoreCameraViewport = true;
  89736. this._textures = [this._blurTexture];
  89737. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  89738. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89739. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  89740. effect.setTexture("textureSampler", _this._mainTexture);
  89741. });
  89742. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89743. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  89744. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  89745. });
  89746. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  89747. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  89748. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  89749. });
  89750. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  89751. }
  89752. else {
  89753. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  89754. width: blurTextureWidth,
  89755. height: blurTextureHeight
  89756. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89757. this._horizontalBlurPostprocess.width = blurTextureWidth;
  89758. this._horizontalBlurPostprocess.height = blurTextureHeight;
  89759. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  89760. effect.setTexture("textureSampler", _this._mainTexture);
  89761. });
  89762. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  89763. width: blurTextureWidth,
  89764. height: blurTextureHeight
  89765. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  89766. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  89767. }
  89768. this._mainTexture.onAfterUnbindObservable.add(function () {
  89769. _this.onBeforeBlurObservable.notifyObservers(_this);
  89770. var internalTexture = _this._blurTexture.getInternalTexture();
  89771. if (internalTexture) {
  89772. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  89773. }
  89774. _this.onAfterBlurObservable.notifyObservers(_this);
  89775. });
  89776. // Prevent autoClear.
  89777. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  89778. };
  89779. /**
  89780. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  89781. */
  89782. HighlightLayer.prototype.needStencil = function () {
  89783. return true;
  89784. };
  89785. /**
  89786. * Checks for the readiness of the element composing the layer.
  89787. * @param subMesh the mesh to check for
  89788. * @param useInstances specify wether or not to use instances to render the mesh
  89789. * @param emissiveTexture the associated emissive texture used to generate the glow
  89790. * @return true if ready otherwise, false
  89791. */
  89792. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  89793. var material = subMesh.getMaterial();
  89794. var mesh = subMesh.getRenderingMesh();
  89795. if (!material || !mesh || !this._meshes) {
  89796. return false;
  89797. }
  89798. var emissiveTexture = null;
  89799. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  89800. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  89801. emissiveTexture = material.emissiveTexture;
  89802. }
  89803. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  89804. };
  89805. /**
  89806. * Implementation specific of rendering the generating effect on the main canvas.
  89807. * @param effect The effect used to render through
  89808. */
  89809. HighlightLayer.prototype._internalRender = function (effect) {
  89810. // Texture
  89811. effect.setTexture("textureSampler", this._blurTexture);
  89812. // Cache
  89813. var engine = this._engine;
  89814. var previousStencilBuffer = engine.getStencilBuffer();
  89815. var previousStencilFunction = engine.getStencilFunction();
  89816. var previousStencilMask = engine.getStencilMask();
  89817. var previousStencilOperationPass = engine.getStencilOperationPass();
  89818. var previousStencilOperationFail = engine.getStencilOperationFail();
  89819. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  89820. var previousStencilReference = engine.getStencilFunctionReference();
  89821. // Stencil operations
  89822. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  89823. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  89824. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  89825. // Draw order
  89826. engine.setStencilMask(0x00);
  89827. engine.setStencilBuffer(true);
  89828. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  89829. // 2 passes inner outer
  89830. if (this.outerGlow) {
  89831. effect.setFloat("offset", 0);
  89832. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  89833. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89834. }
  89835. if (this.innerGlow) {
  89836. effect.setFloat("offset", 1);
  89837. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  89838. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89839. }
  89840. // Restore Cache
  89841. engine.setStencilFunction(previousStencilFunction);
  89842. engine.setStencilMask(previousStencilMask);
  89843. engine.setStencilBuffer(previousStencilBuffer);
  89844. engine.setStencilOperationPass(previousStencilOperationPass);
  89845. engine.setStencilOperationFail(previousStencilOperationFail);
  89846. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  89847. engine.setStencilFunctionReference(previousStencilReference);
  89848. };
  89849. /**
  89850. * Returns true if the layer contains information to display, otherwise false.
  89851. */
  89852. HighlightLayer.prototype.shouldRender = function () {
  89853. if (_super.prototype.shouldRender.call(this)) {
  89854. return this._meshes ? true : false;
  89855. }
  89856. return false;
  89857. };
  89858. /**
  89859. * Returns true if the mesh should render, otherwise false.
  89860. * @param mesh The mesh to render
  89861. * @returns true if it should render otherwise false
  89862. */
  89863. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  89864. // Excluded Mesh
  89865. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  89866. return false;
  89867. }
  89868. ;
  89869. return true;
  89870. };
  89871. /**
  89872. * Sets the required values for both the emissive texture and and the main color.
  89873. */
  89874. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  89875. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  89876. if (highlightLayerMesh) {
  89877. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  89878. }
  89879. else {
  89880. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  89881. }
  89882. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  89883. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  89884. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  89885. }
  89886. else {
  89887. this._emissiveTextureAndColor.texture = null;
  89888. }
  89889. };
  89890. /**
  89891. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  89892. * @param mesh The mesh to exclude from the highlight layer
  89893. */
  89894. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  89895. if (!this._excludedMeshes) {
  89896. return;
  89897. }
  89898. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  89899. if (!meshExcluded) {
  89900. this._excludedMeshes[mesh.uniqueId] = {
  89901. mesh: mesh,
  89902. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  89903. mesh.getEngine().setStencilBuffer(false);
  89904. }),
  89905. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  89906. mesh.getEngine().setStencilBuffer(true);
  89907. }),
  89908. };
  89909. }
  89910. };
  89911. /**
  89912. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  89913. * @param mesh The mesh to highlight
  89914. */
  89915. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  89916. if (!this._excludedMeshes) {
  89917. return;
  89918. }
  89919. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  89920. if (meshExcluded) {
  89921. if (meshExcluded.beforeRender) {
  89922. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  89923. }
  89924. if (meshExcluded.afterRender) {
  89925. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  89926. }
  89927. }
  89928. this._excludedMeshes[mesh.uniqueId] = null;
  89929. };
  89930. /**
  89931. * Determine if a given mesh will be highlighted by the current HighlightLayer
  89932. * @param mesh mesh to test
  89933. * @returns true if the mesh will be highlighted by the current HighlightLayer
  89934. */
  89935. HighlightLayer.prototype.hasMesh = function (mesh) {
  89936. if (!this._meshes) {
  89937. return false;
  89938. }
  89939. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  89940. };
  89941. /**
  89942. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  89943. * @param mesh The mesh to highlight
  89944. * @param color The color of the highlight
  89945. * @param glowEmissiveOnly Extract the glow from the emissive texture
  89946. */
  89947. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  89948. var _this = this;
  89949. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  89950. if (!this._meshes) {
  89951. return;
  89952. }
  89953. var meshHighlight = this._meshes[mesh.uniqueId];
  89954. if (meshHighlight) {
  89955. meshHighlight.color = color;
  89956. }
  89957. else {
  89958. this._meshes[mesh.uniqueId] = {
  89959. mesh: mesh,
  89960. color: color,
  89961. // Lambda required for capture due to Observable this context
  89962. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  89963. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  89964. _this._defaultStencilReference(mesh);
  89965. }
  89966. else {
  89967. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  89968. }
  89969. }),
  89970. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  89971. glowEmissiveOnly: glowEmissiveOnly
  89972. };
  89973. }
  89974. this._shouldRender = true;
  89975. };
  89976. /**
  89977. * Remove a mesh from the highlight layer in order to make it stop glowing.
  89978. * @param mesh The mesh to highlight
  89979. */
  89980. HighlightLayer.prototype.removeMesh = function (mesh) {
  89981. if (!this._meshes) {
  89982. return;
  89983. }
  89984. var meshHighlight = this._meshes[mesh.uniqueId];
  89985. if (meshHighlight) {
  89986. if (meshHighlight.observerHighlight) {
  89987. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  89988. }
  89989. if (meshHighlight.observerDefault) {
  89990. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  89991. }
  89992. delete this._meshes[mesh.uniqueId];
  89993. }
  89994. this._shouldRender = false;
  89995. for (var meshHighlightToCheck in this._meshes) {
  89996. if (this._meshes[meshHighlightToCheck]) {
  89997. this._shouldRender = true;
  89998. break;
  89999. }
  90000. }
  90001. };
  90002. /**
  90003. * Force the stencil to the normal expected value for none glowing parts
  90004. */
  90005. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  90006. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  90007. };
  90008. /**
  90009. * Free any resources and references associated to a mesh.
  90010. * Internal use
  90011. * @param mesh The mesh to free.
  90012. */
  90013. HighlightLayer.prototype._disposeMesh = function (mesh) {
  90014. this.removeMesh(mesh);
  90015. this.removeExcludedMesh(mesh);
  90016. };
  90017. /**
  90018. * Dispose the highlight layer and free resources.
  90019. */
  90020. HighlightLayer.prototype.dispose = function () {
  90021. if (this._meshes) {
  90022. // Clean mesh references
  90023. for (var id in this._meshes) {
  90024. var meshHighlight = this._meshes[id];
  90025. if (meshHighlight && meshHighlight.mesh) {
  90026. if (meshHighlight.observerHighlight) {
  90027. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  90028. }
  90029. if (meshHighlight.observerDefault) {
  90030. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  90031. }
  90032. }
  90033. }
  90034. this._meshes = null;
  90035. }
  90036. if (this._excludedMeshes) {
  90037. for (var id in this._excludedMeshes) {
  90038. var meshHighlight = this._excludedMeshes[id];
  90039. if (meshHighlight) {
  90040. if (meshHighlight.beforeRender) {
  90041. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  90042. }
  90043. if (meshHighlight.afterRender) {
  90044. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  90045. }
  90046. }
  90047. }
  90048. this._excludedMeshes = null;
  90049. }
  90050. _super.prototype.dispose.call(this);
  90051. };
  90052. /**
  90053. * Gets the class name of the effect layer
  90054. * @returns the string with the class name of the effect layer
  90055. */
  90056. HighlightLayer.prototype.getClassName = function () {
  90057. return "HighlightLayer";
  90058. };
  90059. /**
  90060. * Serializes this Highlight layer
  90061. * @returns a serialized Highlight layer object
  90062. */
  90063. HighlightLayer.prototype.serialize = function () {
  90064. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90065. serializationObject.customType = "BABYLON.HighlightLayer";
  90066. // Highlighted meshes
  90067. serializationObject.meshes = [];
  90068. if (this._meshes) {
  90069. for (var m in this._meshes) {
  90070. var mesh = this._meshes[m];
  90071. if (mesh) {
  90072. serializationObject.meshes.push({
  90073. glowEmissiveOnly: mesh.glowEmissiveOnly,
  90074. color: mesh.color.asArray(),
  90075. meshId: mesh.mesh.id
  90076. });
  90077. }
  90078. }
  90079. }
  90080. // Excluded meshes
  90081. serializationObject.excludedMeshes = [];
  90082. if (this._excludedMeshes) {
  90083. for (var e in this._excludedMeshes) {
  90084. var excludedMesh = this._excludedMeshes[e];
  90085. if (excludedMesh) {
  90086. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  90087. }
  90088. }
  90089. }
  90090. return serializationObject;
  90091. };
  90092. /**
  90093. * Creates a Highlight layer from parsed Highlight layer data
  90094. * @param parsedHightlightLayer defines the Highlight layer data
  90095. * @param scene defines the current scene
  90096. * @param rootUrl defines the root URL containing the Highlight layer information
  90097. * @returns a parsed Highlight layer
  90098. */
  90099. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  90100. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  90101. var index;
  90102. // Excluded meshes
  90103. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  90104. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  90105. if (mesh) {
  90106. hl.addExcludedMesh(mesh);
  90107. }
  90108. }
  90109. // Included meshes
  90110. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  90111. var highlightedMesh = parsedHightlightLayer.meshes[index];
  90112. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  90113. if (mesh) {
  90114. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  90115. }
  90116. }
  90117. return hl;
  90118. };
  90119. /**
  90120. * Effect Name of the highlight layer.
  90121. */
  90122. HighlightLayer.EffectName = "HighlightLayer";
  90123. /**
  90124. * The neutral color used during the preparation of the glow effect.
  90125. * This is black by default as the blend operation is a blend operation.
  90126. */
  90127. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  90128. /**
  90129. * Stencil value used for glowing meshes.
  90130. */
  90131. HighlightLayer.GlowingMeshStencilReference = 0x02;
  90132. /**
  90133. * Stencil value used for the other meshes in the scene.
  90134. */
  90135. HighlightLayer.NormalMeshStencilReference = 0x01;
  90136. __decorate([
  90137. BABYLON.serialize()
  90138. ], HighlightLayer.prototype, "innerGlow", void 0);
  90139. __decorate([
  90140. BABYLON.serialize()
  90141. ], HighlightLayer.prototype, "outerGlow", void 0);
  90142. __decorate([
  90143. BABYLON.serialize()
  90144. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  90145. __decorate([
  90146. BABYLON.serialize()
  90147. ], HighlightLayer.prototype, "blurVerticalSize", null);
  90148. __decorate([
  90149. BABYLON.serialize("options")
  90150. ], HighlightLayer.prototype, "_options", void 0);
  90151. return HighlightLayer;
  90152. }(BABYLON.EffectLayer));
  90153. BABYLON.HighlightLayer = HighlightLayer;
  90154. })(BABYLON || (BABYLON = {}));
  90155. //# sourceMappingURL=babylon.highlightLayer.js.map
  90156. "use strict";
  90157. var BABYLON;
  90158. (function (BABYLON) {
  90159. /**
  90160. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  90161. *
  90162. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90163. * glowy meshes to your scene.
  90164. *
  90165. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  90166. */
  90167. var GlowLayer = /** @class */ (function (_super) {
  90168. __extends(GlowLayer, _super);
  90169. /**
  90170. * Instantiates a new glow Layer and references it to the scene.
  90171. * @param name The name of the layer
  90172. * @param scene The scene to use the layer in
  90173. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  90174. */
  90175. function GlowLayer(name, scene, options) {
  90176. var _this = _super.call(this, name, scene) || this;
  90177. _this._intensity = 1.0;
  90178. _this._includedOnlyMeshes = [];
  90179. _this._excludedMeshes = [];
  90180. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  90181. // Adapt options
  90182. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  90183. // Initialize the layer
  90184. _this._init({
  90185. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  90186. camera: _this._options.camera,
  90187. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90188. mainTextureRatio: _this._options.mainTextureRatio
  90189. });
  90190. return _this;
  90191. }
  90192. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  90193. /**
  90194. * Gets the kernel size of the blur.
  90195. */
  90196. get: function () {
  90197. return this._horizontalBlurPostprocess1.kernel;
  90198. },
  90199. /**
  90200. * Sets the kernel size of the blur.
  90201. */
  90202. set: function (value) {
  90203. this._horizontalBlurPostprocess1.kernel = value;
  90204. this._verticalBlurPostprocess1.kernel = value;
  90205. this._horizontalBlurPostprocess2.kernel = value;
  90206. this._verticalBlurPostprocess2.kernel = value;
  90207. },
  90208. enumerable: true,
  90209. configurable: true
  90210. });
  90211. Object.defineProperty(GlowLayer.prototype, "intensity", {
  90212. /**
  90213. * Gets the glow intensity.
  90214. */
  90215. get: function () {
  90216. return this._intensity;
  90217. },
  90218. /**
  90219. * Sets the glow intensity.
  90220. */
  90221. set: function (value) {
  90222. this._intensity = value;
  90223. },
  90224. enumerable: true,
  90225. configurable: true
  90226. });
  90227. /**
  90228. * Get the effect name of the layer.
  90229. * @return The effect name
  90230. */
  90231. GlowLayer.prototype.getEffectName = function () {
  90232. return GlowLayer.EffectName;
  90233. };
  90234. /**
  90235. * Create the merge effect. This is the shader use to blit the information back
  90236. * to the main canvas at the end of the scene rendering.
  90237. */
  90238. GlowLayer.prototype._createMergeEffect = function () {
  90239. // Effect
  90240. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  90241. };
  90242. /**
  90243. * Creates the render target textures and post processes used in the glow layer.
  90244. */
  90245. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  90246. var _this = this;
  90247. var blurTextureWidth = this._mainTextureDesiredSize.width;
  90248. var blurTextureHeight = this._mainTextureDesiredSize.height;
  90249. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90250. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90251. var textureType = 0;
  90252. if (this._engine.getCaps().textureHalfFloatRender) {
  90253. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90254. }
  90255. else {
  90256. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90257. }
  90258. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  90259. width: blurTextureWidth,
  90260. height: blurTextureHeight
  90261. }, this._scene, false, true, textureType);
  90262. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90263. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90264. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90265. this._blurTexture1.renderParticles = false;
  90266. this._blurTexture1.ignoreCameraViewport = true;
  90267. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  90268. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  90269. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  90270. width: blurTextureWidth2,
  90271. height: blurTextureHeight2
  90272. }, this._scene, false, true, textureType);
  90273. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90274. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90275. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90276. this._blurTexture2.renderParticles = false;
  90277. this._blurTexture2.ignoreCameraViewport = true;
  90278. this._textures = [this._blurTexture1, this._blurTexture2];
  90279. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90280. width: blurTextureWidth,
  90281. height: blurTextureHeight
  90282. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90283. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  90284. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  90285. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  90286. effect.setTexture("textureSampler", _this._mainTexture);
  90287. });
  90288. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90289. width: blurTextureWidth,
  90290. height: blurTextureHeight
  90291. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90292. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  90293. width: blurTextureWidth2,
  90294. height: blurTextureHeight2
  90295. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90296. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  90297. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  90298. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  90299. effect.setTexture("textureSampler", _this._blurTexture1);
  90300. });
  90301. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  90302. width: blurTextureWidth2,
  90303. height: blurTextureHeight2
  90304. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  90305. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  90306. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  90307. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  90308. this._mainTexture.samples = this._options.mainTextureSamples;
  90309. this._mainTexture.onAfterUnbindObservable.add(function () {
  90310. var internalTexture = _this._blurTexture1.getInternalTexture();
  90311. if (internalTexture) {
  90312. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  90313. internalTexture = _this._blurTexture2.getInternalTexture();
  90314. if (internalTexture) {
  90315. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  90316. }
  90317. }
  90318. });
  90319. // Prevent autoClear.
  90320. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  90321. };
  90322. /**
  90323. * Checks for the readiness of the element composing the layer.
  90324. * @param subMesh the mesh to check for
  90325. * @param useInstances specify wether or not to use instances to render the mesh
  90326. * @param emissiveTexture the associated emissive texture used to generate the glow
  90327. * @return true if ready otherwise, false
  90328. */
  90329. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  90330. var material = subMesh.getMaterial();
  90331. var mesh = subMesh.getRenderingMesh();
  90332. if (!material || !mesh) {
  90333. return false;
  90334. }
  90335. var emissiveTexture = material.emissiveTexture;
  90336. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  90337. };
  90338. /**
  90339. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  90340. */
  90341. GlowLayer.prototype.needStencil = function () {
  90342. return false;
  90343. };
  90344. /**
  90345. * Implementation specific of rendering the generating effect on the main canvas.
  90346. * @param effect The effect used to render through
  90347. */
  90348. GlowLayer.prototype._internalRender = function (effect) {
  90349. // Texture
  90350. effect.setTexture("textureSampler", this._blurTexture1);
  90351. effect.setTexture("textureSampler2", this._blurTexture2);
  90352. effect.setFloat("offset", this._intensity);
  90353. // Cache
  90354. var engine = this._engine;
  90355. var previousStencilBuffer = engine.getStencilBuffer();
  90356. // Draw order
  90357. engine.setStencilBuffer(false);
  90358. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  90359. // Draw order
  90360. engine.setStencilBuffer(previousStencilBuffer);
  90361. };
  90362. /**
  90363. * Sets the required values for both the emissive texture and and the main color.
  90364. */
  90365. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  90366. var textureLevel = 1.0;
  90367. if (this.customEmissiveTextureSelector) {
  90368. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  90369. }
  90370. else {
  90371. if (material) {
  90372. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  90373. if (this._emissiveTextureAndColor.texture) {
  90374. textureLevel = this._emissiveTextureAndColor.texture.level;
  90375. }
  90376. }
  90377. else {
  90378. this._emissiveTextureAndColor.texture = null;
  90379. }
  90380. }
  90381. if (this.customEmissiveColorSelector) {
  90382. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  90383. }
  90384. else {
  90385. if (material.emissiveColor) {
  90386. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  90387. }
  90388. else {
  90389. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  90390. }
  90391. }
  90392. };
  90393. /**
  90394. * Returns true if the mesh should render, otherwise false.
  90395. * @param mesh The mesh to render
  90396. * @returns true if it should render otherwise false
  90397. */
  90398. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  90399. return this.hasMesh(mesh);
  90400. };
  90401. /**
  90402. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  90403. * @param mesh The mesh to exclude from the glow layer
  90404. */
  90405. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  90406. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  90407. this._excludedMeshes.push(mesh.uniqueId);
  90408. }
  90409. };
  90410. /**
  90411. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  90412. * @param mesh The mesh to remove
  90413. */
  90414. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  90415. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  90416. if (index !== -1) {
  90417. this._excludedMeshes.splice(index, 1);
  90418. }
  90419. };
  90420. /**
  90421. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  90422. * @param mesh The mesh to include in the glow layer
  90423. */
  90424. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  90425. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  90426. this._includedOnlyMeshes.push(mesh.uniqueId);
  90427. }
  90428. };
  90429. /**
  90430. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  90431. * @param mesh The mesh to remove
  90432. */
  90433. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  90434. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  90435. if (index !== -1) {
  90436. this._includedOnlyMeshes.splice(index, 1);
  90437. }
  90438. };
  90439. /**
  90440. * Determine if a given mesh will be used in the glow layer
  90441. * @param mesh The mesh to test
  90442. * @returns true if the mesh will be highlighted by the current glow layer
  90443. */
  90444. GlowLayer.prototype.hasMesh = function (mesh) {
  90445. // Included Mesh
  90446. if (this._includedOnlyMeshes.length) {
  90447. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  90448. }
  90449. ;
  90450. // Excluded Mesh
  90451. if (this._excludedMeshes.length) {
  90452. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  90453. }
  90454. ;
  90455. return true;
  90456. };
  90457. /**
  90458. * Free any resources and references associated to a mesh.
  90459. * Internal use
  90460. * @param mesh The mesh to free.
  90461. */
  90462. GlowLayer.prototype._disposeMesh = function (mesh) {
  90463. this.removeIncludedOnlyMesh(mesh);
  90464. this.removeExcludedMesh(mesh);
  90465. };
  90466. /**
  90467. * Gets the class name of the effect layer
  90468. * @returns the string with the class name of the effect layer
  90469. */
  90470. GlowLayer.prototype.getClassName = function () {
  90471. return "GlowLayer";
  90472. };
  90473. /**
  90474. * Serializes this glow layer
  90475. * @returns a serialized glow layer object
  90476. */
  90477. GlowLayer.prototype.serialize = function () {
  90478. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90479. serializationObject.customType = "BABYLON.GlowLayer";
  90480. var index;
  90481. // Included meshes
  90482. serializationObject.includedMeshes = [];
  90483. if (this._includedOnlyMeshes.length) {
  90484. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  90485. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  90486. if (mesh) {
  90487. serializationObject.includedMeshes.push(mesh.id);
  90488. }
  90489. }
  90490. }
  90491. // Excluded meshes
  90492. serializationObject.excludedMeshes = [];
  90493. if (this._excludedMeshes.length) {
  90494. for (index = 0; index < this._excludedMeshes.length; index++) {
  90495. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  90496. if (mesh) {
  90497. serializationObject.excludedMeshes.push(mesh.id);
  90498. }
  90499. }
  90500. }
  90501. return serializationObject;
  90502. };
  90503. /**
  90504. * Creates a Glow Layer from parsed glow layer data
  90505. * @param parsedGlowLayer defines glow layer data
  90506. * @param scene defines the current scene
  90507. * @param rootUrl defines the root URL containing the glow layer information
  90508. * @returns a parsed Glow Layer
  90509. */
  90510. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  90511. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  90512. var index;
  90513. // Excluded meshes
  90514. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  90515. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  90516. if (mesh) {
  90517. gl.addExcludedMesh(mesh);
  90518. }
  90519. }
  90520. // Included meshes
  90521. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  90522. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  90523. if (mesh) {
  90524. gl.addIncludedOnlyMesh(mesh);
  90525. }
  90526. }
  90527. return gl;
  90528. };
  90529. /**
  90530. * Effect Name of the layer.
  90531. */
  90532. GlowLayer.EffectName = "GlowLayer";
  90533. /**
  90534. * The default blur kernel size used for the glow.
  90535. */
  90536. GlowLayer.DefaultBlurKernelSize = 32;
  90537. /**
  90538. * The default texture size ratio used for the glow.
  90539. */
  90540. GlowLayer.DefaultTextureRatio = 0.5;
  90541. __decorate([
  90542. BABYLON.serialize()
  90543. ], GlowLayer.prototype, "blurKernelSize", null);
  90544. __decorate([
  90545. BABYLON.serialize()
  90546. ], GlowLayer.prototype, "intensity", null);
  90547. __decorate([
  90548. BABYLON.serialize("options")
  90549. ], GlowLayer.prototype, "_options", void 0);
  90550. return GlowLayer;
  90551. }(BABYLON.EffectLayer));
  90552. BABYLON.GlowLayer = GlowLayer;
  90553. })(BABYLON || (BABYLON = {}));
  90554. //# sourceMappingURL=babylon.glowLayer.js.map
  90555. "use strict";
  90556. var BABYLON;
  90557. (function (BABYLON) {
  90558. /**
  90559. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  90560. */
  90561. var AssetTaskState;
  90562. (function (AssetTaskState) {
  90563. /**
  90564. * Initialization
  90565. */
  90566. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  90567. /**
  90568. * Running
  90569. */
  90570. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  90571. /**
  90572. * Done
  90573. */
  90574. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  90575. /**
  90576. * Error
  90577. */
  90578. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  90579. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  90580. /**
  90581. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  90582. */
  90583. var AbstractAssetTask = /** @class */ (function () {
  90584. /**
  90585. * Creates a new {BABYLON.AssetsManager}
  90586. * @param name defines the name of the task
  90587. */
  90588. function AbstractAssetTask(
  90589. /**
  90590. * Task name
  90591. */ name) {
  90592. this.name = name;
  90593. this._isCompleted = false;
  90594. this._taskState = AssetTaskState.INIT;
  90595. }
  90596. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  90597. /**
  90598. * Get if the task is completed
  90599. */
  90600. get: function () {
  90601. return this._isCompleted;
  90602. },
  90603. enumerable: true,
  90604. configurable: true
  90605. });
  90606. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  90607. /**
  90608. * Gets the current state of the task
  90609. */
  90610. get: function () {
  90611. return this._taskState;
  90612. },
  90613. enumerable: true,
  90614. configurable: true
  90615. });
  90616. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  90617. /**
  90618. * Gets the current error object (if task is in error)
  90619. */
  90620. get: function () {
  90621. return this._errorObject;
  90622. },
  90623. enumerable: true,
  90624. configurable: true
  90625. });
  90626. /**
  90627. * Internal only
  90628. * @ignore
  90629. */
  90630. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  90631. if (this._errorObject) {
  90632. return;
  90633. }
  90634. this._errorObject = {
  90635. message: message,
  90636. exception: exception
  90637. };
  90638. };
  90639. /**
  90640. * Execute the current task
  90641. * @param scene defines the scene where you want your assets to be loaded
  90642. * @param onSuccess is a callback called when the task is successfully executed
  90643. * @param onError is a callback called if an error occurs
  90644. */
  90645. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  90646. var _this = this;
  90647. this._taskState = AssetTaskState.RUNNING;
  90648. this.runTask(scene, function () {
  90649. _this.onDoneCallback(onSuccess, onError);
  90650. }, function (msg, exception) {
  90651. _this.onErrorCallback(onError, msg, exception);
  90652. });
  90653. };
  90654. /**
  90655. * Execute the current task
  90656. * @param scene defines the scene where you want your assets to be loaded
  90657. * @param onSuccess is a callback called when the task is successfully executed
  90658. * @param onError is a callback called if an error occurs
  90659. */
  90660. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90661. throw new Error("runTask is not implemented");
  90662. };
  90663. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  90664. this._taskState = AssetTaskState.ERROR;
  90665. this._errorObject = {
  90666. message: message,
  90667. exception: exception
  90668. };
  90669. if (this.onError) {
  90670. this.onError(this, message, exception);
  90671. }
  90672. onError();
  90673. };
  90674. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  90675. try {
  90676. this._taskState = AssetTaskState.DONE;
  90677. this._isCompleted = true;
  90678. if (this.onSuccess) {
  90679. this.onSuccess(this);
  90680. }
  90681. onSuccess();
  90682. }
  90683. catch (e) {
  90684. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  90685. }
  90686. };
  90687. return AbstractAssetTask;
  90688. }());
  90689. BABYLON.AbstractAssetTask = AbstractAssetTask;
  90690. /**
  90691. * Class used to share progress information about assets loading
  90692. */
  90693. var AssetsProgressEvent = /** @class */ (function () {
  90694. /**
  90695. * Creates a {BABYLON.AssetsProgressEvent}
  90696. * @param remainingCount defines the number of remaining tasks to process
  90697. * @param totalCount defines the total number of tasks
  90698. * @param task defines the task that was just processed
  90699. */
  90700. function AssetsProgressEvent(remainingCount, totalCount, task) {
  90701. this.remainingCount = remainingCount;
  90702. this.totalCount = totalCount;
  90703. this.task = task;
  90704. }
  90705. return AssetsProgressEvent;
  90706. }());
  90707. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  90708. /**
  90709. * Define a task used by {BABYLON.AssetsManager} to load meshes
  90710. */
  90711. var MeshAssetTask = /** @class */ (function (_super) {
  90712. __extends(MeshAssetTask, _super);
  90713. /**
  90714. * Creates a new {BABYLON.MeshAssetTask}
  90715. * @param name defines the name of the task
  90716. * @param meshesNames defines the list of mesh's names you want to load
  90717. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  90718. * @param sceneFilename defines the filename of the scene to load from
  90719. */
  90720. function MeshAssetTask(
  90721. /**
  90722. * Defines the name of the task
  90723. */
  90724. name,
  90725. /**
  90726. * Defines the list of mesh's names you want to load
  90727. */
  90728. meshesNames,
  90729. /**
  90730. * Defines the root url to use as a base to load your meshes and associated resources
  90731. */
  90732. rootUrl,
  90733. /**
  90734. * Defines the filename of the scene to load from
  90735. */
  90736. sceneFilename) {
  90737. var _this = _super.call(this, name) || this;
  90738. _this.name = name;
  90739. _this.meshesNames = meshesNames;
  90740. _this.rootUrl = rootUrl;
  90741. _this.sceneFilename = sceneFilename;
  90742. return _this;
  90743. }
  90744. /**
  90745. * Execute the current task
  90746. * @param scene defines the scene where you want your assets to be loaded
  90747. * @param onSuccess is a callback called when the task is successfully executed
  90748. * @param onError is a callback called if an error occurs
  90749. */
  90750. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90751. var _this = this;
  90752. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  90753. _this.loadedMeshes = meshes;
  90754. _this.loadedParticleSystems = particleSystems;
  90755. _this.loadedSkeletons = skeletons;
  90756. onSuccess();
  90757. }, null, function (scene, message, exception) {
  90758. onError(message, exception);
  90759. });
  90760. };
  90761. return MeshAssetTask;
  90762. }(AbstractAssetTask));
  90763. BABYLON.MeshAssetTask = MeshAssetTask;
  90764. /**
  90765. * Define a task used by {BABYLON.AssetsManager} to load text content
  90766. */
  90767. var TextFileAssetTask = /** @class */ (function (_super) {
  90768. __extends(TextFileAssetTask, _super);
  90769. /**
  90770. * Creates a new TextFileAssetTask object
  90771. * @param name defines the name of the task
  90772. * @param url defines the location of the file to load
  90773. */
  90774. function TextFileAssetTask(
  90775. /**
  90776. * Defines the name of the task
  90777. */
  90778. name,
  90779. /**
  90780. * Defines the location of the file to load
  90781. */
  90782. url) {
  90783. var _this = _super.call(this, name) || this;
  90784. _this.name = name;
  90785. _this.url = url;
  90786. return _this;
  90787. }
  90788. /**
  90789. * Execute the current task
  90790. * @param scene defines the scene where you want your assets to be loaded
  90791. * @param onSuccess is a callback called when the task is successfully executed
  90792. * @param onError is a callback called if an error occurs
  90793. */
  90794. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90795. var _this = this;
  90796. scene._loadFile(this.url, function (data) {
  90797. _this.text = data;
  90798. onSuccess();
  90799. }, undefined, false, false, function (request, exception) {
  90800. if (request) {
  90801. onError(request.status + " " + request.statusText, exception);
  90802. }
  90803. });
  90804. };
  90805. return TextFileAssetTask;
  90806. }(AbstractAssetTask));
  90807. BABYLON.TextFileAssetTask = TextFileAssetTask;
  90808. /**
  90809. * Define a task used by {BABYLON.AssetsManager} to load binary data
  90810. */
  90811. var BinaryFileAssetTask = /** @class */ (function (_super) {
  90812. __extends(BinaryFileAssetTask, _super);
  90813. /**
  90814. * Creates a new BinaryFileAssetTask object
  90815. * @param name defines the name of the new task
  90816. * @param url defines the location of the file to load
  90817. */
  90818. function BinaryFileAssetTask(
  90819. /**
  90820. * Defines the name of the task
  90821. */
  90822. name,
  90823. /**
  90824. * Defines the location of the file to load
  90825. */
  90826. url) {
  90827. var _this = _super.call(this, name) || this;
  90828. _this.name = name;
  90829. _this.url = url;
  90830. return _this;
  90831. }
  90832. /**
  90833. * Execute the current task
  90834. * @param scene defines the scene where you want your assets to be loaded
  90835. * @param onSuccess is a callback called when the task is successfully executed
  90836. * @param onError is a callback called if an error occurs
  90837. */
  90838. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90839. var _this = this;
  90840. scene._loadFile(this.url, function (data) {
  90841. _this.data = data;
  90842. onSuccess();
  90843. }, undefined, true, true, function (request, exception) {
  90844. if (request) {
  90845. onError(request.status + " " + request.statusText, exception);
  90846. }
  90847. });
  90848. };
  90849. return BinaryFileAssetTask;
  90850. }(AbstractAssetTask));
  90851. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  90852. /**
  90853. * Define a task used by {BABYLON.AssetsManager} to load images
  90854. */
  90855. var ImageAssetTask = /** @class */ (function (_super) {
  90856. __extends(ImageAssetTask, _super);
  90857. /**
  90858. * Creates a new ImageAssetTask
  90859. * @param name defines the name of the task
  90860. * @param url defines the location of the image to load
  90861. */
  90862. function ImageAssetTask(
  90863. /**
  90864. * Defines the name of the task
  90865. */
  90866. name,
  90867. /**
  90868. * Defines the location of the image to load
  90869. */
  90870. url) {
  90871. var _this = _super.call(this, name) || this;
  90872. _this.name = name;
  90873. _this.url = url;
  90874. return _this;
  90875. }
  90876. /**
  90877. * Execute the current task
  90878. * @param scene defines the scene where you want your assets to be loaded
  90879. * @param onSuccess is a callback called when the task is successfully executed
  90880. * @param onError is a callback called if an error occurs
  90881. */
  90882. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90883. var _this = this;
  90884. var img = new Image();
  90885. BABYLON.Tools.SetCorsBehavior(this.url, img);
  90886. img.onload = function () {
  90887. _this.image = img;
  90888. onSuccess();
  90889. };
  90890. img.onerror = function (err) {
  90891. onError("Error loading image", err);
  90892. };
  90893. img.src = this.url;
  90894. };
  90895. return ImageAssetTask;
  90896. }(AbstractAssetTask));
  90897. BABYLON.ImageAssetTask = ImageAssetTask;
  90898. /**
  90899. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  90900. */
  90901. var TextureAssetTask = /** @class */ (function (_super) {
  90902. __extends(TextureAssetTask, _super);
  90903. /**
  90904. * Creates a new TextureAssetTask object
  90905. * @param name defines the name of the task
  90906. * @param url defines the location of the file to load
  90907. * @param noMipmap defines if mipmap should not be generated (default is false)
  90908. * @param invertY defines if texture must be inverted on Y axis (default is false)
  90909. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  90910. */
  90911. function TextureAssetTask(
  90912. /**
  90913. * Defines the name of the task
  90914. */
  90915. name,
  90916. /**
  90917. * Defines the location of the file to load
  90918. */
  90919. url,
  90920. /**
  90921. * Defines if mipmap should not be generated (default is false)
  90922. */
  90923. noMipmap,
  90924. /**
  90925. * Defines if texture must be inverted on Y axis (default is false)
  90926. */
  90927. invertY,
  90928. /**
  90929. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  90930. */
  90931. samplingMode) {
  90932. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90933. var _this = _super.call(this, name) || this;
  90934. _this.name = name;
  90935. _this.url = url;
  90936. _this.noMipmap = noMipmap;
  90937. _this.invertY = invertY;
  90938. _this.samplingMode = samplingMode;
  90939. return _this;
  90940. }
  90941. /**
  90942. * Execute the current task
  90943. * @param scene defines the scene where you want your assets to be loaded
  90944. * @param onSuccess is a callback called when the task is successfully executed
  90945. * @param onError is a callback called if an error occurs
  90946. */
  90947. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  90948. var onload = function () {
  90949. onSuccess();
  90950. };
  90951. var onerror = function (message, exception) {
  90952. onError(message, exception);
  90953. };
  90954. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  90955. };
  90956. return TextureAssetTask;
  90957. }(AbstractAssetTask));
  90958. BABYLON.TextureAssetTask = TextureAssetTask;
  90959. /**
  90960. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  90961. */
  90962. var CubeTextureAssetTask = /** @class */ (function (_super) {
  90963. __extends(CubeTextureAssetTask, _super);
  90964. /**
  90965. * Creates a new CubeTextureAssetTask
  90966. * @param name defines the name of the task
  90967. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  90968. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  90969. * @param noMipmap defines if mipmaps should not be generated (default is false)
  90970. * @param files defines the explicit list of files (undefined by default)
  90971. */
  90972. function CubeTextureAssetTask(
  90973. /**
  90974. * Defines the name of the task
  90975. */
  90976. name,
  90977. /**
  90978. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  90979. */
  90980. url,
  90981. /**
  90982. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  90983. */
  90984. extensions,
  90985. /**
  90986. * Defines if mipmaps should not be generated (default is false)
  90987. */
  90988. noMipmap,
  90989. /**
  90990. * Defines the explicit list of files (undefined by default)
  90991. */
  90992. files) {
  90993. var _this = _super.call(this, name) || this;
  90994. _this.name = name;
  90995. _this.url = url;
  90996. _this.extensions = extensions;
  90997. _this.noMipmap = noMipmap;
  90998. _this.files = files;
  90999. return _this;
  91000. }
  91001. /**
  91002. * Execute the current task
  91003. * @param scene defines the scene where you want your assets to be loaded
  91004. * @param onSuccess is a callback called when the task is successfully executed
  91005. * @param onError is a callback called if an error occurs
  91006. */
  91007. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91008. var onload = function () {
  91009. onSuccess();
  91010. };
  91011. var onerror = function (message, exception) {
  91012. onError(message, exception);
  91013. };
  91014. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  91015. };
  91016. return CubeTextureAssetTask;
  91017. }(AbstractAssetTask));
  91018. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  91019. /**
  91020. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  91021. */
  91022. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  91023. __extends(HDRCubeTextureAssetTask, _super);
  91024. /**
  91025. * Creates a new HDRCubeTextureAssetTask object
  91026. * @param name defines the name of the task
  91027. * @param url defines the location of the file to load
  91028. * @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.
  91029. * @param noMipmap defines if mipmaps should not be generated (default is false)
  91030. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91031. * @param useInGammaSpace 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)
  91032. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91033. */
  91034. function HDRCubeTextureAssetTask(
  91035. /**
  91036. * Defines the name of the task
  91037. */
  91038. name,
  91039. /**
  91040. * Defines the location of the file to load
  91041. */
  91042. url,
  91043. /**
  91044. * 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.
  91045. */
  91046. size,
  91047. /**
  91048. * Defines if mipmaps should not be generated (default is false)
  91049. */
  91050. noMipmap,
  91051. /**
  91052. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  91053. */
  91054. generateHarmonics,
  91055. /**
  91056. * 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)
  91057. */
  91058. useInGammaSpace,
  91059. /**
  91060. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  91061. */
  91062. usePMREMGenerator) {
  91063. if (noMipmap === void 0) { noMipmap = false; }
  91064. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91065. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91066. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91067. var _this = _super.call(this, name) || this;
  91068. _this.name = name;
  91069. _this.url = url;
  91070. _this.size = size;
  91071. _this.noMipmap = noMipmap;
  91072. _this.generateHarmonics = generateHarmonics;
  91073. _this.useInGammaSpace = useInGammaSpace;
  91074. _this.usePMREMGenerator = usePMREMGenerator;
  91075. return _this;
  91076. }
  91077. /**
  91078. * Execute the current task
  91079. * @param scene defines the scene where you want your assets to be loaded
  91080. * @param onSuccess is a callback called when the task is successfully executed
  91081. * @param onError is a callback called if an error occurs
  91082. */
  91083. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91084. var onload = function () {
  91085. onSuccess();
  91086. };
  91087. var onerror = function (message, exception) {
  91088. onError(message, exception);
  91089. };
  91090. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  91091. };
  91092. return HDRCubeTextureAssetTask;
  91093. }(AbstractAssetTask));
  91094. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  91095. /**
  91096. * This class can be used to easily import assets into a scene
  91097. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  91098. */
  91099. var AssetsManager = /** @class */ (function () {
  91100. /**
  91101. * Creates a new AssetsManager
  91102. * @param scene defines the scene to work on
  91103. */
  91104. function AssetsManager(scene) {
  91105. this._isLoading = false;
  91106. this._tasks = new Array();
  91107. this._waitingTasksCount = 0;
  91108. this._totalTasksCount = 0;
  91109. /**
  91110. * Observable called when all tasks are processed
  91111. */
  91112. this.onTaskSuccessObservable = new BABYLON.Observable();
  91113. /**
  91114. * Observable called when a task had an error
  91115. */
  91116. this.onTaskErrorObservable = new BABYLON.Observable();
  91117. /**
  91118. * Observable called when a task is successful
  91119. */
  91120. this.onTasksDoneObservable = new BABYLON.Observable();
  91121. /**
  91122. * Observable called when a task is done (whatever the result is)
  91123. */
  91124. this.onProgressObservable = new BABYLON.Observable();
  91125. /**
  91126. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  91127. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  91128. */
  91129. this.useDefaultLoadingScreen = true;
  91130. this._scene = scene;
  91131. }
  91132. /**
  91133. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  91134. * @param taskName defines the name of the new task
  91135. * @param meshesNames defines the name of meshes to load
  91136. * @param rootUrl defines the root url to use to locate files
  91137. * @param sceneFilename defines the filename of the scene file
  91138. * @returns a new {BABYLON.MeshAssetTask} object
  91139. */
  91140. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  91141. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  91142. this._tasks.push(task);
  91143. return task;
  91144. };
  91145. /**
  91146. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  91147. * @param taskName defines the name of the new task
  91148. * @param url defines the url of the file to load
  91149. * @returns a new {BABYLON.TextFileAssetTask} object
  91150. */
  91151. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  91152. var task = new TextFileAssetTask(taskName, url);
  91153. this._tasks.push(task);
  91154. return task;
  91155. };
  91156. /**
  91157. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  91158. * @param taskName defines the name of the new task
  91159. * @param url defines the url of the file to load
  91160. * @returns a new {BABYLON.BinaryFileAssetTask} object
  91161. */
  91162. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  91163. var task = new BinaryFileAssetTask(taskName, url);
  91164. this._tasks.push(task);
  91165. return task;
  91166. };
  91167. /**
  91168. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  91169. * @param taskName defines the name of the new task
  91170. * @param url defines the url of the file to load
  91171. * @returns a new {BABYLON.ImageAssetTask} object
  91172. */
  91173. AssetsManager.prototype.addImageTask = function (taskName, url) {
  91174. var task = new ImageAssetTask(taskName, url);
  91175. this._tasks.push(task);
  91176. return task;
  91177. };
  91178. /**
  91179. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  91180. * @param taskName defines the name of the new task
  91181. * @param url defines the url of the file to load
  91182. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91183. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  91184. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  91185. * @returns a new {BABYLON.TextureAssetTask} object
  91186. */
  91187. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  91188. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  91189. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  91190. this._tasks.push(task);
  91191. return task;
  91192. };
  91193. /**
  91194. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  91195. * @param taskName defines the name of the new task
  91196. * @param url defines the url of the file to load
  91197. * @param extensions defines the extension to use to load the cube map (can be null)
  91198. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91199. * @param files defines the list of files to load (can be null)
  91200. * @returns a new {BABYLON.CubeTextureAssetTask} object
  91201. */
  91202. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  91203. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  91204. this._tasks.push(task);
  91205. return task;
  91206. };
  91207. /**
  91208. *
  91209. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  91210. * @param taskName defines the name of the new task
  91211. * @param url defines the url of the file to load
  91212. * @param size defines the size you want for the cubemap (can be null)
  91213. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  91214. * @param generateHarmonics defines if you want to automatically generate (true by default)
  91215. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  91216. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  91217. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  91218. */
  91219. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  91220. if (noMipmap === void 0) { noMipmap = false; }
  91221. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91222. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  91223. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  91224. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  91225. this._tasks.push(task);
  91226. return task;
  91227. };
  91228. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  91229. var _this = this;
  91230. this._waitingTasksCount--;
  91231. try {
  91232. if (task.taskState === AssetTaskState.DONE) {
  91233. // Let's remove successfull tasks
  91234. BABYLON.Tools.SetImmediate(function () {
  91235. var index = _this._tasks.indexOf(task);
  91236. if (index > -1) {
  91237. _this._tasks.splice(index, 1);
  91238. }
  91239. });
  91240. }
  91241. if (this.onProgress) {
  91242. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  91243. }
  91244. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  91245. }
  91246. catch (e) {
  91247. BABYLON.Tools.Error("Error running progress callbacks.");
  91248. console.log(e);
  91249. }
  91250. if (this._waitingTasksCount === 0) {
  91251. try {
  91252. if (this.onFinish) {
  91253. this.onFinish(this._tasks);
  91254. }
  91255. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91256. }
  91257. catch (e) {
  91258. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  91259. console.log(e);
  91260. }
  91261. this._isLoading = false;
  91262. this._scene.getEngine().hideLoadingUI();
  91263. }
  91264. };
  91265. AssetsManager.prototype._runTask = function (task) {
  91266. var _this = this;
  91267. var done = function () {
  91268. try {
  91269. if (_this.onTaskSuccess) {
  91270. _this.onTaskSuccess(task);
  91271. }
  91272. _this.onTaskSuccessObservable.notifyObservers(task);
  91273. _this._decreaseWaitingTasksCount(task);
  91274. }
  91275. catch (e) {
  91276. error("Error executing task success callbacks", e);
  91277. }
  91278. };
  91279. var error = function (message, exception) {
  91280. task._setErrorObject(message, exception);
  91281. if (_this.onTaskError) {
  91282. _this.onTaskError(task);
  91283. }
  91284. _this.onTaskErrorObservable.notifyObservers(task);
  91285. _this._decreaseWaitingTasksCount(task);
  91286. };
  91287. task.run(this._scene, done, error);
  91288. };
  91289. /**
  91290. * Reset the {BABYLON.AssetsManager} and remove all tasks
  91291. * @return the current instance of the {BABYLON.AssetsManager}
  91292. */
  91293. AssetsManager.prototype.reset = function () {
  91294. this._isLoading = false;
  91295. this._tasks = new Array();
  91296. return this;
  91297. };
  91298. /**
  91299. * Start the loading process
  91300. * @return the current instance of the {BABYLON.AssetsManager}
  91301. */
  91302. AssetsManager.prototype.load = function () {
  91303. if (this._isLoading) {
  91304. return this;
  91305. }
  91306. this._isLoading = true;
  91307. this._waitingTasksCount = this._tasks.length;
  91308. this._totalTasksCount = this._tasks.length;
  91309. if (this._waitingTasksCount === 0) {
  91310. this._isLoading = false;
  91311. if (this.onFinish) {
  91312. this.onFinish(this._tasks);
  91313. }
  91314. this.onTasksDoneObservable.notifyObservers(this._tasks);
  91315. return this;
  91316. }
  91317. if (this.useDefaultLoadingScreen) {
  91318. this._scene.getEngine().displayLoadingUI();
  91319. }
  91320. for (var index = 0; index < this._tasks.length; index++) {
  91321. var task = this._tasks[index];
  91322. this._runTask(task);
  91323. }
  91324. return this;
  91325. };
  91326. return AssetsManager;
  91327. }());
  91328. BABYLON.AssetsManager = AssetsManager;
  91329. })(BABYLON || (BABYLON = {}));
  91330. //# sourceMappingURL=babylon.assetsManager.js.map
  91331. "use strict";
  91332. var BABYLON;
  91333. (function (BABYLON) {
  91334. var serializedGeometries = [];
  91335. var serializeGeometry = function (geometry, serializationGeometries) {
  91336. if (serializedGeometries[geometry.id]) {
  91337. return;
  91338. }
  91339. if (geometry.doNotSerialize) {
  91340. return;
  91341. }
  91342. if (geometry instanceof BABYLON.BoxGeometry) {
  91343. serializationGeometries.boxes.push(geometry.serialize());
  91344. }
  91345. else if (geometry instanceof BABYLON.SphereGeometry) {
  91346. serializationGeometries.spheres.push(geometry.serialize());
  91347. }
  91348. else if (geometry instanceof BABYLON.CylinderGeometry) {
  91349. serializationGeometries.cylinders.push(geometry.serialize());
  91350. }
  91351. else if (geometry instanceof BABYLON.TorusGeometry) {
  91352. serializationGeometries.toruses.push(geometry.serialize());
  91353. }
  91354. else if (geometry instanceof BABYLON.GroundGeometry) {
  91355. serializationGeometries.grounds.push(geometry.serialize());
  91356. }
  91357. else if (geometry instanceof BABYLON.Plane) {
  91358. serializationGeometries.planes.push(geometry.serialize());
  91359. }
  91360. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  91361. serializationGeometries.torusKnots.push(geometry.serialize());
  91362. }
  91363. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  91364. throw new Error("Unknown primitive type");
  91365. }
  91366. else {
  91367. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  91368. }
  91369. serializedGeometries[geometry.id] = true;
  91370. };
  91371. var serializeMesh = function (mesh, serializationScene) {
  91372. var serializationObject = {};
  91373. // Geometry
  91374. var geometry = mesh._geometry;
  91375. if (geometry) {
  91376. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  91377. // 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
  91378. serializeGeometry(geometry, serializationScene.geometries);
  91379. }
  91380. }
  91381. // Custom
  91382. if (mesh.serialize) {
  91383. mesh.serialize(serializationObject);
  91384. }
  91385. return serializationObject;
  91386. };
  91387. var finalizeSingleMesh = function (mesh, serializationObject) {
  91388. //only works if the mesh is already loaded
  91389. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  91390. //serialize material
  91391. if (mesh.material) {
  91392. if (mesh.material instanceof BABYLON.StandardMaterial) {
  91393. serializationObject.materials = serializationObject.materials || [];
  91394. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  91395. serializationObject.materials.push(mesh.material.serialize());
  91396. }
  91397. }
  91398. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  91399. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  91400. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  91401. serializationObject.multiMaterials.push(mesh.material.serialize());
  91402. }
  91403. }
  91404. }
  91405. //serialize geometry
  91406. var geometry = mesh._geometry;
  91407. if (geometry) {
  91408. if (!serializationObject.geometries) {
  91409. serializationObject.geometries = {};
  91410. serializationObject.geometries.boxes = [];
  91411. serializationObject.geometries.spheres = [];
  91412. serializationObject.geometries.cylinders = [];
  91413. serializationObject.geometries.toruses = [];
  91414. serializationObject.geometries.grounds = [];
  91415. serializationObject.geometries.planes = [];
  91416. serializationObject.geometries.torusKnots = [];
  91417. serializationObject.geometries.vertexData = [];
  91418. }
  91419. serializeGeometry(geometry, serializationObject.geometries);
  91420. }
  91421. // Skeletons
  91422. if (mesh.skeleton) {
  91423. serializationObject.skeletons = serializationObject.skeletons || [];
  91424. serializationObject.skeletons.push(mesh.skeleton.serialize());
  91425. }
  91426. //serialize the actual mesh
  91427. serializationObject.meshes = serializationObject.meshes || [];
  91428. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  91429. }
  91430. };
  91431. var SceneSerializer = /** @class */ (function () {
  91432. function SceneSerializer() {
  91433. }
  91434. SceneSerializer.ClearCache = function () {
  91435. serializedGeometries = [];
  91436. };
  91437. SceneSerializer.Serialize = function (scene) {
  91438. var serializationObject = {};
  91439. SceneSerializer.ClearCache();
  91440. // Scene
  91441. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  91442. serializationObject.autoClear = scene.autoClear;
  91443. serializationObject.clearColor = scene.clearColor.asArray();
  91444. serializationObject.ambientColor = scene.ambientColor.asArray();
  91445. serializationObject.gravity = scene.gravity.asArray();
  91446. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  91447. serializationObject.workerCollisions = scene.workerCollisions;
  91448. // Fog
  91449. if (scene.fogMode && scene.fogMode !== 0) {
  91450. serializationObject.fogMode = scene.fogMode;
  91451. serializationObject.fogColor = scene.fogColor.asArray();
  91452. serializationObject.fogStart = scene.fogStart;
  91453. serializationObject.fogEnd = scene.fogEnd;
  91454. serializationObject.fogDensity = scene.fogDensity;
  91455. }
  91456. //Physics
  91457. if (scene.isPhysicsEnabled()) {
  91458. var physicEngine = scene.getPhysicsEngine();
  91459. if (physicEngine) {
  91460. serializationObject.physicsEnabled = true;
  91461. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  91462. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  91463. }
  91464. }
  91465. // Metadata
  91466. if (scene.metadata) {
  91467. serializationObject.metadata = scene.metadata;
  91468. }
  91469. // Morph targets
  91470. serializationObject.morphTargetManagers = [];
  91471. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  91472. var abstractMesh = _a[_i];
  91473. var manager = abstractMesh.morphTargetManager;
  91474. if (manager) {
  91475. serializationObject.morphTargetManagers.push(manager.serialize());
  91476. }
  91477. }
  91478. // Lights
  91479. serializationObject.lights = [];
  91480. var index;
  91481. var light;
  91482. for (index = 0; index < scene.lights.length; index++) {
  91483. light = scene.lights[index];
  91484. if (!light.doNotSerialize) {
  91485. serializationObject.lights.push(light.serialize());
  91486. }
  91487. }
  91488. // Cameras
  91489. serializationObject.cameras = [];
  91490. for (index = 0; index < scene.cameras.length; index++) {
  91491. var camera = scene.cameras[index];
  91492. if (!camera.doNotSerialize) {
  91493. serializationObject.cameras.push(camera.serialize());
  91494. }
  91495. }
  91496. if (scene.activeCamera) {
  91497. serializationObject.activeCameraID = scene.activeCamera.id;
  91498. }
  91499. // Animations
  91500. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  91501. // Materials
  91502. serializationObject.materials = [];
  91503. serializationObject.multiMaterials = [];
  91504. var material;
  91505. for (index = 0; index < scene.materials.length; index++) {
  91506. material = scene.materials[index];
  91507. if (!material.doNotSerialize) {
  91508. serializationObject.materials.push(material.serialize());
  91509. }
  91510. }
  91511. // MultiMaterials
  91512. serializationObject.multiMaterials = [];
  91513. for (index = 0; index < scene.multiMaterials.length; index++) {
  91514. var multiMaterial = scene.multiMaterials[index];
  91515. serializationObject.multiMaterials.push(multiMaterial.serialize());
  91516. }
  91517. // Environment texture
  91518. if (scene.environmentTexture) {
  91519. serializationObject.environmentTexture = scene.environmentTexture.name;
  91520. }
  91521. // Skeletons
  91522. serializationObject.skeletons = [];
  91523. for (index = 0; index < scene.skeletons.length; index++) {
  91524. var skeleton = scene.skeletons[index];
  91525. if (!skeleton.doNotSerialize) {
  91526. serializationObject.skeletons.push(skeleton.serialize());
  91527. }
  91528. }
  91529. // Transform nodes
  91530. serializationObject.transformNodes = [];
  91531. for (index = 0; index < scene.transformNodes.length; index++) {
  91532. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  91533. }
  91534. // Geometries
  91535. serializationObject.geometries = {};
  91536. serializationObject.geometries.boxes = [];
  91537. serializationObject.geometries.spheres = [];
  91538. serializationObject.geometries.cylinders = [];
  91539. serializationObject.geometries.toruses = [];
  91540. serializationObject.geometries.grounds = [];
  91541. serializationObject.geometries.planes = [];
  91542. serializationObject.geometries.torusKnots = [];
  91543. serializationObject.geometries.vertexData = [];
  91544. serializedGeometries = [];
  91545. var geometries = scene.getGeometries();
  91546. for (index = 0; index < geometries.length; index++) {
  91547. var geometry = geometries[index];
  91548. if (geometry.isReady()) {
  91549. serializeGeometry(geometry, serializationObject.geometries);
  91550. }
  91551. }
  91552. // Meshes
  91553. serializationObject.meshes = [];
  91554. for (index = 0; index < scene.meshes.length; index++) {
  91555. var abstractMesh = scene.meshes[index];
  91556. if (abstractMesh instanceof BABYLON.Mesh) {
  91557. var mesh = abstractMesh;
  91558. if (!mesh.doNotSerialize) {
  91559. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  91560. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  91561. }
  91562. }
  91563. }
  91564. }
  91565. // Particles Systems
  91566. serializationObject.particleSystems = [];
  91567. for (index = 0; index < scene.particleSystems.length; index++) {
  91568. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  91569. }
  91570. // Lens flares
  91571. serializationObject.lensFlareSystems = [];
  91572. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  91573. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  91574. }
  91575. // Shadows
  91576. serializationObject.shadowGenerators = [];
  91577. for (index = 0; index < scene.lights.length; index++) {
  91578. light = scene.lights[index];
  91579. var shadowGenerator = light.getShadowGenerator();
  91580. if (shadowGenerator) {
  91581. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  91582. }
  91583. }
  91584. // Action Manager
  91585. if (scene.actionManager) {
  91586. serializationObject.actions = scene.actionManager.serialize("scene");
  91587. }
  91588. // Audio
  91589. serializationObject.sounds = [];
  91590. for (index = 0; index < scene.soundTracks.length; index++) {
  91591. var soundtrack = scene.soundTracks[index];
  91592. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  91593. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  91594. }
  91595. }
  91596. // Effect layers
  91597. serializationObject.effectLayers = [];
  91598. for (index = 0; index < scene.effectLayers.length; index++) {
  91599. var layer = scene.effectLayers[index];
  91600. if (layer.serialize) {
  91601. serializationObject.effectLayers.push(layer.serialize());
  91602. }
  91603. }
  91604. return serializationObject;
  91605. };
  91606. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  91607. if (withParents === void 0) { withParents = false; }
  91608. if (withChildren === void 0) { withChildren = false; }
  91609. var serializationObject = {};
  91610. SceneSerializer.ClearCache();
  91611. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  91612. if (withParents || withChildren) {
  91613. //deliberate for loop! not for each, appended should be processed as well.
  91614. for (var i = 0; i < toSerialize.length; ++i) {
  91615. if (withChildren) {
  91616. toSerialize[i].getDescendants().forEach(function (node) {
  91617. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  91618. toSerialize.push(node);
  91619. }
  91620. });
  91621. }
  91622. //make sure the array doesn't contain the object already
  91623. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  91624. toSerialize.push(toSerialize[i].parent);
  91625. }
  91626. }
  91627. }
  91628. toSerialize.forEach(function (mesh) {
  91629. finalizeSingleMesh(mesh, serializationObject);
  91630. });
  91631. return serializationObject;
  91632. };
  91633. return SceneSerializer;
  91634. }());
  91635. BABYLON.SceneSerializer = SceneSerializer;
  91636. })(BABYLON || (BABYLON = {}));
  91637. //# sourceMappingURL=babylon.sceneSerializer.js.map
  91638. "use strict";
  91639. var BABYLON;
  91640. (function (BABYLON) {
  91641. var ReflectionProbe = /** @class */ (function () {
  91642. function ReflectionProbe(name, size, scene, generateMipMaps) {
  91643. if (generateMipMaps === void 0) { generateMipMaps = true; }
  91644. var _this = this;
  91645. this.name = name;
  91646. this._viewMatrix = BABYLON.Matrix.Identity();
  91647. this._target = BABYLON.Vector3.Zero();
  91648. this._add = BABYLON.Vector3.Zero();
  91649. this._invertYAxis = false;
  91650. this.position = BABYLON.Vector3.Zero();
  91651. this._scene = scene;
  91652. this._scene.reflectionProbes.push(this);
  91653. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  91654. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  91655. switch (faceIndex) {
  91656. case 0:
  91657. _this._add.copyFromFloats(1, 0, 0);
  91658. break;
  91659. case 1:
  91660. _this._add.copyFromFloats(-1, 0, 0);
  91661. break;
  91662. case 2:
  91663. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  91664. break;
  91665. case 3:
  91666. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  91667. break;
  91668. case 4:
  91669. _this._add.copyFromFloats(0, 0, 1);
  91670. break;
  91671. case 5:
  91672. _this._add.copyFromFloats(0, 0, -1);
  91673. break;
  91674. }
  91675. if (_this._attachedMesh) {
  91676. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  91677. }
  91678. _this.position.addToRef(_this._add, _this._target);
  91679. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  91680. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  91681. scene._forcedViewPosition = _this.position;
  91682. });
  91683. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  91684. scene._forcedViewPosition = null;
  91685. scene.updateTransformMatrix(true);
  91686. });
  91687. if (scene.activeCamera) {
  91688. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  91689. }
  91690. }
  91691. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  91692. get: function () {
  91693. return this._renderTargetTexture.samples;
  91694. },
  91695. set: function (value) {
  91696. this._renderTargetTexture.samples = value;
  91697. },
  91698. enumerable: true,
  91699. configurable: true
  91700. });
  91701. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  91702. get: function () {
  91703. return this._renderTargetTexture.refreshRate;
  91704. },
  91705. set: function (value) {
  91706. this._renderTargetTexture.refreshRate = value;
  91707. },
  91708. enumerable: true,
  91709. configurable: true
  91710. });
  91711. ReflectionProbe.prototype.getScene = function () {
  91712. return this._scene;
  91713. };
  91714. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  91715. get: function () {
  91716. return this._renderTargetTexture;
  91717. },
  91718. enumerable: true,
  91719. configurable: true
  91720. });
  91721. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  91722. get: function () {
  91723. return this._renderTargetTexture.renderList;
  91724. },
  91725. enumerable: true,
  91726. configurable: true
  91727. });
  91728. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  91729. this._attachedMesh = mesh;
  91730. };
  91731. /**
  91732. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  91733. *
  91734. * @param renderingGroupId The rendering group id corresponding to its index
  91735. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  91736. */
  91737. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  91738. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  91739. };
  91740. ReflectionProbe.prototype.dispose = function () {
  91741. var index = this._scene.reflectionProbes.indexOf(this);
  91742. if (index !== -1) {
  91743. // Remove from the scene if found
  91744. this._scene.reflectionProbes.splice(index, 1);
  91745. }
  91746. if (this._renderTargetTexture) {
  91747. this._renderTargetTexture.dispose();
  91748. this._renderTargetTexture = null;
  91749. }
  91750. };
  91751. return ReflectionProbe;
  91752. }());
  91753. BABYLON.ReflectionProbe = ReflectionProbe;
  91754. })(BABYLON || (BABYLON = {}));
  91755. //# sourceMappingURL=babylon.reflectionProbe.js.map
  91756. "use strict";
  91757. var BABYLON;
  91758. (function (BABYLON) {
  91759. var Layer = /** @class */ (function () {
  91760. function Layer(name, imgUrl, scene, isBackground, color) {
  91761. this.name = name;
  91762. this.scale = new BABYLON.Vector2(1, 1);
  91763. this.offset = new BABYLON.Vector2(0, 0);
  91764. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  91765. this.layerMask = 0x0FFFFFFF;
  91766. this._vertexBuffers = {};
  91767. // Events
  91768. /**
  91769. * An event triggered when the layer is disposed.
  91770. */
  91771. this.onDisposeObservable = new BABYLON.Observable();
  91772. /**
  91773. * An event triggered before rendering the scene
  91774. */
  91775. this.onBeforeRenderObservable = new BABYLON.Observable();
  91776. /**
  91777. * An event triggered after rendering the scene
  91778. */
  91779. this.onAfterRenderObservable = new BABYLON.Observable();
  91780. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  91781. this.isBackground = isBackground === undefined ? true : isBackground;
  91782. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  91783. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  91784. this._scene.layers.push(this);
  91785. var engine = this._scene.getEngine();
  91786. // VBO
  91787. var vertices = [];
  91788. vertices.push(1, 1);
  91789. vertices.push(-1, 1);
  91790. vertices.push(-1, -1);
  91791. vertices.push(1, -1);
  91792. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91793. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91794. this._createIndexBuffer();
  91795. // Effects
  91796. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  91797. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  91798. }
  91799. Object.defineProperty(Layer.prototype, "onDispose", {
  91800. set: function (callback) {
  91801. if (this._onDisposeObserver) {
  91802. this.onDisposeObservable.remove(this._onDisposeObserver);
  91803. }
  91804. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  91805. },
  91806. enumerable: true,
  91807. configurable: true
  91808. });
  91809. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  91810. set: function (callback) {
  91811. if (this._onBeforeRenderObserver) {
  91812. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  91813. }
  91814. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  91815. },
  91816. enumerable: true,
  91817. configurable: true
  91818. });
  91819. Object.defineProperty(Layer.prototype, "onAfterRender", {
  91820. set: function (callback) {
  91821. if (this._onAfterRenderObserver) {
  91822. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  91823. }
  91824. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  91825. },
  91826. enumerable: true,
  91827. configurable: true
  91828. });
  91829. Layer.prototype._createIndexBuffer = function () {
  91830. var engine = this._scene.getEngine();
  91831. // Indices
  91832. var indices = [];
  91833. indices.push(0);
  91834. indices.push(1);
  91835. indices.push(2);
  91836. indices.push(0);
  91837. indices.push(2);
  91838. indices.push(3);
  91839. this._indexBuffer = engine.createIndexBuffer(indices);
  91840. };
  91841. Layer.prototype._rebuild = function () {
  91842. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91843. if (vb) {
  91844. vb._rebuild();
  91845. }
  91846. this._createIndexBuffer();
  91847. };
  91848. Layer.prototype.render = function () {
  91849. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  91850. // Check
  91851. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  91852. return;
  91853. var engine = this._scene.getEngine();
  91854. this.onBeforeRenderObservable.notifyObservers(this);
  91855. // Render
  91856. engine.enableEffect(currentEffect);
  91857. engine.setState(false);
  91858. // Texture
  91859. currentEffect.setTexture("textureSampler", this.texture);
  91860. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  91861. // Color
  91862. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  91863. // Scale / offset
  91864. currentEffect.setVector2("offset", this.offset);
  91865. currentEffect.setVector2("scale", this.scale);
  91866. // VBOs
  91867. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91868. // Draw order
  91869. if (!this.alphaTest) {
  91870. engine.setAlphaMode(this.alphaBlendingMode);
  91871. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91872. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  91873. }
  91874. else {
  91875. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91876. }
  91877. this.onAfterRenderObservable.notifyObservers(this);
  91878. };
  91879. Layer.prototype.dispose = function () {
  91880. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91881. if (vertexBuffer) {
  91882. vertexBuffer.dispose();
  91883. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91884. }
  91885. if (this._indexBuffer) {
  91886. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91887. this._indexBuffer = null;
  91888. }
  91889. if (this.texture) {
  91890. this.texture.dispose();
  91891. this.texture = null;
  91892. }
  91893. // Remove from scene
  91894. var index = this._scene.layers.indexOf(this);
  91895. this._scene.layers.splice(index, 1);
  91896. // Callback
  91897. this.onDisposeObservable.notifyObservers(this);
  91898. this.onDisposeObservable.clear();
  91899. this.onAfterRenderObservable.clear();
  91900. this.onBeforeRenderObservable.clear();
  91901. };
  91902. return Layer;
  91903. }());
  91904. BABYLON.Layer = Layer;
  91905. })(BABYLON || (BABYLON = {}));
  91906. //# sourceMappingURL=babylon.layer.js.map
  91907. "use strict";
  91908. var BABYLON;
  91909. (function (BABYLON) {
  91910. var TextureTools = /** @class */ (function () {
  91911. function TextureTools() {
  91912. }
  91913. /**
  91914. * Uses the GPU to create a copy texture rescaled at a given size
  91915. * @param texture Texture to copy from
  91916. * @param width Desired width
  91917. * @param height Desired height
  91918. * @return Generated texture
  91919. */
  91920. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  91921. if (useBilinearMode === void 0) { useBilinearMode = true; }
  91922. var scene = texture.getScene();
  91923. var engine = scene.getEngine();
  91924. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  91925. rtt.wrapU = texture.wrapU;
  91926. rtt.wrapV = texture.wrapV;
  91927. rtt.uOffset = texture.uOffset;
  91928. rtt.vOffset = texture.vOffset;
  91929. rtt.uScale = texture.uScale;
  91930. rtt.vScale = texture.vScale;
  91931. rtt.uAng = texture.uAng;
  91932. rtt.vAng = texture.vAng;
  91933. rtt.wAng = texture.wAng;
  91934. rtt.coordinatesIndex = texture.coordinatesIndex;
  91935. rtt.level = texture.level;
  91936. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  91937. rtt._texture.isReady = false;
  91938. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91939. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91940. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91941. passPostProcess.getEffect().executeWhenCompiled(function () {
  91942. passPostProcess.onApply = function (effect) {
  91943. effect.setTexture("textureSampler", texture);
  91944. };
  91945. var internalTexture = rtt.getInternalTexture();
  91946. if (internalTexture) {
  91947. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  91948. engine.unBindFramebuffer(internalTexture);
  91949. rtt.disposeFramebufferObjects();
  91950. passPostProcess.dispose();
  91951. internalTexture.isReady = true;
  91952. }
  91953. });
  91954. return rtt;
  91955. };
  91956. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  91957. if (!scene._environmentBRDFTexture) {
  91958. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91959. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91960. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91961. scene._environmentBRDFTexture = texture;
  91962. }
  91963. return scene._environmentBRDFTexture;
  91964. };
  91965. 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=";
  91966. return TextureTools;
  91967. }());
  91968. BABYLON.TextureTools = TextureTools;
  91969. })(BABYLON || (BABYLON = {}));
  91970. //# sourceMappingURL=babylon.textureTools.js.map
  91971. "use strict";
  91972. var BABYLON;
  91973. (function (BABYLON) {
  91974. var FramingBehavior = /** @class */ (function () {
  91975. function FramingBehavior() {
  91976. this._mode = FramingBehavior.FitFrustumSidesMode;
  91977. this._radiusScale = 1.0;
  91978. this._positionScale = 0.5;
  91979. this._defaultElevation = 0.3;
  91980. this._elevationReturnTime = 1500;
  91981. this._elevationReturnWaitTime = 1000;
  91982. this._zoomStopsAnimation = false;
  91983. this._framingTime = 1500;
  91984. this._isPointerDown = false;
  91985. this._lastInteractionTime = -Infinity;
  91986. // Framing control
  91987. this._animatables = new Array();
  91988. this._betaIsAnimating = false;
  91989. }
  91990. Object.defineProperty(FramingBehavior.prototype, "name", {
  91991. get: function () {
  91992. return "Framing";
  91993. },
  91994. enumerable: true,
  91995. configurable: true
  91996. });
  91997. Object.defineProperty(FramingBehavior.prototype, "mode", {
  91998. /**
  91999. * Gets current mode used by the behavior.
  92000. */
  92001. get: function () {
  92002. return this._mode;
  92003. },
  92004. /**
  92005. * Sets the current mode used by the behavior
  92006. */
  92007. set: function (mode) {
  92008. this._mode = mode;
  92009. },
  92010. enumerable: true,
  92011. configurable: true
  92012. });
  92013. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  92014. /**
  92015. * Gets the scale applied to the radius
  92016. */
  92017. get: function () {
  92018. return this._radiusScale;
  92019. },
  92020. /**
  92021. * Sets the scale applied to the radius (1 by default)
  92022. */
  92023. set: function (radius) {
  92024. this._radiusScale = radius;
  92025. },
  92026. enumerable: true,
  92027. configurable: true
  92028. });
  92029. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  92030. /**
  92031. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92032. */
  92033. get: function () {
  92034. return this._positionScale;
  92035. },
  92036. /**
  92037. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  92038. */
  92039. set: function (scale) {
  92040. this._positionScale = scale;
  92041. },
  92042. enumerable: true,
  92043. configurable: true
  92044. });
  92045. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  92046. /**
  92047. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92048. * behaviour is triggered, in radians.
  92049. */
  92050. get: function () {
  92051. return this._defaultElevation;
  92052. },
  92053. /**
  92054. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  92055. * behaviour is triggered, in radians.
  92056. */
  92057. set: function (elevation) {
  92058. this._defaultElevation = elevation;
  92059. },
  92060. enumerable: true,
  92061. configurable: true
  92062. });
  92063. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  92064. /**
  92065. * Gets the time (in milliseconds) taken to return to the default beta position.
  92066. * Negative value indicates camera should not return to default.
  92067. */
  92068. get: function () {
  92069. return this._elevationReturnTime;
  92070. },
  92071. /**
  92072. * Sets the time (in milliseconds) taken to return to the default beta position.
  92073. * Negative value indicates camera should not return to default.
  92074. */
  92075. set: function (speed) {
  92076. this._elevationReturnTime = speed;
  92077. },
  92078. enumerable: true,
  92079. configurable: true
  92080. });
  92081. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  92082. /**
  92083. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92084. */
  92085. get: function () {
  92086. return this._elevationReturnWaitTime;
  92087. },
  92088. /**
  92089. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  92090. */
  92091. set: function (time) {
  92092. this._elevationReturnWaitTime = time;
  92093. },
  92094. enumerable: true,
  92095. configurable: true
  92096. });
  92097. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  92098. /**
  92099. * Gets the flag that indicates if user zooming should stop animation.
  92100. */
  92101. get: function () {
  92102. return this._zoomStopsAnimation;
  92103. },
  92104. /**
  92105. * Sets the flag that indicates if user zooming should stop animation.
  92106. */
  92107. set: function (flag) {
  92108. this._zoomStopsAnimation = flag;
  92109. },
  92110. enumerable: true,
  92111. configurable: true
  92112. });
  92113. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  92114. /**
  92115. * Gets the transition time when framing the mesh, in milliseconds
  92116. */
  92117. get: function () {
  92118. return this._framingTime;
  92119. },
  92120. /**
  92121. * Sets the transition time when framing the mesh, in milliseconds
  92122. */
  92123. set: function (time) {
  92124. this._framingTime = time;
  92125. },
  92126. enumerable: true,
  92127. configurable: true
  92128. });
  92129. FramingBehavior.prototype.init = function () {
  92130. // Do notihng
  92131. };
  92132. FramingBehavior.prototype.attach = function (camera) {
  92133. var _this = this;
  92134. this._attachedCamera = camera;
  92135. var scene = this._attachedCamera.getScene();
  92136. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  92137. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92138. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92139. _this._isPointerDown = true;
  92140. return;
  92141. }
  92142. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92143. _this._isPointerDown = false;
  92144. }
  92145. });
  92146. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  92147. if (mesh) {
  92148. _this.zoomOnMesh(mesh);
  92149. }
  92150. });
  92151. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92152. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92153. _this._applyUserInteraction();
  92154. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  92155. // back to the default position after a given timeout
  92156. _this._maintainCameraAboveGround();
  92157. });
  92158. };
  92159. FramingBehavior.prototype.detach = function () {
  92160. if (!this._attachedCamera) {
  92161. return;
  92162. }
  92163. var scene = this._attachedCamera.getScene();
  92164. if (this._onPrePointerObservableObserver) {
  92165. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92166. }
  92167. if (this._onAfterCheckInputsObserver) {
  92168. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92169. }
  92170. if (this._onMeshTargetChangedObserver) {
  92171. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92172. }
  92173. this._attachedCamera = null;
  92174. };
  92175. /**
  92176. * Targets the given mesh and updates zoom level accordingly.
  92177. * @param mesh The mesh to target.
  92178. * @param radius Optional. If a cached radius position already exists, overrides default.
  92179. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92180. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92181. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92182. */
  92183. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92184. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92185. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92186. mesh.computeWorldMatrix(true);
  92187. var boundingBox = mesh.getBoundingInfo().boundingBox;
  92188. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  92189. };
  92190. /**
  92191. * Targets the given mesh with its children and updates zoom level accordingly.
  92192. * @param mesh The mesh to target.
  92193. * @param radius Optional. If a cached radius position already exists, overrides default.
  92194. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92195. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92196. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92197. */
  92198. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  92199. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92200. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92201. mesh.computeWorldMatrix(true);
  92202. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  92203. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  92204. };
  92205. /**
  92206. * Targets the given meshes with their children and updates zoom level accordingly.
  92207. * @param meshes The mesh to target.
  92208. * @param radius Optional. If a cached radius position already exists, overrides default.
  92209. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92210. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92211. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92212. */
  92213. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  92214. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92215. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92216. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  92217. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  92218. for (var i = 0; i < meshes.length; i++) {
  92219. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  92220. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  92221. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  92222. }
  92223. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  92224. };
  92225. /**
  92226. * Targets the given mesh and updates zoom level accordingly.
  92227. * @param mesh The mesh to target.
  92228. * @param radius Optional. If a cached radius position already exists, overrides default.
  92229. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  92230. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  92231. * @param onAnimationEnd Callback triggered at the end of the framing animation
  92232. */
  92233. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  92234. var _this = this;
  92235. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  92236. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  92237. var zoomTarget;
  92238. if (!this._attachedCamera) {
  92239. return;
  92240. }
  92241. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  92242. var bottom = minimumWorld.y;
  92243. var top = maximumWorld.y;
  92244. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  92245. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  92246. if (focusOnOriginXZ) {
  92247. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  92248. }
  92249. else {
  92250. var centerWorld = minimumWorld.add(radiusWorld);
  92251. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  92252. }
  92253. if (!this._vectorTransition) {
  92254. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  92255. }
  92256. this._betaIsAnimating = true;
  92257. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  92258. if (animatable) {
  92259. this._animatables.push(animatable);
  92260. }
  92261. // sets the radius and lower radius bounds
  92262. // Small delta ensures camera is not always at lower zoom limit.
  92263. var radius = 0;
  92264. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  92265. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92266. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  92267. radius = position;
  92268. }
  92269. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92270. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  92271. if (this._attachedCamera.lowerRadiusLimit === null) {
  92272. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  92273. }
  92274. }
  92275. // Set sensibilities
  92276. var extend = maximumWorld.subtract(minimumWorld).length();
  92277. this._attachedCamera.panningSensibility = 5000 / extend;
  92278. this._attachedCamera.wheelPrecision = 100 / radius;
  92279. // transition to new radius
  92280. if (!this._radiusTransition) {
  92281. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92282. }
  92283. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  92284. _this.stopAllAnimations();
  92285. if (onAnimationEnd) {
  92286. onAnimationEnd();
  92287. }
  92288. if (_this._attachedCamera) {
  92289. _this._attachedCamera.storeState();
  92290. }
  92291. });
  92292. if (animatable) {
  92293. this._animatables.push(animatable);
  92294. }
  92295. };
  92296. /**
  92297. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  92298. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  92299. * frustum width.
  92300. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  92301. * to fully enclose the mesh in the viewing frustum.
  92302. */
  92303. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  92304. var size = maximumWorld.subtract(minimumWorld);
  92305. var boxVectorGlobalDiagonal = size.length();
  92306. var frustumSlope = this._getFrustumSlope();
  92307. // Formula for setting distance
  92308. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  92309. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  92310. // Horizon distance
  92311. var radius = radiusWithoutFraming * this._radiusScale;
  92312. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  92313. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  92314. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  92315. var camera = this._attachedCamera;
  92316. if (!camera) {
  92317. return 0;
  92318. }
  92319. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  92320. // Don't exceed the requested limit
  92321. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  92322. }
  92323. // Don't exceed the upper radius limit
  92324. if (camera.upperRadiusLimit) {
  92325. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  92326. }
  92327. return distance;
  92328. };
  92329. /**
  92330. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  92331. * is automatically returned to its default position (expected to be above ground plane).
  92332. */
  92333. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  92334. var _this = this;
  92335. if (this._elevationReturnTime < 0) {
  92336. return;
  92337. }
  92338. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  92339. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  92340. var limitBeta = Math.PI * 0.5;
  92341. // Bring the camera back up if below the ground plane
  92342. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  92343. this._betaIsAnimating = true;
  92344. //Transition to new position
  92345. this.stopAllAnimations();
  92346. if (!this._betaTransition) {
  92347. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  92348. }
  92349. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  92350. _this._clearAnimationLocks();
  92351. _this.stopAllAnimations();
  92352. });
  92353. if (animatabe) {
  92354. this._animatables.push(animatabe);
  92355. }
  92356. }
  92357. };
  92358. /**
  92359. * Returns the frustum slope based on the canvas ratio and camera FOV
  92360. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  92361. */
  92362. FramingBehavior.prototype._getFrustumSlope = function () {
  92363. // Calculate the viewport ratio
  92364. // Aspect Ratio is Height/Width.
  92365. var camera = this._attachedCamera;
  92366. if (!camera) {
  92367. return BABYLON.Vector2.Zero();
  92368. }
  92369. var engine = camera.getScene().getEngine();
  92370. var aspectRatio = engine.getAspectRatio(camera);
  92371. // Camera FOV is the vertical field of view (top-bottom) in radians.
  92372. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  92373. var frustumSlopeY = Math.tan(camera.fov / 2);
  92374. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  92375. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  92376. // along the forward vector.
  92377. var frustumSlopeX = frustumSlopeY * aspectRatio;
  92378. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  92379. };
  92380. /**
  92381. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  92382. */
  92383. FramingBehavior.prototype._clearAnimationLocks = function () {
  92384. this._betaIsAnimating = false;
  92385. };
  92386. /**
  92387. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  92388. */
  92389. FramingBehavior.prototype._applyUserInteraction = function () {
  92390. if (this.isUserIsMoving) {
  92391. this._lastInteractionTime = BABYLON.Tools.Now;
  92392. this.stopAllAnimations();
  92393. this._clearAnimationLocks();
  92394. }
  92395. };
  92396. /**
  92397. * Stops and removes all animations that have been applied to the camera
  92398. */
  92399. FramingBehavior.prototype.stopAllAnimations = function () {
  92400. if (this._attachedCamera) {
  92401. this._attachedCamera.animations = [];
  92402. }
  92403. while (this._animatables.length) {
  92404. if (this._animatables[0]) {
  92405. this._animatables[0].onAnimationEnd = null;
  92406. this._animatables[0].stop();
  92407. }
  92408. this._animatables.shift();
  92409. }
  92410. };
  92411. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  92412. /**
  92413. * Gets a value indicating if the user is moving the camera
  92414. */
  92415. get: function () {
  92416. if (!this._attachedCamera) {
  92417. return false;
  92418. }
  92419. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  92420. this._attachedCamera.inertialBetaOffset !== 0 ||
  92421. this._attachedCamera.inertialRadiusOffset !== 0 ||
  92422. this._attachedCamera.inertialPanningX !== 0 ||
  92423. this._attachedCamera.inertialPanningY !== 0 ||
  92424. this._isPointerDown;
  92425. },
  92426. enumerable: true,
  92427. configurable: true
  92428. });
  92429. /**
  92430. * The easing function used by animations
  92431. */
  92432. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  92433. /**
  92434. * The easing mode used by animations
  92435. */
  92436. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  92437. // Statics
  92438. /**
  92439. * The camera can move all the way towards the mesh.
  92440. */
  92441. FramingBehavior.IgnoreBoundsSizeMode = 0;
  92442. /**
  92443. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  92444. */
  92445. FramingBehavior.FitFrustumSidesMode = 1;
  92446. return FramingBehavior;
  92447. }());
  92448. BABYLON.FramingBehavior = FramingBehavior;
  92449. })(BABYLON || (BABYLON = {}));
  92450. //# sourceMappingURL=babylon.framingBehavior.js.map
  92451. "use strict";
  92452. var BABYLON;
  92453. (function (BABYLON) {
  92454. /**
  92455. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  92456. */
  92457. var BouncingBehavior = /** @class */ (function () {
  92458. function BouncingBehavior() {
  92459. /**
  92460. * The duration of the animation, in milliseconds
  92461. */
  92462. this.transitionDuration = 450;
  92463. /**
  92464. * Length of the distance animated by the transition when lower radius is reached
  92465. */
  92466. this.lowerRadiusTransitionRange = 2;
  92467. /**
  92468. * Length of the distance animated by the transition when upper radius is reached
  92469. */
  92470. this.upperRadiusTransitionRange = -2;
  92471. this._autoTransitionRange = false;
  92472. // Animations
  92473. this._radiusIsAnimating = false;
  92474. this._radiusBounceTransition = null;
  92475. this._animatables = new Array();
  92476. }
  92477. Object.defineProperty(BouncingBehavior.prototype, "name", {
  92478. get: function () {
  92479. return "Bouncing";
  92480. },
  92481. enumerable: true,
  92482. configurable: true
  92483. });
  92484. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  92485. /**
  92486. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  92487. */
  92488. get: function () {
  92489. return this._autoTransitionRange;
  92490. },
  92491. /**
  92492. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  92493. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  92494. */
  92495. set: function (value) {
  92496. var _this = this;
  92497. if (this._autoTransitionRange === value) {
  92498. return;
  92499. }
  92500. this._autoTransitionRange = value;
  92501. var camera = this._attachedCamera;
  92502. if (!camera) {
  92503. return;
  92504. }
  92505. if (value) {
  92506. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  92507. if (!mesh) {
  92508. return;
  92509. }
  92510. mesh.computeWorldMatrix(true);
  92511. var diagonal = mesh.getBoundingInfo().diagonalLength;
  92512. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  92513. _this.upperRadiusTransitionRange = diagonal * 0.05;
  92514. });
  92515. }
  92516. else if (this._onMeshTargetChangedObserver) {
  92517. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92518. }
  92519. },
  92520. enumerable: true,
  92521. configurable: true
  92522. });
  92523. BouncingBehavior.prototype.init = function () {
  92524. // Do notihng
  92525. };
  92526. BouncingBehavior.prototype.attach = function (camera) {
  92527. var _this = this;
  92528. this._attachedCamera = camera;
  92529. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92530. if (!_this._attachedCamera) {
  92531. return;
  92532. }
  92533. // Add the bounce animation to the lower radius limit
  92534. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  92535. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  92536. }
  92537. // Add the bounce animation to the upper radius limit
  92538. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  92539. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  92540. }
  92541. });
  92542. };
  92543. BouncingBehavior.prototype.detach = function () {
  92544. if (!this._attachedCamera) {
  92545. return;
  92546. }
  92547. if (this._onAfterCheckInputsObserver) {
  92548. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92549. }
  92550. if (this._onMeshTargetChangedObserver) {
  92551. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  92552. }
  92553. this._attachedCamera = null;
  92554. };
  92555. /**
  92556. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  92557. * @param radiusLimit The limit to check against.
  92558. * @return Bool to indicate if at limit.
  92559. */
  92560. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  92561. if (!this._attachedCamera) {
  92562. return false;
  92563. }
  92564. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  92565. return true;
  92566. }
  92567. return false;
  92568. };
  92569. /**
  92570. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  92571. * @param radiusDelta The delta by which to animate to. Can be negative.
  92572. */
  92573. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  92574. var _this = this;
  92575. if (!this._attachedCamera) {
  92576. return;
  92577. }
  92578. if (!this._radiusBounceTransition) {
  92579. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  92580. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  92581. }
  92582. // Prevent zoom until bounce has completed
  92583. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  92584. this._attachedCamera.wheelPrecision = Infinity;
  92585. this._attachedCamera.inertialRadiusOffset = 0;
  92586. // Animate to the radius limit
  92587. this.stopAllAnimations();
  92588. this._radiusIsAnimating = true;
  92589. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  92590. if (animatable) {
  92591. this._animatables.push(animatable);
  92592. }
  92593. };
  92594. /**
  92595. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  92596. */
  92597. BouncingBehavior.prototype._clearAnimationLocks = function () {
  92598. this._radiusIsAnimating = false;
  92599. if (this._attachedCamera) {
  92600. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  92601. }
  92602. };
  92603. /**
  92604. * Stops and removes all animations that have been applied to the camera
  92605. */
  92606. BouncingBehavior.prototype.stopAllAnimations = function () {
  92607. if (this._attachedCamera) {
  92608. this._attachedCamera.animations = [];
  92609. }
  92610. while (this._animatables.length) {
  92611. this._animatables[0].onAnimationEnd = null;
  92612. this._animatables[0].stop();
  92613. this._animatables.shift();
  92614. }
  92615. };
  92616. /**
  92617. * The easing function used by animations
  92618. */
  92619. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  92620. /**
  92621. * The easing mode used by animations
  92622. */
  92623. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  92624. return BouncingBehavior;
  92625. }());
  92626. BABYLON.BouncingBehavior = BouncingBehavior;
  92627. })(BABYLON || (BABYLON = {}));
  92628. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  92629. "use strict";
  92630. var BABYLON;
  92631. (function (BABYLON) {
  92632. var AutoRotationBehavior = /** @class */ (function () {
  92633. function AutoRotationBehavior() {
  92634. this._zoomStopsAnimation = false;
  92635. this._idleRotationSpeed = 0.05;
  92636. this._idleRotationWaitTime = 2000;
  92637. this._idleRotationSpinupTime = 2000;
  92638. this._isPointerDown = false;
  92639. this._lastFrameTime = null;
  92640. this._lastInteractionTime = -Infinity;
  92641. this._cameraRotationSpeed = 0;
  92642. this._lastFrameRadius = 0;
  92643. }
  92644. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  92645. get: function () {
  92646. return "AutoRotation";
  92647. },
  92648. enumerable: true,
  92649. configurable: true
  92650. });
  92651. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  92652. /**
  92653. * Gets the flag that indicates if user zooming should stop animation.
  92654. */
  92655. get: function () {
  92656. return this._zoomStopsAnimation;
  92657. },
  92658. /**
  92659. * Sets the flag that indicates if user zooming should stop animation.
  92660. */
  92661. set: function (flag) {
  92662. this._zoomStopsAnimation = flag;
  92663. },
  92664. enumerable: true,
  92665. configurable: true
  92666. });
  92667. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  92668. /**
  92669. * Gets the default speed at which the camera rotates around the model.
  92670. */
  92671. get: function () {
  92672. return this._idleRotationSpeed;
  92673. },
  92674. /**
  92675. * Sets the default speed at which the camera rotates around the model.
  92676. */
  92677. set: function (speed) {
  92678. this._idleRotationSpeed = speed;
  92679. },
  92680. enumerable: true,
  92681. configurable: true
  92682. });
  92683. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  92684. /**
  92685. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  92686. */
  92687. get: function () {
  92688. return this._idleRotationWaitTime;
  92689. },
  92690. /**
  92691. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  92692. */
  92693. set: function (time) {
  92694. this._idleRotationWaitTime = time;
  92695. },
  92696. enumerable: true,
  92697. configurable: true
  92698. });
  92699. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  92700. /**
  92701. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  92702. */
  92703. get: function () {
  92704. return this._idleRotationSpinupTime;
  92705. },
  92706. /**
  92707. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  92708. */
  92709. set: function (time) {
  92710. this._idleRotationSpinupTime = time;
  92711. },
  92712. enumerable: true,
  92713. configurable: true
  92714. });
  92715. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  92716. /**
  92717. * Gets a value indicating if the camera is currently rotating because of this behavior
  92718. */
  92719. get: function () {
  92720. return Math.abs(this._cameraRotationSpeed) > 0;
  92721. },
  92722. enumerable: true,
  92723. configurable: true
  92724. });
  92725. AutoRotationBehavior.prototype.init = function () {
  92726. // Do notihng
  92727. };
  92728. AutoRotationBehavior.prototype.attach = function (camera) {
  92729. var _this = this;
  92730. this._attachedCamera = camera;
  92731. var scene = this._attachedCamera.getScene();
  92732. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  92733. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  92734. _this._isPointerDown = true;
  92735. return;
  92736. }
  92737. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  92738. _this._isPointerDown = false;
  92739. }
  92740. });
  92741. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  92742. var now = BABYLON.Tools.Now;
  92743. var dt = 0;
  92744. if (_this._lastFrameTime != null) {
  92745. dt = now - _this._lastFrameTime;
  92746. }
  92747. _this._lastFrameTime = now;
  92748. // Stop the animation if there is user interaction and the animation should stop for this interaction
  92749. _this._applyUserInteraction();
  92750. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  92751. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  92752. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  92753. // Step camera rotation by rotation speed
  92754. if (_this._attachedCamera) {
  92755. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  92756. }
  92757. });
  92758. };
  92759. AutoRotationBehavior.prototype.detach = function () {
  92760. if (!this._attachedCamera) {
  92761. return;
  92762. }
  92763. var scene = this._attachedCamera.getScene();
  92764. if (this._onPrePointerObservableObserver) {
  92765. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  92766. }
  92767. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  92768. this._attachedCamera = null;
  92769. };
  92770. /**
  92771. * Returns true if user is scrolling.
  92772. * @return true if user is scrolling.
  92773. */
  92774. AutoRotationBehavior.prototype._userIsZooming = function () {
  92775. if (!this._attachedCamera) {
  92776. return false;
  92777. }
  92778. return this._attachedCamera.inertialRadiusOffset !== 0;
  92779. };
  92780. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  92781. if (!this._attachedCamera) {
  92782. return false;
  92783. }
  92784. var zoomHasHitLimit = false;
  92785. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  92786. zoomHasHitLimit = true;
  92787. }
  92788. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  92789. this._lastFrameRadius = this._attachedCamera.radius;
  92790. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  92791. };
  92792. /**
  92793. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  92794. */
  92795. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  92796. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  92797. this._lastInteractionTime = BABYLON.Tools.Now;
  92798. }
  92799. };
  92800. // Tools
  92801. AutoRotationBehavior.prototype._userIsMoving = function () {
  92802. if (!this._attachedCamera) {
  92803. return false;
  92804. }
  92805. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  92806. this._attachedCamera.inertialBetaOffset !== 0 ||
  92807. this._attachedCamera.inertialRadiusOffset !== 0 ||
  92808. this._attachedCamera.inertialPanningX !== 0 ||
  92809. this._attachedCamera.inertialPanningY !== 0 ||
  92810. this._isPointerDown;
  92811. };
  92812. return AutoRotationBehavior;
  92813. }());
  92814. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  92815. })(BABYLON || (BABYLON = {}));
  92816. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  92817. "use strict";
  92818. var BABYLON;
  92819. (function (BABYLON) {
  92820. var NullEngineOptions = /** @class */ (function () {
  92821. function NullEngineOptions() {
  92822. this.renderWidth = 512;
  92823. this.renderHeight = 256;
  92824. this.textureSize = 512;
  92825. this.deterministicLockstep = false;
  92826. this.lockstepMaxSteps = 4;
  92827. }
  92828. return NullEngineOptions;
  92829. }());
  92830. BABYLON.NullEngineOptions = NullEngineOptions;
  92831. /**
  92832. * The null engine class provides support for headless version of babylon.js.
  92833. * This can be used in server side scenario or for testing purposes
  92834. */
  92835. var NullEngine = /** @class */ (function (_super) {
  92836. __extends(NullEngine, _super);
  92837. function NullEngine(options) {
  92838. if (options === void 0) { options = new NullEngineOptions(); }
  92839. var _this = _super.call(this, null) || this;
  92840. if (options.deterministicLockstep === undefined) {
  92841. options.deterministicLockstep = false;
  92842. }
  92843. if (options.lockstepMaxSteps === undefined) {
  92844. options.lockstepMaxSteps = 4;
  92845. }
  92846. _this._options = options;
  92847. // Init caps
  92848. // We consider we are on a webgl1 capable device
  92849. _this._caps = new BABYLON.EngineCapabilities();
  92850. _this._caps.maxTexturesImageUnits = 16;
  92851. _this._caps.maxVertexTextureImageUnits = 16;
  92852. _this._caps.maxTextureSize = 512;
  92853. _this._caps.maxCubemapTextureSize = 512;
  92854. _this._caps.maxRenderTextureSize = 512;
  92855. _this._caps.maxVertexAttribs = 16;
  92856. _this._caps.maxVaryingVectors = 16;
  92857. _this._caps.maxFragmentUniformVectors = 16;
  92858. _this._caps.maxVertexUniformVectors = 16;
  92859. // Extensions
  92860. _this._caps.standardDerivatives = false;
  92861. _this._caps.astc = null;
  92862. _this._caps.s3tc = null;
  92863. _this._caps.pvrtc = null;
  92864. _this._caps.etc1 = null;
  92865. _this._caps.etc2 = null;
  92866. _this._caps.textureAnisotropicFilterExtension = null;
  92867. _this._caps.maxAnisotropy = 0;
  92868. _this._caps.uintIndices = false;
  92869. _this._caps.fragmentDepthSupported = false;
  92870. _this._caps.highPrecisionShaderSupported = true;
  92871. _this._caps.colorBufferFloat = false;
  92872. _this._caps.textureFloat = false;
  92873. _this._caps.textureFloatLinearFiltering = false;
  92874. _this._caps.textureFloatRender = false;
  92875. _this._caps.textureHalfFloat = false;
  92876. _this._caps.textureHalfFloatLinearFiltering = false;
  92877. _this._caps.textureHalfFloatRender = false;
  92878. _this._caps.textureLOD = false;
  92879. _this._caps.drawBuffersExtension = false;
  92880. _this._caps.depthTextureExtension = false;
  92881. _this._caps.vertexArrayObject = false;
  92882. _this._caps.instancedArrays = false;
  92883. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  92884. // Wrappers
  92885. if (typeof URL === "undefined") {
  92886. URL = {
  92887. createObjectURL: function () { },
  92888. revokeObjectURL: function () { }
  92889. };
  92890. }
  92891. if (typeof Blob === "undefined") {
  92892. Blob = function () { };
  92893. }
  92894. return _this;
  92895. }
  92896. NullEngine.prototype.isDeterministicLockStep = function () {
  92897. return this._options.deterministicLockstep;
  92898. };
  92899. NullEngine.prototype.getLockstepMaxSteps = function () {
  92900. return this._options.lockstepMaxSteps;
  92901. };
  92902. NullEngine.prototype.getHardwareScalingLevel = function () {
  92903. return 1.0;
  92904. };
  92905. NullEngine.prototype.createVertexBuffer = function (vertices) {
  92906. return {
  92907. capacity: 0,
  92908. references: 1,
  92909. is32Bits: false
  92910. };
  92911. };
  92912. NullEngine.prototype.createIndexBuffer = function (indices) {
  92913. return {
  92914. capacity: 0,
  92915. references: 1,
  92916. is32Bits: false
  92917. };
  92918. };
  92919. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  92920. if (stencil === void 0) { stencil = false; }
  92921. };
  92922. NullEngine.prototype.getRenderWidth = function (useScreen) {
  92923. if (useScreen === void 0) { useScreen = false; }
  92924. if (!useScreen && this._currentRenderTarget) {
  92925. return this._currentRenderTarget.width;
  92926. }
  92927. return this._options.renderWidth;
  92928. };
  92929. NullEngine.prototype.getRenderHeight = function (useScreen) {
  92930. if (useScreen === void 0) { useScreen = false; }
  92931. if (!useScreen && this._currentRenderTarget) {
  92932. return this._currentRenderTarget.height;
  92933. }
  92934. return this._options.renderHeight;
  92935. };
  92936. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  92937. this._cachedViewport = viewport;
  92938. };
  92939. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  92940. return {
  92941. transformFeedback: null,
  92942. __SPECTOR_rebuildProgram: null
  92943. };
  92944. };
  92945. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  92946. return [];
  92947. };
  92948. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  92949. return [];
  92950. };
  92951. NullEngine.prototype.bindSamplers = function (effect) {
  92952. this._currentEffect = null;
  92953. };
  92954. NullEngine.prototype.enableEffect = function (effect) {
  92955. this._currentEffect = effect;
  92956. if (effect.onBind) {
  92957. effect.onBind(effect);
  92958. }
  92959. effect.onBindObservable.notifyObservers(effect);
  92960. };
  92961. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  92962. if (zOffset === void 0) { zOffset = 0; }
  92963. if (reverseSide === void 0) { reverseSide = false; }
  92964. };
  92965. NullEngine.prototype.setIntArray = function (uniform, array) {
  92966. };
  92967. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  92968. };
  92969. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  92970. };
  92971. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  92972. };
  92973. NullEngine.prototype.setFloatArray = function (uniform, array) {
  92974. };
  92975. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  92976. };
  92977. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  92978. };
  92979. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  92980. };
  92981. NullEngine.prototype.setArray = function (uniform, array) {
  92982. };
  92983. NullEngine.prototype.setArray2 = function (uniform, array) {
  92984. };
  92985. NullEngine.prototype.setArray3 = function (uniform, array) {
  92986. };
  92987. NullEngine.prototype.setArray4 = function (uniform, array) {
  92988. };
  92989. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  92990. };
  92991. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  92992. };
  92993. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  92994. };
  92995. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  92996. };
  92997. NullEngine.prototype.setFloat = function (uniform, value) {
  92998. };
  92999. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  93000. };
  93001. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  93002. };
  93003. NullEngine.prototype.setBool = function (uniform, bool) {
  93004. };
  93005. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  93006. };
  93007. NullEngine.prototype.setColor3 = function (uniform, color3) {
  93008. };
  93009. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  93010. };
  93011. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  93012. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  93013. if (this._alphaMode === mode) {
  93014. return;
  93015. }
  93016. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  93017. if (!noDepthWriteChange) {
  93018. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  93019. }
  93020. this._alphaMode = mode;
  93021. };
  93022. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  93023. };
  93024. NullEngine.prototype.wipeCaches = function (bruteForce) {
  93025. if (this.preventCacheWipeBetweenFrames) {
  93026. return;
  93027. }
  93028. this.resetTextureCache();
  93029. this._currentEffect = null;
  93030. if (bruteForce) {
  93031. this._currentProgram = null;
  93032. this._stencilState.reset();
  93033. this._depthCullingState.reset();
  93034. this._alphaState.reset();
  93035. }
  93036. this._cachedVertexBuffers = null;
  93037. this._cachedIndexBuffer = null;
  93038. this._cachedEffectForVertexBuffers = null;
  93039. };
  93040. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  93041. };
  93042. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  93043. };
  93044. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  93045. };
  93046. NullEngine.prototype._createTexture = function () {
  93047. return {};
  93048. };
  93049. NullEngine.prototype._releaseTexture = function (texture) {
  93050. };
  93051. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  93052. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93053. if (onLoad === void 0) { onLoad = null; }
  93054. if (onError === void 0) { onError = null; }
  93055. if (buffer === void 0) { buffer = null; }
  93056. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  93057. var url = String(urlArg);
  93058. texture.url = url;
  93059. texture.generateMipMaps = !noMipmap;
  93060. texture.samplingMode = samplingMode;
  93061. texture.invertY = invertY;
  93062. texture.baseWidth = this._options.textureSize;
  93063. texture.baseHeight = this._options.textureSize;
  93064. texture.width = this._options.textureSize;
  93065. texture.height = this._options.textureSize;
  93066. if (format) {
  93067. texture.format = format;
  93068. }
  93069. texture.isReady = true;
  93070. if (onLoad) {
  93071. onLoad();
  93072. }
  93073. return texture;
  93074. };
  93075. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  93076. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  93077. if (options !== undefined && typeof options === "object") {
  93078. fullOptions.generateMipMaps = options.generateMipMaps;
  93079. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  93080. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  93081. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  93082. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  93083. }
  93084. else {
  93085. fullOptions.generateMipMaps = options;
  93086. fullOptions.generateDepthBuffer = true;
  93087. fullOptions.generateStencilBuffer = false;
  93088. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93089. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  93090. }
  93091. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  93092. var width = size.width || size;
  93093. var height = size.height || size;
  93094. texture._depthStencilBuffer = {};
  93095. texture._framebuffer = {};
  93096. texture.baseWidth = width;
  93097. texture.baseHeight = height;
  93098. texture.width = width;
  93099. texture.height = height;
  93100. texture.isReady = true;
  93101. texture.samples = 1;
  93102. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  93103. texture.samplingMode = fullOptions.samplingMode;
  93104. texture.type = fullOptions.type;
  93105. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  93106. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  93107. return texture;
  93108. };
  93109. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  93110. texture.samplingMode = samplingMode;
  93111. };
  93112. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  93113. if (this._currentRenderTarget) {
  93114. this.unBindFramebuffer(this._currentRenderTarget);
  93115. }
  93116. this._currentRenderTarget = texture;
  93117. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  93118. if (this._cachedViewport && !forceFullscreenViewport) {
  93119. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  93120. }
  93121. };
  93122. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  93123. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  93124. this._currentRenderTarget = null;
  93125. if (onBeforeUnbind) {
  93126. if (texture._MSAAFramebuffer) {
  93127. this._currentFramebuffer = texture._framebuffer;
  93128. }
  93129. onBeforeUnbind();
  93130. }
  93131. this._currentFramebuffer = null;
  93132. };
  93133. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  93134. var vbo = {
  93135. capacity: 1,
  93136. references: 1,
  93137. is32Bits: false
  93138. };
  93139. return vbo;
  93140. };
  93141. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  93142. if (offset === void 0) { offset = 0; }
  93143. };
  93144. /**
  93145. * Updates a dynamic vertex buffer.
  93146. * @param vertexBuffer the vertex buffer to update
  93147. * @param data the data used to update the vertex buffer
  93148. * @param byteOffset the byte offset of the data (optional)
  93149. * @param byteLength the byte length of the data (optional)
  93150. */
  93151. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  93152. };
  93153. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  93154. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  93155. this._boundTexturesCache[this._activeChannel] = texture;
  93156. }
  93157. };
  93158. NullEngine.prototype._bindTexture = function (channel, texture) {
  93159. if (channel < 0) {
  93160. return;
  93161. }
  93162. this._bindTextureDirectly(0, texture);
  93163. };
  93164. NullEngine.prototype._releaseBuffer = function (buffer) {
  93165. buffer.references--;
  93166. if (buffer.references === 0) {
  93167. return true;
  93168. }
  93169. return false;
  93170. };
  93171. return NullEngine;
  93172. }(BABYLON.Engine));
  93173. BABYLON.NullEngine = NullEngine;
  93174. })(BABYLON || (BABYLON = {}));
  93175. //# sourceMappingURL=babylon.nullEngine.js.map
  93176. "use strict";
  93177. var BABYLON;
  93178. (function (BABYLON) {
  93179. /**
  93180. * This class can be used to get instrumentation data from a Babylon engine
  93181. */
  93182. var EngineInstrumentation = /** @class */ (function () {
  93183. function EngineInstrumentation(engine) {
  93184. this.engine = engine;
  93185. this._captureGPUFrameTime = false;
  93186. this._gpuFrameTime = new BABYLON.PerfCounter();
  93187. this._captureShaderCompilationTime = false;
  93188. this._shaderCompilationTime = new BABYLON.PerfCounter();
  93189. // Observers
  93190. this._onBeginFrameObserver = null;
  93191. this._onEndFrameObserver = null;
  93192. this._onBeforeShaderCompilationObserver = null;
  93193. this._onAfterShaderCompilationObserver = null;
  93194. }
  93195. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  93196. // Properties
  93197. /**
  93198. * Gets the perf counter used for GPU frame time
  93199. */
  93200. get: function () {
  93201. return this._gpuFrameTime;
  93202. },
  93203. enumerable: true,
  93204. configurable: true
  93205. });
  93206. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  93207. /**
  93208. * Gets the GPU frame time capture status
  93209. */
  93210. get: function () {
  93211. return this._captureGPUFrameTime;
  93212. },
  93213. /**
  93214. * Enable or disable the GPU frame time capture
  93215. */
  93216. set: function (value) {
  93217. var _this = this;
  93218. if (value === this._captureGPUFrameTime) {
  93219. return;
  93220. }
  93221. this._captureGPUFrameTime = value;
  93222. if (value) {
  93223. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  93224. if (!_this._gpuFrameTimeToken) {
  93225. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  93226. }
  93227. });
  93228. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  93229. if (!_this._gpuFrameTimeToken) {
  93230. return;
  93231. }
  93232. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  93233. if (time > -1) {
  93234. _this._gpuFrameTimeToken = null;
  93235. _this._gpuFrameTime.fetchNewFrame();
  93236. _this._gpuFrameTime.addCount(time, true);
  93237. }
  93238. });
  93239. }
  93240. else {
  93241. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93242. this._onBeginFrameObserver = null;
  93243. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93244. this._onEndFrameObserver = null;
  93245. }
  93246. },
  93247. enumerable: true,
  93248. configurable: true
  93249. });
  93250. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  93251. /**
  93252. * Gets the perf counter used for shader compilation time
  93253. */
  93254. get: function () {
  93255. return this._shaderCompilationTime;
  93256. },
  93257. enumerable: true,
  93258. configurable: true
  93259. });
  93260. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  93261. /**
  93262. * Gets the shader compilation time capture status
  93263. */
  93264. get: function () {
  93265. return this._captureShaderCompilationTime;
  93266. },
  93267. /**
  93268. * Enable or disable the shader compilation time capture
  93269. */
  93270. set: function (value) {
  93271. var _this = this;
  93272. if (value === this._captureShaderCompilationTime) {
  93273. return;
  93274. }
  93275. this._captureShaderCompilationTime = value;
  93276. if (value) {
  93277. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  93278. _this._shaderCompilationTime.fetchNewFrame();
  93279. _this._shaderCompilationTime.beginMonitoring();
  93280. });
  93281. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  93282. _this._shaderCompilationTime.endMonitoring();
  93283. });
  93284. }
  93285. else {
  93286. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93287. this._onBeforeShaderCompilationObserver = null;
  93288. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93289. this._onAfterShaderCompilationObserver = null;
  93290. }
  93291. },
  93292. enumerable: true,
  93293. configurable: true
  93294. });
  93295. EngineInstrumentation.prototype.dispose = function () {
  93296. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  93297. this._onBeginFrameObserver = null;
  93298. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  93299. this._onEndFrameObserver = null;
  93300. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  93301. this._onBeforeShaderCompilationObserver = null;
  93302. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  93303. this._onAfterShaderCompilationObserver = null;
  93304. this.engine = null;
  93305. };
  93306. return EngineInstrumentation;
  93307. }());
  93308. BABYLON.EngineInstrumentation = EngineInstrumentation;
  93309. })(BABYLON || (BABYLON = {}));
  93310. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  93311. "use strict";
  93312. var BABYLON;
  93313. (function (BABYLON) {
  93314. /**
  93315. * This class can be used to get instrumentation data from a Babylon engine
  93316. */
  93317. var SceneInstrumentation = /** @class */ (function () {
  93318. function SceneInstrumentation(scene) {
  93319. var _this = this;
  93320. this.scene = scene;
  93321. this._captureActiveMeshesEvaluationTime = false;
  93322. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  93323. this._captureRenderTargetsRenderTime = false;
  93324. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  93325. this._captureFrameTime = false;
  93326. this._frameTime = new BABYLON.PerfCounter();
  93327. this._captureRenderTime = false;
  93328. this._renderTime = new BABYLON.PerfCounter();
  93329. this._captureInterFrameTime = false;
  93330. this._interFrameTime = new BABYLON.PerfCounter();
  93331. this._captureParticlesRenderTime = false;
  93332. this._particlesRenderTime = new BABYLON.PerfCounter();
  93333. this._captureSpritesRenderTime = false;
  93334. this._spritesRenderTime = new BABYLON.PerfCounter();
  93335. this._capturePhysicsTime = false;
  93336. this._physicsTime = new BABYLON.PerfCounter();
  93337. this._captureAnimationsTime = false;
  93338. this._animationsTime = new BABYLON.PerfCounter();
  93339. // Observers
  93340. this._onBeforeActiveMeshesEvaluationObserver = null;
  93341. this._onAfterActiveMeshesEvaluationObserver = null;
  93342. this._onBeforeRenderTargetsRenderObserver = null;
  93343. this._onAfterRenderTargetsRenderObserver = null;
  93344. this._onAfterRenderObserver = null;
  93345. this._onBeforeDrawPhaseObserver = null;
  93346. this._onAfterDrawPhaseObserver = null;
  93347. this._onBeforeAnimationsObserver = null;
  93348. this._onBeforeParticlesRenderingObserver = null;
  93349. this._onAfterParticlesRenderingObserver = null;
  93350. this._onBeforeSpritesRenderingObserver = null;
  93351. this._onAfterSpritesRenderingObserver = null;
  93352. this._onBeforePhysicsObserver = null;
  93353. this._onAfterPhysicsObserver = null;
  93354. this._onAfterAnimationsObserver = null;
  93355. // Before render
  93356. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  93357. if (_this._captureActiveMeshesEvaluationTime) {
  93358. _this._activeMeshesEvaluationTime.fetchNewFrame();
  93359. }
  93360. if (_this._captureRenderTargetsRenderTime) {
  93361. _this._renderTargetsRenderTime.fetchNewFrame();
  93362. }
  93363. if (_this._captureFrameTime) {
  93364. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  93365. _this._frameTime.beginMonitoring();
  93366. }
  93367. if (_this._captureInterFrameTime) {
  93368. _this._interFrameTime.endMonitoring();
  93369. }
  93370. if (_this._captureParticlesRenderTime) {
  93371. _this._particlesRenderTime.fetchNewFrame();
  93372. }
  93373. if (_this._captureSpritesRenderTime) {
  93374. _this._spritesRenderTime.fetchNewFrame();
  93375. }
  93376. if (_this._captureAnimationsTime) {
  93377. _this._animationsTime.beginMonitoring();
  93378. }
  93379. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  93380. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  93381. });
  93382. // After render
  93383. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  93384. if (_this._captureFrameTime) {
  93385. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  93386. _this._frameTime.endMonitoring();
  93387. }
  93388. if (_this._captureRenderTime) {
  93389. _this._renderTime.endMonitoring(false);
  93390. }
  93391. if (_this._captureInterFrameTime) {
  93392. _this._interFrameTime.beginMonitoring();
  93393. }
  93394. });
  93395. }
  93396. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  93397. // Properties
  93398. /**
  93399. * Gets the perf counter used for active meshes evaluation time
  93400. */
  93401. get: function () {
  93402. return this._activeMeshesEvaluationTime;
  93403. },
  93404. enumerable: true,
  93405. configurable: true
  93406. });
  93407. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  93408. /**
  93409. * Gets the active meshes evaluation time capture status
  93410. */
  93411. get: function () {
  93412. return this._captureActiveMeshesEvaluationTime;
  93413. },
  93414. /**
  93415. * Enable or disable the active meshes evaluation time capture
  93416. */
  93417. set: function (value) {
  93418. var _this = this;
  93419. if (value === this._captureActiveMeshesEvaluationTime) {
  93420. return;
  93421. }
  93422. this._captureActiveMeshesEvaluationTime = value;
  93423. if (value) {
  93424. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  93425. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  93426. _this._activeMeshesEvaluationTime.beginMonitoring();
  93427. });
  93428. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  93429. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  93430. _this._activeMeshesEvaluationTime.endMonitoring();
  93431. });
  93432. }
  93433. else {
  93434. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  93435. this._onBeforeActiveMeshesEvaluationObserver = null;
  93436. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  93437. this._onAfterActiveMeshesEvaluationObserver = null;
  93438. }
  93439. },
  93440. enumerable: true,
  93441. configurable: true
  93442. });
  93443. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  93444. /**
  93445. * Gets the perf counter used for render targets render time
  93446. */
  93447. get: function () {
  93448. return this._renderTargetsRenderTime;
  93449. },
  93450. enumerable: true,
  93451. configurable: true
  93452. });
  93453. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  93454. /**
  93455. * Gets the render targets render time capture status
  93456. */
  93457. get: function () {
  93458. return this._captureRenderTargetsRenderTime;
  93459. },
  93460. /**
  93461. * Enable or disable the render targets render time capture
  93462. */
  93463. set: function (value) {
  93464. var _this = this;
  93465. if (value === this._captureRenderTargetsRenderTime) {
  93466. return;
  93467. }
  93468. this._captureRenderTargetsRenderTime = value;
  93469. if (value) {
  93470. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  93471. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  93472. _this._renderTargetsRenderTime.beginMonitoring();
  93473. });
  93474. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  93475. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  93476. _this._renderTargetsRenderTime.endMonitoring(false);
  93477. });
  93478. }
  93479. else {
  93480. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  93481. this._onBeforeRenderTargetsRenderObserver = null;
  93482. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  93483. this._onAfterRenderTargetsRenderObserver = null;
  93484. }
  93485. },
  93486. enumerable: true,
  93487. configurable: true
  93488. });
  93489. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  93490. /**
  93491. * Gets the perf counter used for particles render time
  93492. */
  93493. get: function () {
  93494. return this._particlesRenderTime;
  93495. },
  93496. enumerable: true,
  93497. configurable: true
  93498. });
  93499. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  93500. /**
  93501. * Gets the particles render time capture status
  93502. */
  93503. get: function () {
  93504. return this._captureParticlesRenderTime;
  93505. },
  93506. /**
  93507. * Enable or disable the particles render time capture
  93508. */
  93509. set: function (value) {
  93510. var _this = this;
  93511. if (value === this._captureParticlesRenderTime) {
  93512. return;
  93513. }
  93514. this._captureParticlesRenderTime = value;
  93515. if (value) {
  93516. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  93517. BABYLON.Tools.StartPerformanceCounter("Particles");
  93518. _this._particlesRenderTime.beginMonitoring();
  93519. });
  93520. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  93521. BABYLON.Tools.EndPerformanceCounter("Particles");
  93522. _this._particlesRenderTime.endMonitoring(false);
  93523. });
  93524. }
  93525. else {
  93526. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  93527. this._onBeforeParticlesRenderingObserver = null;
  93528. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  93529. this._onAfterParticlesRenderingObserver = null;
  93530. }
  93531. },
  93532. enumerable: true,
  93533. configurable: true
  93534. });
  93535. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  93536. /**
  93537. * Gets the perf counter used for sprites render time
  93538. */
  93539. get: function () {
  93540. return this._spritesRenderTime;
  93541. },
  93542. enumerable: true,
  93543. configurable: true
  93544. });
  93545. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  93546. /**
  93547. * Gets the sprites render time capture status
  93548. */
  93549. get: function () {
  93550. return this._captureSpritesRenderTime;
  93551. },
  93552. /**
  93553. * Enable or disable the sprites render time capture
  93554. */
  93555. set: function (value) {
  93556. var _this = this;
  93557. if (value === this._captureSpritesRenderTime) {
  93558. return;
  93559. }
  93560. this._captureSpritesRenderTime = value;
  93561. if (value) {
  93562. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  93563. BABYLON.Tools.StartPerformanceCounter("Sprites");
  93564. _this._spritesRenderTime.beginMonitoring();
  93565. });
  93566. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  93567. BABYLON.Tools.EndPerformanceCounter("Sprites");
  93568. _this._spritesRenderTime.endMonitoring(false);
  93569. });
  93570. }
  93571. else {
  93572. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  93573. this._onBeforeSpritesRenderingObserver = null;
  93574. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  93575. this._onAfterSpritesRenderingObserver = null;
  93576. }
  93577. },
  93578. enumerable: true,
  93579. configurable: true
  93580. });
  93581. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  93582. /**
  93583. * Gets the perf counter used for physics time
  93584. */
  93585. get: function () {
  93586. return this._physicsTime;
  93587. },
  93588. enumerable: true,
  93589. configurable: true
  93590. });
  93591. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  93592. /**
  93593. * Gets the physics time capture status
  93594. */
  93595. get: function () {
  93596. return this._capturePhysicsTime;
  93597. },
  93598. /**
  93599. * Enable or disable the physics time capture
  93600. */
  93601. set: function (value) {
  93602. var _this = this;
  93603. if (value === this._capturePhysicsTime) {
  93604. return;
  93605. }
  93606. this._capturePhysicsTime = value;
  93607. if (value) {
  93608. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  93609. BABYLON.Tools.StartPerformanceCounter("Physics");
  93610. _this._physicsTime.beginMonitoring();
  93611. });
  93612. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  93613. BABYLON.Tools.EndPerformanceCounter("Physics");
  93614. _this._physicsTime.endMonitoring();
  93615. });
  93616. }
  93617. else {
  93618. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  93619. this._onBeforePhysicsObserver = null;
  93620. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  93621. this._onAfterPhysicsObserver = null;
  93622. }
  93623. },
  93624. enumerable: true,
  93625. configurable: true
  93626. });
  93627. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  93628. /**
  93629. * Gets the perf counter used for animations time
  93630. */
  93631. get: function () {
  93632. return this._animationsTime;
  93633. },
  93634. enumerable: true,
  93635. configurable: true
  93636. });
  93637. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  93638. /**
  93639. * Gets the animations time capture status
  93640. */
  93641. get: function () {
  93642. return this._captureAnimationsTime;
  93643. },
  93644. /**
  93645. * Enable or disable the animations time capture
  93646. */
  93647. set: function (value) {
  93648. var _this = this;
  93649. if (value === this._captureAnimationsTime) {
  93650. return;
  93651. }
  93652. this._captureAnimationsTime = value;
  93653. if (value) {
  93654. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  93655. _this._animationsTime.endMonitoring();
  93656. });
  93657. }
  93658. else {
  93659. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  93660. this._onAfterAnimationsObserver = null;
  93661. }
  93662. },
  93663. enumerable: true,
  93664. configurable: true
  93665. });
  93666. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  93667. /**
  93668. * Gets the perf counter used for frame time capture
  93669. */
  93670. get: function () {
  93671. return this._frameTime;
  93672. },
  93673. enumerable: true,
  93674. configurable: true
  93675. });
  93676. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  93677. /**
  93678. * Gets the frame time capture status
  93679. */
  93680. get: function () {
  93681. return this._captureFrameTime;
  93682. },
  93683. /**
  93684. * Enable or disable the frame time capture
  93685. */
  93686. set: function (value) {
  93687. this._captureFrameTime = value;
  93688. },
  93689. enumerable: true,
  93690. configurable: true
  93691. });
  93692. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  93693. /**
  93694. * Gets the perf counter used for inter-frames time capture
  93695. */
  93696. get: function () {
  93697. return this._interFrameTime;
  93698. },
  93699. enumerable: true,
  93700. configurable: true
  93701. });
  93702. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  93703. /**
  93704. * Gets the inter-frames time capture status
  93705. */
  93706. get: function () {
  93707. return this._captureInterFrameTime;
  93708. },
  93709. /**
  93710. * Enable or disable the inter-frames time capture
  93711. */
  93712. set: function (value) {
  93713. this._captureInterFrameTime = value;
  93714. },
  93715. enumerable: true,
  93716. configurable: true
  93717. });
  93718. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  93719. /**
  93720. * Gets the perf counter used for render time capture
  93721. */
  93722. get: function () {
  93723. return this._renderTime;
  93724. },
  93725. enumerable: true,
  93726. configurable: true
  93727. });
  93728. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  93729. /**
  93730. * Gets the render time capture status
  93731. */
  93732. get: function () {
  93733. return this._captureRenderTime;
  93734. },
  93735. /**
  93736. * Enable or disable the render time capture
  93737. */
  93738. set: function (value) {
  93739. var _this = this;
  93740. if (value === this._captureRenderTime) {
  93741. return;
  93742. }
  93743. this._captureRenderTime = value;
  93744. if (value) {
  93745. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  93746. _this._renderTime.beginMonitoring();
  93747. BABYLON.Tools.StartPerformanceCounter("Main render");
  93748. });
  93749. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  93750. _this._renderTime.endMonitoring(false);
  93751. BABYLON.Tools.EndPerformanceCounter("Main render");
  93752. });
  93753. }
  93754. else {
  93755. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  93756. this._onBeforeDrawPhaseObserver = null;
  93757. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  93758. this._onAfterDrawPhaseObserver = null;
  93759. }
  93760. },
  93761. enumerable: true,
  93762. configurable: true
  93763. });
  93764. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  93765. /**
  93766. * Gets the perf counter used for draw calls
  93767. */
  93768. get: function () {
  93769. return this.scene.getEngine()._drawCalls;
  93770. },
  93771. enumerable: true,
  93772. configurable: true
  93773. });
  93774. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  93775. /**
  93776. * Gets the perf counter used for texture collisions
  93777. */
  93778. get: function () {
  93779. return this.scene.getEngine()._textureCollisions;
  93780. },
  93781. enumerable: true,
  93782. configurable: true
  93783. });
  93784. SceneInstrumentation.prototype.dispose = function () {
  93785. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93786. this._onAfterRenderObserver = null;
  93787. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  93788. this._onBeforeActiveMeshesEvaluationObserver = null;
  93789. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  93790. this._onAfterActiveMeshesEvaluationObserver = null;
  93791. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  93792. this._onBeforeRenderTargetsRenderObserver = null;
  93793. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  93794. this._onAfterRenderTargetsRenderObserver = null;
  93795. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  93796. this._onBeforeAnimationsObserver = null;
  93797. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  93798. this._onBeforeParticlesRenderingObserver = null;
  93799. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  93800. this._onAfterParticlesRenderingObserver = null;
  93801. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  93802. this._onBeforeSpritesRenderingObserver = null;
  93803. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  93804. this._onAfterSpritesRenderingObserver = null;
  93805. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  93806. this._onBeforeDrawPhaseObserver = null;
  93807. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  93808. this._onAfterDrawPhaseObserver = null;
  93809. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  93810. this._onBeforePhysicsObserver = null;
  93811. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  93812. this._onAfterPhysicsObserver = null;
  93813. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  93814. this._onAfterAnimationsObserver = null;
  93815. this.scene = null;
  93816. };
  93817. return SceneInstrumentation;
  93818. }());
  93819. BABYLON.SceneInstrumentation = SceneInstrumentation;
  93820. })(BABYLON || (BABYLON = {}));
  93821. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  93822. "use strict";
  93823. var BABYLON;
  93824. (function (BABYLON) {
  93825. var _TimeToken = /** @class */ (function () {
  93826. function _TimeToken() {
  93827. this._timeElapsedQueryEnded = false;
  93828. }
  93829. return _TimeToken;
  93830. }());
  93831. BABYLON._TimeToken = _TimeToken;
  93832. })(BABYLON || (BABYLON = {}));
  93833. //# sourceMappingURL=babylon.timeToken.js.map
  93834. "use strict";
  93835. var BABYLON;
  93836. (function (BABYLON) {
  93837. /**
  93838. * Background material defines definition.
  93839. * @ignore Mainly internal Use
  93840. */
  93841. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  93842. __extends(BackgroundMaterialDefines, _super);
  93843. /**
  93844. * Constructor of the defines.
  93845. */
  93846. function BackgroundMaterialDefines() {
  93847. var _this = _super.call(this) || this;
  93848. /**
  93849. * True if the diffuse texture is in use.
  93850. */
  93851. _this.DIFFUSE = false;
  93852. /**
  93853. * The direct UV channel to use.
  93854. */
  93855. _this.DIFFUSEDIRECTUV = 0;
  93856. /**
  93857. * True if the diffuse texture is in gamma space.
  93858. */
  93859. _this.GAMMADIFFUSE = false;
  93860. /**
  93861. * True if the diffuse texture has opacity in the alpha channel.
  93862. */
  93863. _this.DIFFUSEHASALPHA = false;
  93864. /**
  93865. * True if you want the material to fade to transparent at grazing angle.
  93866. */
  93867. _this.OPACITYFRESNEL = false;
  93868. /**
  93869. * True if an extra blur needs to be added in the reflection.
  93870. */
  93871. _this.REFLECTIONBLUR = false;
  93872. /**
  93873. * True if you want the material to fade to reflection at grazing angle.
  93874. */
  93875. _this.REFLECTIONFRESNEL = false;
  93876. /**
  93877. * True if you want the material to falloff as far as you move away from the scene center.
  93878. */
  93879. _this.REFLECTIONFALLOFF = false;
  93880. /**
  93881. * False if the current Webgl implementation does not support the texture lod extension.
  93882. */
  93883. _this.TEXTURELODSUPPORT = false;
  93884. /**
  93885. * True to ensure the data are premultiplied.
  93886. */
  93887. _this.PREMULTIPLYALPHA = false;
  93888. /**
  93889. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  93890. */
  93891. _this.USERGBCOLOR = false;
  93892. /**
  93893. * True to add noise in order to reduce the banding effect.
  93894. */
  93895. _this.NOISE = false;
  93896. /**
  93897. * is the reflection texture in BGR color scheme?
  93898. * Mainly used to solve a bug in ios10 video tag
  93899. */
  93900. _this.REFLECTIONBGR = false;
  93901. _this.IMAGEPROCESSING = false;
  93902. _this.VIGNETTE = false;
  93903. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  93904. _this.VIGNETTEBLENDMODEOPAQUE = false;
  93905. _this.TONEMAPPING = false;
  93906. _this.CONTRAST = false;
  93907. _this.COLORCURVES = false;
  93908. _this.COLORGRADING = false;
  93909. _this.COLORGRADING3D = false;
  93910. _this.SAMPLER3DGREENDEPTH = false;
  93911. _this.SAMPLER3DBGRMAP = false;
  93912. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  93913. _this.EXPOSURE = false;
  93914. // Reflection.
  93915. _this.REFLECTION = false;
  93916. _this.REFLECTIONMAP_3D = false;
  93917. _this.REFLECTIONMAP_SPHERICAL = false;
  93918. _this.REFLECTIONMAP_PLANAR = false;
  93919. _this.REFLECTIONMAP_CUBIC = false;
  93920. _this.REFLECTIONMAP_PROJECTION = false;
  93921. _this.REFLECTIONMAP_SKYBOX = false;
  93922. _this.REFLECTIONMAP_EXPLICIT = false;
  93923. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  93924. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  93925. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  93926. _this.INVERTCUBICMAP = false;
  93927. _this.REFLECTIONMAP_OPPOSITEZ = false;
  93928. _this.LODINREFLECTIONALPHA = false;
  93929. _this.GAMMAREFLECTION = false;
  93930. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  93931. // Default BJS.
  93932. _this.MAINUV1 = false;
  93933. _this.MAINUV2 = false;
  93934. _this.UV1 = false;
  93935. _this.UV2 = false;
  93936. _this.CLIPPLANE = false;
  93937. _this.POINTSIZE = false;
  93938. _this.FOG = false;
  93939. _this.NORMAL = false;
  93940. _this.NUM_BONE_INFLUENCERS = 0;
  93941. _this.BonesPerMesh = 0;
  93942. _this.INSTANCES = false;
  93943. _this.SHADOWFLOAT = false;
  93944. _this.rebuild();
  93945. return _this;
  93946. }
  93947. return BackgroundMaterialDefines;
  93948. }(BABYLON.MaterialDefines));
  93949. /**
  93950. * Background material used to create an efficient environement around your scene.
  93951. */
  93952. var BackgroundMaterial = /** @class */ (function (_super) {
  93953. __extends(BackgroundMaterial, _super);
  93954. /**
  93955. * Instantiates a Background Material in the given scene
  93956. * @param name The friendly name of the material
  93957. * @param scene The scene to add the material to
  93958. */
  93959. function BackgroundMaterial(name, scene) {
  93960. var _this = _super.call(this, name, scene) || this;
  93961. /**
  93962. * Key light Color (multiply against the R channel of the environement texture)
  93963. */
  93964. _this.primaryColor = BABYLON.Color3.White();
  93965. /**
  93966. * Key light Level (allowing HDR output of the background)
  93967. */
  93968. _this.primaryLevel = 1;
  93969. /**
  93970. * Secondary light Color (multiply against the G channel of the environement texture)
  93971. */
  93972. _this.secondaryColor = BABYLON.Color3.Gray();
  93973. /**
  93974. * Secondary light Level (allowing HDR output of the background)
  93975. */
  93976. _this.secondaryLevel = 1;
  93977. /**
  93978. * Tertiary light Color (multiply against the B channel of the environement texture)
  93979. */
  93980. _this.tertiaryColor = BABYLON.Color3.Black();
  93981. /**
  93982. * Tertiary light Level (allowing HDR output of the background)
  93983. */
  93984. _this.tertiaryLevel = 1;
  93985. /**
  93986. * Reflection Texture used in the material.
  93987. * Should be author in a specific way for the best result (refer to the documentation).
  93988. */
  93989. _this.reflectionTexture = null;
  93990. /**
  93991. * Reflection Texture level of blur.
  93992. *
  93993. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  93994. * texture twice.
  93995. */
  93996. _this.reflectionBlur = 0;
  93997. /**
  93998. * Diffuse Texture used in the material.
  93999. * Should be author in a specific way for the best result (refer to the documentation).
  94000. */
  94001. _this.diffuseTexture = null;
  94002. _this._shadowLights = null;
  94003. /**
  94004. * Specify the list of lights casting shadow on the material.
  94005. * All scene shadow lights will be included if null.
  94006. */
  94007. _this.shadowLights = null;
  94008. /**
  94009. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  94010. * soft lighting on the background.
  94011. */
  94012. _this.shadowBlurScale = 1;
  94013. /**
  94014. * Helps adjusting the shadow to a softer level if required.
  94015. * 0 means black shadows and 1 means no shadows.
  94016. */
  94017. _this.shadowLevel = 0;
  94018. /**
  94019. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  94020. * It is usually zero but might be interesting to modify according to your setup.
  94021. */
  94022. _this.sceneCenter = BABYLON.Vector3.Zero();
  94023. /**
  94024. * This helps specifying that the material is falling off to the sky box at grazing angle.
  94025. * This helps ensuring a nice transition when the camera goes under the ground.
  94026. */
  94027. _this.opacityFresnel = true;
  94028. /**
  94029. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  94030. * This helps adding a mirror texture on the ground.
  94031. */
  94032. _this.reflectionFresnel = false;
  94033. /**
  94034. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  94035. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  94036. */
  94037. _this.reflectionFalloffDistance = 0.0;
  94038. /**
  94039. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  94040. */
  94041. _this.reflectionAmount = 1.0;
  94042. /**
  94043. * This specifies the weight of the reflection at grazing angle.
  94044. */
  94045. _this.reflectionReflectance0 = 0.05;
  94046. /**
  94047. * This specifies the weight of the reflection at a perpendicular point of view.
  94048. */
  94049. _this.reflectionReflectance90 = 0.5;
  94050. /**
  94051. * Helps to directly use the maps channels instead of their level.
  94052. */
  94053. _this.useRGBColor = true;
  94054. /**
  94055. * This helps reducing the banding effect that could occur on the background.
  94056. */
  94057. _this.enableNoise = false;
  94058. _this._fovMultiplier = 1.0;
  94059. /**
  94060. * Enable the FOV adjustment feature controlled by fovMultiplier.
  94061. */
  94062. _this.useEquirectangularFOV = false;
  94063. _this._maxSimultaneousLights = 4;
  94064. /**
  94065. * Number of Simultaneous lights allowed on the material.
  94066. */
  94067. _this.maxSimultaneousLights = 4;
  94068. /**
  94069. * Keep track of the image processing observer to allow dispose and replace.
  94070. */
  94071. _this._imageProcessingObserver = null;
  94072. /**
  94073. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  94074. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  94075. */
  94076. _this.switchToBGR = false;
  94077. // Temp values kept as cache in the material.
  94078. _this._renderTargets = new BABYLON.SmartArray(16);
  94079. _this._reflectionControls = BABYLON.Vector4.Zero();
  94080. // Setup the default processing configuration to the scene.
  94081. _this._attachImageProcessingConfiguration(null);
  94082. _this.getRenderTargetTextures = function () {
  94083. _this._renderTargets.reset();
  94084. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  94085. _this._renderTargets.push(_this._diffuseTexture);
  94086. }
  94087. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  94088. _this._renderTargets.push(_this._reflectionTexture);
  94089. }
  94090. return _this._renderTargets;
  94091. };
  94092. return _this;
  94093. }
  94094. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  94095. /**
  94096. * Sets the reflection reflectance fresnel values according to the default standard
  94097. * empirically know to work well :-)
  94098. */
  94099. set: function (value) {
  94100. var reflectionWeight = value;
  94101. if (reflectionWeight < 0.5) {
  94102. reflectionWeight = reflectionWeight * 2.0;
  94103. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  94104. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  94105. }
  94106. else {
  94107. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  94108. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  94109. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  94110. }
  94111. },
  94112. enumerable: true,
  94113. configurable: true
  94114. });
  94115. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  94116. /**
  94117. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  94118. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  94119. * Recommended to be keep at 1.0 except for special cases.
  94120. */
  94121. get: function () {
  94122. return this._fovMultiplier;
  94123. },
  94124. set: function (value) {
  94125. if (isNaN(value)) {
  94126. value = 1.0;
  94127. }
  94128. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  94129. },
  94130. enumerable: true,
  94131. configurable: true
  94132. });
  94133. /**
  94134. * Attaches a new image processing configuration to the PBR Material.
  94135. * @param configuration (if null the scene configuration will be use)
  94136. */
  94137. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  94138. var _this = this;
  94139. if (configuration === this._imageProcessingConfiguration) {
  94140. return;
  94141. }
  94142. // Detaches observer.
  94143. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94144. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94145. }
  94146. // Pick the scene configuration if needed.
  94147. if (!configuration) {
  94148. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  94149. }
  94150. else {
  94151. this._imageProcessingConfiguration = configuration;
  94152. }
  94153. // Attaches observer.
  94154. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  94155. _this._markAllSubMeshesAsImageProcessingDirty();
  94156. });
  94157. };
  94158. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  94159. /**
  94160. * Gets the image processing configuration used either in this material.
  94161. */
  94162. get: function () {
  94163. return this._imageProcessingConfiguration;
  94164. },
  94165. /**
  94166. * Sets the Default image processing configuration used either in the this material.
  94167. *
  94168. * If sets to null, the scene one is in use.
  94169. */
  94170. set: function (value) {
  94171. this._attachImageProcessingConfiguration(value);
  94172. // Ensure the effect will be rebuilt.
  94173. this._markAllSubMeshesAsTexturesDirty();
  94174. },
  94175. enumerable: true,
  94176. configurable: true
  94177. });
  94178. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  94179. /**
  94180. * Gets wether the color curves effect is enabled.
  94181. */
  94182. get: function () {
  94183. return this.imageProcessingConfiguration.colorCurvesEnabled;
  94184. },
  94185. /**
  94186. * Sets wether the color curves effect is enabled.
  94187. */
  94188. set: function (value) {
  94189. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  94190. },
  94191. enumerable: true,
  94192. configurable: true
  94193. });
  94194. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  94195. /**
  94196. * Gets wether the color grading effect is enabled.
  94197. */
  94198. get: function () {
  94199. return this.imageProcessingConfiguration.colorGradingEnabled;
  94200. },
  94201. /**
  94202. * Gets wether the color grading effect is enabled.
  94203. */
  94204. set: function (value) {
  94205. this.imageProcessingConfiguration.colorGradingEnabled = value;
  94206. },
  94207. enumerable: true,
  94208. configurable: true
  94209. });
  94210. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  94211. /**
  94212. * Gets wether tonemapping is enabled or not.
  94213. */
  94214. get: function () {
  94215. return this._imageProcessingConfiguration.toneMappingEnabled;
  94216. },
  94217. /**
  94218. * Sets wether tonemapping is enabled or not
  94219. */
  94220. set: function (value) {
  94221. this._imageProcessingConfiguration.toneMappingEnabled = value;
  94222. },
  94223. enumerable: true,
  94224. configurable: true
  94225. });
  94226. ;
  94227. ;
  94228. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  94229. /**
  94230. * The camera exposure used on this material.
  94231. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94232. * This corresponds to a photographic exposure.
  94233. */
  94234. get: function () {
  94235. return this._imageProcessingConfiguration.exposure;
  94236. },
  94237. /**
  94238. * The camera exposure used on this material.
  94239. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  94240. * This corresponds to a photographic exposure.
  94241. */
  94242. set: function (value) {
  94243. this._imageProcessingConfiguration.exposure = value;
  94244. },
  94245. enumerable: true,
  94246. configurable: true
  94247. });
  94248. ;
  94249. ;
  94250. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  94251. /**
  94252. * Gets The camera contrast used on this material.
  94253. */
  94254. get: function () {
  94255. return this._imageProcessingConfiguration.contrast;
  94256. },
  94257. /**
  94258. * Sets The camera contrast used on this material.
  94259. */
  94260. set: function (value) {
  94261. this._imageProcessingConfiguration.contrast = value;
  94262. },
  94263. enumerable: true,
  94264. configurable: true
  94265. });
  94266. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  94267. /**
  94268. * Gets the Color Grading 2D Lookup Texture.
  94269. */
  94270. get: function () {
  94271. return this._imageProcessingConfiguration.colorGradingTexture;
  94272. },
  94273. /**
  94274. * Sets the Color Grading 2D Lookup Texture.
  94275. */
  94276. set: function (value) {
  94277. this.imageProcessingConfiguration.colorGradingTexture = value;
  94278. },
  94279. enumerable: true,
  94280. configurable: true
  94281. });
  94282. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  94283. /**
  94284. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  94285. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  94286. * 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;
  94287. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  94288. */
  94289. get: function () {
  94290. return this.imageProcessingConfiguration.colorCurves;
  94291. },
  94292. /**
  94293. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  94294. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  94295. * 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;
  94296. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  94297. */
  94298. set: function (value) {
  94299. this.imageProcessingConfiguration.colorCurves = value;
  94300. },
  94301. enumerable: true,
  94302. configurable: true
  94303. });
  94304. /**
  94305. * The entire material has been created in order to prevent overdraw.
  94306. * @returns false
  94307. */
  94308. BackgroundMaterial.prototype.needAlphaTesting = function () {
  94309. return true;
  94310. };
  94311. /**
  94312. * The entire material has been created in order to prevent overdraw.
  94313. * @returns true if blending is enable
  94314. */
  94315. BackgroundMaterial.prototype.needAlphaBlending = function () {
  94316. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  94317. };
  94318. /**
  94319. * Checks wether the material is ready to be rendered for a given mesh.
  94320. * @param mesh The mesh to render
  94321. * @param subMesh The submesh to check against
  94322. * @param useInstances Specify wether or not the material is used with instances
  94323. * @returns true if all the dependencies are ready (Textures, Effects...)
  94324. */
  94325. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  94326. var _this = this;
  94327. if (useInstances === void 0) { useInstances = false; }
  94328. if (subMesh.effect && this.isFrozen) {
  94329. if (this._wasPreviouslyReady) {
  94330. return true;
  94331. }
  94332. }
  94333. if (!subMesh._materialDefines) {
  94334. subMesh._materialDefines = new BackgroundMaterialDefines();
  94335. }
  94336. var scene = this.getScene();
  94337. var defines = subMesh._materialDefines;
  94338. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  94339. if (defines._renderId === scene.getRenderId()) {
  94340. return true;
  94341. }
  94342. }
  94343. var engine = scene.getEngine();
  94344. // Lights
  94345. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  94346. defines._needNormals = true;
  94347. // Textures
  94348. if (defines._areTexturesDirty) {
  94349. defines._needUVs = false;
  94350. if (scene.texturesEnabled) {
  94351. if (scene.getEngine().getCaps().textureLOD) {
  94352. defines.TEXTURELODSUPPORT = true;
  94353. }
  94354. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94355. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  94356. return false;
  94357. }
  94358. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  94359. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  94360. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  94361. defines.OPACITYFRESNEL = this._opacityFresnel;
  94362. }
  94363. else {
  94364. defines.DIFFUSE = false;
  94365. defines.DIFFUSEHASALPHA = false;
  94366. defines.GAMMADIFFUSE = false;
  94367. defines.OPACITYFRESNEL = false;
  94368. }
  94369. var reflectionTexture = this._reflectionTexture;
  94370. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94371. if (!reflectionTexture.isReadyOrNotBlocking()) {
  94372. return false;
  94373. }
  94374. defines.REFLECTION = true;
  94375. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  94376. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  94377. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  94378. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  94379. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  94380. defines.REFLECTIONBGR = this.switchToBGR;
  94381. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  94382. defines.INVERTCUBICMAP = true;
  94383. }
  94384. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  94385. switch (reflectionTexture.coordinatesMode) {
  94386. case BABYLON.Texture.CUBIC_MODE:
  94387. case BABYLON.Texture.INVCUBIC_MODE:
  94388. defines.REFLECTIONMAP_CUBIC = true;
  94389. break;
  94390. case BABYLON.Texture.EXPLICIT_MODE:
  94391. defines.REFLECTIONMAP_EXPLICIT = true;
  94392. break;
  94393. case BABYLON.Texture.PLANAR_MODE:
  94394. defines.REFLECTIONMAP_PLANAR = true;
  94395. break;
  94396. case BABYLON.Texture.PROJECTION_MODE:
  94397. defines.REFLECTIONMAP_PROJECTION = true;
  94398. break;
  94399. case BABYLON.Texture.SKYBOX_MODE:
  94400. defines.REFLECTIONMAP_SKYBOX = true;
  94401. break;
  94402. case BABYLON.Texture.SPHERICAL_MODE:
  94403. defines.REFLECTIONMAP_SPHERICAL = true;
  94404. break;
  94405. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  94406. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  94407. break;
  94408. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  94409. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  94410. break;
  94411. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  94412. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  94413. break;
  94414. }
  94415. if (this.reflectionFresnel) {
  94416. defines.REFLECTIONFRESNEL = true;
  94417. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  94418. this._reflectionControls.x = this.reflectionAmount;
  94419. this._reflectionControls.y = this.reflectionReflectance0;
  94420. this._reflectionControls.z = this.reflectionReflectance90;
  94421. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  94422. }
  94423. else {
  94424. defines.REFLECTIONFRESNEL = false;
  94425. defines.REFLECTIONFALLOFF = false;
  94426. }
  94427. }
  94428. else {
  94429. defines.REFLECTION = false;
  94430. defines.REFLECTIONFALLOFF = false;
  94431. defines.REFLECTIONBLUR = false;
  94432. defines.REFLECTIONMAP_3D = false;
  94433. defines.REFLECTIONMAP_SPHERICAL = false;
  94434. defines.REFLECTIONMAP_PLANAR = false;
  94435. defines.REFLECTIONMAP_CUBIC = false;
  94436. defines.REFLECTIONMAP_PROJECTION = false;
  94437. defines.REFLECTIONMAP_SKYBOX = false;
  94438. defines.REFLECTIONMAP_EXPLICIT = false;
  94439. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  94440. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  94441. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  94442. defines.INVERTCUBICMAP = false;
  94443. defines.REFLECTIONMAP_OPPOSITEZ = false;
  94444. defines.LODINREFLECTIONALPHA = false;
  94445. defines.GAMMAREFLECTION = false;
  94446. }
  94447. }
  94448. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  94449. defines.USERGBCOLOR = this._useRGBColor;
  94450. defines.NOISE = this._enableNoise;
  94451. }
  94452. if (defines._areImageProcessingDirty) {
  94453. if (!this._imageProcessingConfiguration.isReady()) {
  94454. return false;
  94455. }
  94456. this._imageProcessingConfiguration.prepareDefines(defines);
  94457. }
  94458. // Misc.
  94459. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  94460. // Values that need to be evaluated on every frame
  94461. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  94462. // Attribs
  94463. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  94464. if (mesh) {
  94465. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  94466. mesh.createNormals(true);
  94467. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  94468. }
  94469. }
  94470. }
  94471. // Get correct effect
  94472. if (defines.isDirty) {
  94473. defines.markAsProcessed();
  94474. scene.resetCachedMaterial();
  94475. // Fallbacks
  94476. var fallbacks = new BABYLON.EffectFallbacks();
  94477. if (defines.FOG) {
  94478. fallbacks.addFallback(0, "FOG");
  94479. }
  94480. if (defines.POINTSIZE) {
  94481. fallbacks.addFallback(1, "POINTSIZE");
  94482. }
  94483. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  94484. if (defines.NUM_BONE_INFLUENCERS > 0) {
  94485. fallbacks.addCPUSkinningFallback(0, mesh);
  94486. }
  94487. //Attributes
  94488. var attribs = [BABYLON.VertexBuffer.PositionKind];
  94489. if (defines.NORMAL) {
  94490. attribs.push(BABYLON.VertexBuffer.NormalKind);
  94491. }
  94492. if (defines.UV1) {
  94493. attribs.push(BABYLON.VertexBuffer.UVKind);
  94494. }
  94495. if (defines.UV2) {
  94496. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94497. }
  94498. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  94499. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  94500. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  94501. "vFogInfos", "vFogColor", "pointSize",
  94502. "vClipPlane", "mBones",
  94503. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  94504. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  94505. "shadowLevel", "alpha",
  94506. "vBackgroundCenter", "vReflectionControl",
  94507. "vDiffuseInfos", "diffuseMatrix",
  94508. ];
  94509. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  94510. var uniformBuffers = ["Material", "Scene"];
  94511. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  94512. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  94513. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  94514. uniformsNames: uniforms,
  94515. uniformBuffersNames: uniformBuffers,
  94516. samplers: samplers,
  94517. defines: defines,
  94518. maxSimultaneousLights: this._maxSimultaneousLights
  94519. });
  94520. var onCompiled = function (effect) {
  94521. if (_this.onCompiled) {
  94522. _this.onCompiled(effect);
  94523. }
  94524. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  94525. };
  94526. var join = defines.toString();
  94527. subMesh.setEffect(scene.getEngine().createEffect("background", {
  94528. attributes: attribs,
  94529. uniformsNames: uniforms,
  94530. uniformBuffersNames: uniformBuffers,
  94531. samplers: samplers,
  94532. defines: join,
  94533. fallbacks: fallbacks,
  94534. onCompiled: onCompiled,
  94535. onError: this.onError,
  94536. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  94537. }, engine), defines);
  94538. this.buildUniformLayout();
  94539. }
  94540. if (!subMesh.effect || !subMesh.effect.isReady()) {
  94541. return false;
  94542. }
  94543. defines._renderId = scene.getRenderId();
  94544. this._wasPreviouslyReady = true;
  94545. return true;
  94546. };
  94547. /**
  94548. * Build the uniform buffer used in the material.
  94549. */
  94550. BackgroundMaterial.prototype.buildUniformLayout = function () {
  94551. // Order is important !
  94552. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  94553. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  94554. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  94555. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  94556. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  94557. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  94558. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  94559. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  94560. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  94561. this._uniformBuffer.addUniform("pointSize", 1);
  94562. this._uniformBuffer.addUniform("shadowLevel", 1);
  94563. this._uniformBuffer.addUniform("alpha", 1);
  94564. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  94565. this._uniformBuffer.addUniform("vReflectionControl", 4);
  94566. this._uniformBuffer.create();
  94567. };
  94568. /**
  94569. * Unbind the material.
  94570. */
  94571. BackgroundMaterial.prototype.unbind = function () {
  94572. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  94573. this._uniformBuffer.setTexture("diffuseSampler", null);
  94574. }
  94575. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  94576. this._uniformBuffer.setTexture("reflectionSampler", null);
  94577. }
  94578. _super.prototype.unbind.call(this);
  94579. };
  94580. /**
  94581. * Bind only the world matrix to the material.
  94582. * @param world The world matrix to bind.
  94583. */
  94584. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  94585. this._activeEffect.setMatrix("world", world);
  94586. };
  94587. /**
  94588. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  94589. * @param world The world matrix to bind.
  94590. * @param subMesh The submesh to bind for.
  94591. */
  94592. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  94593. var scene = this.getScene();
  94594. var defines = subMesh._materialDefines;
  94595. if (!defines) {
  94596. return;
  94597. }
  94598. var effect = subMesh.effect;
  94599. if (!effect) {
  94600. return;
  94601. }
  94602. this._activeEffect = effect;
  94603. // Matrices
  94604. this.bindOnlyWorldMatrix(world);
  94605. // Bones
  94606. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  94607. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  94608. if (mustRebind) {
  94609. this._uniformBuffer.bindToEffect(effect, "Material");
  94610. this.bindViewProjection(effect);
  94611. var reflectionTexture = this._reflectionTexture;
  94612. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  94613. // Texture uniforms
  94614. if (scene.texturesEnabled) {
  94615. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94616. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  94617. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  94618. }
  94619. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94620. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  94621. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  94622. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  94623. }
  94624. }
  94625. if (this.shadowLevel > 0) {
  94626. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  94627. }
  94628. this._uniformBuffer.updateFloat("alpha", this.alpha);
  94629. // Point size
  94630. if (this.pointsCloud) {
  94631. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  94632. }
  94633. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  94634. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  94635. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  94636. }
  94637. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  94638. // Textures
  94639. if (scene.texturesEnabled) {
  94640. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  94641. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  94642. }
  94643. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  94644. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  94645. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  94646. }
  94647. else if (!defines.REFLECTIONBLUR) {
  94648. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  94649. }
  94650. else {
  94651. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  94652. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  94653. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  94654. }
  94655. if (defines.REFLECTIONFRESNEL) {
  94656. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  94657. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  94658. }
  94659. }
  94660. }
  94661. // Clip plane
  94662. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  94663. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  94664. }
  94665. if (mustRebind || !this.isFrozen) {
  94666. if (scene.lightsEnabled) {
  94667. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  94668. }
  94669. // View
  94670. this.bindView(effect);
  94671. // Fog
  94672. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  94673. // image processing
  94674. this._imageProcessingConfiguration.bind(this._activeEffect);
  94675. }
  94676. this._uniformBuffer.update();
  94677. this._afterBind(mesh);
  94678. };
  94679. /**
  94680. * Dispose the material.
  94681. * @param forceDisposeEffect Force disposal of the associated effect.
  94682. * @param forceDisposeTextures Force disposal of the associated textures.
  94683. */
  94684. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  94685. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  94686. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  94687. if (forceDisposeTextures) {
  94688. if (this.diffuseTexture) {
  94689. this.diffuseTexture.dispose();
  94690. }
  94691. if (this.reflectionTexture) {
  94692. this.reflectionTexture.dispose();
  94693. }
  94694. }
  94695. this._renderTargets.dispose();
  94696. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  94697. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  94698. }
  94699. _super.prototype.dispose.call(this, forceDisposeEffect);
  94700. };
  94701. /**
  94702. * Clones the material.
  94703. * @param name The cloned name.
  94704. * @returns The cloned material.
  94705. */
  94706. BackgroundMaterial.prototype.clone = function (name) {
  94707. var _this = this;
  94708. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  94709. };
  94710. /**
  94711. * Serializes the current material to its JSON representation.
  94712. * @returns The JSON representation.
  94713. */
  94714. BackgroundMaterial.prototype.serialize = function () {
  94715. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94716. serializationObject.customType = "BABYLON.BackgroundMaterial";
  94717. return serializationObject;
  94718. };
  94719. /**
  94720. * Gets the class name of the material
  94721. * @returns "BackgroundMaterial"
  94722. */
  94723. BackgroundMaterial.prototype.getClassName = function () {
  94724. return "BackgroundMaterial";
  94725. };
  94726. /**
  94727. * Parse a JSON input to create back a background material.
  94728. * @param source The JSON data to parse
  94729. * @param scene The scene to create the parsed material in
  94730. * @param rootUrl The root url of the assets the material depends upon
  94731. * @returns the instantiated BackgroundMaterial.
  94732. */
  94733. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  94734. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  94735. };
  94736. /**
  94737. * Standard reflectance value at parallel view angle.
  94738. */
  94739. BackgroundMaterial.StandardReflectance0 = 0.05;
  94740. /**
  94741. * Standard reflectance value at grazing angle.
  94742. */
  94743. BackgroundMaterial.StandardReflectance90 = 0.5;
  94744. __decorate([
  94745. BABYLON.serializeAsColor3()
  94746. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  94747. __decorate([
  94748. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94749. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  94750. __decorate([
  94751. BABYLON.serialize()
  94752. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  94753. __decorate([
  94754. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94755. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  94756. __decorate([
  94757. BABYLON.serializeAsColor3()
  94758. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  94759. __decorate([
  94760. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94761. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  94762. __decorate([
  94763. BABYLON.serialize()
  94764. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  94765. __decorate([
  94766. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94767. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  94768. __decorate([
  94769. BABYLON.serializeAsColor3()
  94770. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  94771. __decorate([
  94772. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94773. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  94774. __decorate([
  94775. BABYLON.serialize()
  94776. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  94777. __decorate([
  94778. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  94779. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  94780. __decorate([
  94781. BABYLON.serializeAsTexture()
  94782. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  94783. __decorate([
  94784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94785. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  94786. __decorate([
  94787. BABYLON.serialize()
  94788. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  94789. __decorate([
  94790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94791. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  94792. __decorate([
  94793. BABYLON.serializeAsTexture()
  94794. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  94795. __decorate([
  94796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94797. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  94798. __decorate([
  94799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94800. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  94801. __decorate([
  94802. BABYLON.serialize()
  94803. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  94804. __decorate([
  94805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94806. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  94807. __decorate([
  94808. BABYLON.serialize()
  94809. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  94810. __decorate([
  94811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94812. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  94813. __decorate([
  94814. BABYLON.serializeAsVector3()
  94815. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  94816. __decorate([
  94817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94818. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  94819. __decorate([
  94820. BABYLON.serialize()
  94821. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  94822. __decorate([
  94823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94824. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  94825. __decorate([
  94826. BABYLON.serialize()
  94827. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  94828. __decorate([
  94829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94830. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  94831. __decorate([
  94832. BABYLON.serialize()
  94833. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  94834. __decorate([
  94835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94836. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  94837. __decorate([
  94838. BABYLON.serialize()
  94839. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  94840. __decorate([
  94841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94842. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  94843. __decorate([
  94844. BABYLON.serialize()
  94845. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  94846. __decorate([
  94847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94848. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  94849. __decorate([
  94850. BABYLON.serialize()
  94851. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  94852. __decorate([
  94853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94854. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  94855. __decorate([
  94856. BABYLON.serialize()
  94857. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  94858. __decorate([
  94859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94860. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  94861. __decorate([
  94862. BABYLON.serialize()
  94863. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  94864. __decorate([
  94865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94866. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  94867. __decorate([
  94868. BABYLON.serialize()
  94869. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  94870. __decorate([
  94871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  94872. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  94873. __decorate([
  94874. BABYLON.serializeAsImageProcessingConfiguration()
  94875. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  94876. return BackgroundMaterial;
  94877. }(BABYLON.PushMaterial));
  94878. BABYLON.BackgroundMaterial = BackgroundMaterial;
  94879. })(BABYLON || (BABYLON = {}));
  94880. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  94881. "use strict";
  94882. var __assign = (this && this.__assign) || Object.assign || function(t) {
  94883. for (var s, i = 1, n = arguments.length; i < n; i++) {
  94884. s = arguments[i];
  94885. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  94886. t[p] = s[p];
  94887. }
  94888. return t;
  94889. };
  94890. var BABYLON;
  94891. (function (BABYLON) {
  94892. /**
  94893. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  94894. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  94895. * It also helps with the default setup of your imageProcessing configuration.
  94896. */
  94897. var EnvironmentHelper = /** @class */ (function () {
  94898. /**
  94899. * constructor
  94900. * @param options
  94901. * @param scene The scene to add the material to
  94902. */
  94903. function EnvironmentHelper(options, scene) {
  94904. var _this = this;
  94905. this._errorHandler = function (message, exception) {
  94906. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  94907. };
  94908. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  94909. this._scene = scene;
  94910. this.onErrorObservable = new BABYLON.Observable();
  94911. this._setupBackground();
  94912. this._setupImageProcessing();
  94913. }
  94914. /**
  94915. * Creates the default options for the helper.
  94916. */
  94917. EnvironmentHelper._getDefaultOptions = function () {
  94918. return {
  94919. createGround: true,
  94920. groundSize: 15,
  94921. groundTexture: this._groundTextureCDNUrl,
  94922. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  94923. groundOpacity: 0.9,
  94924. enableGroundShadow: true,
  94925. groundShadowLevel: 0.5,
  94926. enableGroundMirror: false,
  94927. groundMirrorSizeRatio: 0.3,
  94928. groundMirrorBlurKernel: 64,
  94929. groundMirrorAmount: 1,
  94930. groundMirrorFresnelWeight: 1,
  94931. groundMirrorFallOffDistance: 0,
  94932. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  94933. groundYBias: 0.00001,
  94934. createSkybox: true,
  94935. skyboxSize: 20,
  94936. skyboxTexture: this._skyboxTextureCDNUrl,
  94937. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  94938. backgroundYRotation: 0,
  94939. sizeAuto: true,
  94940. rootPosition: BABYLON.Vector3.Zero(),
  94941. setupImageProcessing: true,
  94942. environmentTexture: this._environmentTextureCDNUrl,
  94943. cameraExposure: 0.8,
  94944. cameraContrast: 1.2,
  94945. toneMappingEnabled: true,
  94946. };
  94947. };
  94948. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  94949. /**
  94950. * Gets the root mesh created by the helper.
  94951. */
  94952. get: function () {
  94953. return this._rootMesh;
  94954. },
  94955. enumerable: true,
  94956. configurable: true
  94957. });
  94958. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  94959. /**
  94960. * Gets the skybox created by the helper.
  94961. */
  94962. get: function () {
  94963. return this._skybox;
  94964. },
  94965. enumerable: true,
  94966. configurable: true
  94967. });
  94968. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  94969. /**
  94970. * Gets the skybox texture created by the helper.
  94971. */
  94972. get: function () {
  94973. return this._skyboxTexture;
  94974. },
  94975. enumerable: true,
  94976. configurable: true
  94977. });
  94978. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  94979. /**
  94980. * Gets the skybox material created by the helper.
  94981. */
  94982. get: function () {
  94983. return this._skyboxMaterial;
  94984. },
  94985. enumerable: true,
  94986. configurable: true
  94987. });
  94988. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  94989. /**
  94990. * Gets the ground mesh created by the helper.
  94991. */
  94992. get: function () {
  94993. return this._ground;
  94994. },
  94995. enumerable: true,
  94996. configurable: true
  94997. });
  94998. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  94999. /**
  95000. * Gets the ground texture created by the helper.
  95001. */
  95002. get: function () {
  95003. return this._groundTexture;
  95004. },
  95005. enumerable: true,
  95006. configurable: true
  95007. });
  95008. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  95009. /**
  95010. * Gets the ground mirror created by the helper.
  95011. */
  95012. get: function () {
  95013. return this._groundMirror;
  95014. },
  95015. enumerable: true,
  95016. configurable: true
  95017. });
  95018. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  95019. /**
  95020. * Gets the ground mirror render list to helps pushing the meshes
  95021. * you wish in the ground reflection.
  95022. */
  95023. get: function () {
  95024. if (this._groundMirror) {
  95025. return this._groundMirror.renderList;
  95026. }
  95027. return null;
  95028. },
  95029. enumerable: true,
  95030. configurable: true
  95031. });
  95032. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  95033. /**
  95034. * Gets the ground material created by the helper.
  95035. */
  95036. get: function () {
  95037. return this._groundMaterial;
  95038. },
  95039. enumerable: true,
  95040. configurable: true
  95041. });
  95042. /**
  95043. * Updates the background according to the new options
  95044. * @param options
  95045. */
  95046. EnvironmentHelper.prototype.updateOptions = function (options) {
  95047. var newOptions = __assign({}, this._options, options);
  95048. if (this._ground && !newOptions.createGround) {
  95049. this._ground.dispose();
  95050. this._ground = null;
  95051. }
  95052. if (this._groundMaterial && !newOptions.createGround) {
  95053. this._groundMaterial.dispose();
  95054. this._groundMaterial = null;
  95055. }
  95056. if (this._groundTexture) {
  95057. if (this._options.groundTexture != newOptions.groundTexture) {
  95058. this._groundTexture.dispose();
  95059. this._groundTexture = null;
  95060. }
  95061. }
  95062. if (this._skybox && !newOptions.createSkybox) {
  95063. this._skybox.dispose();
  95064. this._skybox = null;
  95065. }
  95066. if (this._skyboxMaterial && !newOptions.createSkybox) {
  95067. this._skyboxMaterial.dispose();
  95068. this._skyboxMaterial = null;
  95069. }
  95070. if (this._skyboxTexture) {
  95071. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  95072. this._skyboxTexture.dispose();
  95073. this._skyboxTexture = null;
  95074. }
  95075. }
  95076. if (this._groundMirror && !newOptions.enableGroundMirror) {
  95077. this._groundMirror.dispose();
  95078. this._groundMirror = null;
  95079. }
  95080. if (this._scene.environmentTexture) {
  95081. if (this._options.environmentTexture != newOptions.environmentTexture) {
  95082. this._scene.environmentTexture.dispose();
  95083. }
  95084. }
  95085. this._options = newOptions;
  95086. this._setupBackground();
  95087. this._setupImageProcessing();
  95088. };
  95089. /**
  95090. * Sets the primary color of all the available elements.
  95091. * @param color
  95092. */
  95093. EnvironmentHelper.prototype.setMainColor = function (color) {
  95094. if (this.groundMaterial) {
  95095. this.groundMaterial.primaryColor = color;
  95096. }
  95097. if (this.skyboxMaterial) {
  95098. this.skyboxMaterial.primaryColor = color;
  95099. }
  95100. if (this.groundMirror) {
  95101. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  95102. }
  95103. };
  95104. /**
  95105. * Setup the image processing according to the specified options.
  95106. */
  95107. EnvironmentHelper.prototype._setupImageProcessing = function () {
  95108. if (this._options.setupImageProcessing) {
  95109. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  95110. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  95111. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  95112. this._setupEnvironmentTexture();
  95113. }
  95114. };
  95115. /**
  95116. * Setup the environment texture according to the specified options.
  95117. */
  95118. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  95119. if (this._scene.environmentTexture) {
  95120. return;
  95121. }
  95122. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  95123. this._scene.environmentTexture = this._options.environmentTexture;
  95124. return;
  95125. }
  95126. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  95127. this._scene.environmentTexture = environmentTexture;
  95128. };
  95129. /**
  95130. * Setup the background according to the specified options.
  95131. */
  95132. EnvironmentHelper.prototype._setupBackground = function () {
  95133. if (!this._rootMesh) {
  95134. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  95135. }
  95136. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  95137. var sceneSize = this._getSceneSize();
  95138. if (this._options.createGround) {
  95139. this._setupGround(sceneSize);
  95140. this._setupGroundMaterial();
  95141. this._setupGroundDiffuseTexture();
  95142. if (this._options.enableGroundMirror) {
  95143. this._setupGroundMirrorTexture(sceneSize);
  95144. }
  95145. this._setupMirrorInGroundMaterial();
  95146. }
  95147. if (this._options.createSkybox) {
  95148. this._setupSkybox(sceneSize);
  95149. this._setupSkyboxMaterial();
  95150. this._setupSkyboxReflectionTexture();
  95151. }
  95152. this._rootMesh.position.x = sceneSize.rootPosition.x;
  95153. this._rootMesh.position.z = sceneSize.rootPosition.z;
  95154. this._rootMesh.position.y = sceneSize.rootPosition.y;
  95155. };
  95156. /**
  95157. * Get the scene sizes according to the setup.
  95158. */
  95159. EnvironmentHelper.prototype._getSceneSize = function () {
  95160. var _this = this;
  95161. var groundSize = this._options.groundSize;
  95162. var skyboxSize = this._options.skyboxSize;
  95163. var rootPosition = this._options.rootPosition;
  95164. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  95165. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95166. }
  95167. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  95168. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  95169. });
  95170. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  95171. if (this._options.sizeAuto) {
  95172. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  95173. this._scene.activeCamera.upperRadiusLimit) {
  95174. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  95175. skyboxSize = groundSize;
  95176. }
  95177. var sceneDiagonalLenght = sceneDiagonal.length();
  95178. if (sceneDiagonalLenght > groundSize) {
  95179. groundSize = sceneDiagonalLenght * 2;
  95180. skyboxSize = groundSize;
  95181. }
  95182. // 10 % bigger.
  95183. groundSize *= 1.1;
  95184. skyboxSize *= 1.5;
  95185. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  95186. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  95187. }
  95188. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  95189. };
  95190. /**
  95191. * Setup the ground according to the specified options.
  95192. */
  95193. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  95194. var _this = this;
  95195. if (!this._ground) {
  95196. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  95197. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  95198. this._ground.parent = this._rootMesh;
  95199. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  95200. }
  95201. this._ground.receiveShadows = this._options.enableGroundShadow;
  95202. };
  95203. /**
  95204. * Setup the ground material according to the specified options.
  95205. */
  95206. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  95207. if (!this._groundMaterial) {
  95208. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  95209. }
  95210. this._groundMaterial.alpha = this._options.groundOpacity;
  95211. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  95212. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  95213. this._groundMaterial.primaryLevel = 1;
  95214. this._groundMaterial.primaryColor = this._options.groundColor;
  95215. this._groundMaterial.secondaryLevel = 0;
  95216. this._groundMaterial.tertiaryLevel = 0;
  95217. this._groundMaterial.useRGBColor = false;
  95218. this._groundMaterial.enableNoise = true;
  95219. if (this._ground) {
  95220. this._ground.material = this._groundMaterial;
  95221. }
  95222. };
  95223. /**
  95224. * Setup the ground diffuse texture according to the specified options.
  95225. */
  95226. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  95227. if (!this._groundMaterial) {
  95228. return;
  95229. }
  95230. if (this._groundTexture) {
  95231. return;
  95232. }
  95233. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  95234. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  95235. return;
  95236. }
  95237. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  95238. diffuseTexture.gammaSpace = false;
  95239. diffuseTexture.hasAlpha = true;
  95240. this._groundMaterial.diffuseTexture = diffuseTexture;
  95241. };
  95242. /**
  95243. * Setup the ground mirror texture according to the specified options.
  95244. */
  95245. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  95246. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95247. if (!this._groundMirror) {
  95248. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  95249. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  95250. this._groundMirror.anisotropicFilteringLevel = 1;
  95251. this._groundMirror.wrapU = wrapping;
  95252. this._groundMirror.wrapV = wrapping;
  95253. this._groundMirror.gammaSpace = false;
  95254. if (this._groundMirror.renderList) {
  95255. for (var i = 0; i < this._scene.meshes.length; i++) {
  95256. var mesh = this._scene.meshes[i];
  95257. if (mesh !== this._ground &&
  95258. mesh !== this._skybox &&
  95259. mesh !== this._rootMesh) {
  95260. this._groundMirror.renderList.push(mesh);
  95261. }
  95262. }
  95263. }
  95264. }
  95265. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  95266. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  95267. };
  95268. /**
  95269. * Setup the ground to receive the mirror texture.
  95270. */
  95271. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  95272. if (this._groundMaterial) {
  95273. this._groundMaterial.reflectionTexture = this._groundMirror;
  95274. this._groundMaterial.reflectionFresnel = true;
  95275. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  95276. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  95277. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  95278. }
  95279. };
  95280. /**
  95281. * Setup the skybox according to the specified options.
  95282. */
  95283. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  95284. var _this = this;
  95285. if (!this._skybox) {
  95286. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  95287. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  95288. }
  95289. this._skybox.parent = this._rootMesh;
  95290. };
  95291. /**
  95292. * Setup the skybox material according to the specified options.
  95293. */
  95294. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  95295. if (!this._skybox) {
  95296. return;
  95297. }
  95298. if (!this._skyboxMaterial) {
  95299. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  95300. }
  95301. this._skyboxMaterial.useRGBColor = false;
  95302. this._skyboxMaterial.primaryLevel = 1;
  95303. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  95304. this._skyboxMaterial.secondaryLevel = 0;
  95305. this._skyboxMaterial.tertiaryLevel = 0;
  95306. this._skyboxMaterial.enableNoise = true;
  95307. this._skybox.material = this._skyboxMaterial;
  95308. };
  95309. /**
  95310. * Setup the skybox reflection texture according to the specified options.
  95311. */
  95312. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  95313. if (!this._skyboxMaterial) {
  95314. return;
  95315. }
  95316. if (this._skyboxTexture) {
  95317. return;
  95318. }
  95319. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  95320. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  95321. return;
  95322. }
  95323. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  95324. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  95325. this._skyboxTexture.gammaSpace = false;
  95326. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  95327. };
  95328. /**
  95329. * Dispose all the elements created by the Helper.
  95330. */
  95331. EnvironmentHelper.prototype.dispose = function () {
  95332. if (this._groundMaterial) {
  95333. this._groundMaterial.dispose(true, true);
  95334. }
  95335. if (this._skyboxMaterial) {
  95336. this._skyboxMaterial.dispose(true, true);
  95337. }
  95338. this._rootMesh.dispose(false);
  95339. };
  95340. /**
  95341. * Default ground texture URL.
  95342. */
  95343. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  95344. /**
  95345. * Default skybox texture URL.
  95346. */
  95347. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  95348. /**
  95349. * Default environment texture URL.
  95350. */
  95351. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  95352. return EnvironmentHelper;
  95353. }());
  95354. BABYLON.EnvironmentHelper = EnvironmentHelper;
  95355. })(BABYLON || (BABYLON = {}));
  95356. //# sourceMappingURL=babylon.environmentHelper.js.map
  95357. "use strict";
  95358. var BABYLON;
  95359. (function (BABYLON) {
  95360. /**
  95361. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  95362. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  95363. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  95364. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  95365. */
  95366. var VideoDome = /** @class */ (function (_super) {
  95367. __extends(VideoDome, _super);
  95368. /**
  95369. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  95370. * @param name Element's name, child elements will append suffixes for their own names.
  95371. * @param urlsOrVideo
  95372. * @param options An object containing optional or exposed sub element properties:
  95373. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  95374. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  95375. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  95376. * @param options **loop=true** Automatically loop video on end.
  95377. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  95378. */
  95379. function VideoDome(name, urlsOrVideo, options, scene) {
  95380. var _this = _super.call(this, name, scene) || this;
  95381. // set defaults and manage values
  95382. name = name || "videoDome";
  95383. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  95384. options.clickToPlay = Boolean(options.clickToPlay);
  95385. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  95386. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  95387. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  95388. // create
  95389. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  95390. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  95391. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  95392. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  95393. flat: false,
  95394. radius: options.size,
  95395. subdivisions: options.resolution,
  95396. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  95397. }, scene);
  95398. // configure material
  95399. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  95400. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  95401. material.reflectionTexture = _this._videoTexture;
  95402. material.useEquirectangularFOV = true;
  95403. material.fovMultiplier = 1.0;
  95404. // configure mesh
  95405. _this._mesh.material = material;
  95406. _this._mesh.parent = _this;
  95407. // optional configuration
  95408. if (options.clickToPlay) {
  95409. scene.onPointerUp = function () {
  95410. _this._videoTexture.video.play();
  95411. };
  95412. }
  95413. return _this;
  95414. }
  95415. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  95416. /**
  95417. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  95418. * Also see the options.resolution property.
  95419. */
  95420. get: function () {
  95421. return this._material.fovMultiplier;
  95422. },
  95423. set: function (value) {
  95424. this._material.fovMultiplier = value;
  95425. },
  95426. enumerable: true,
  95427. configurable: true
  95428. });
  95429. /**
  95430. * Releases resources associated with this node.
  95431. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  95432. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  95433. */
  95434. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  95435. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  95436. this._videoTexture.dispose();
  95437. this._mesh.dispose();
  95438. this._material.dispose();
  95439. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  95440. };
  95441. return VideoDome;
  95442. }(BABYLON.Node));
  95443. BABYLON.VideoDome = VideoDome;
  95444. })(BABYLON || (BABYLON = {}));
  95445. //# sourceMappingURL=babylon.videoDome.js.map
  95446. 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\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<0.4)\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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(GEOMETRYAA)\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#ifdef GEOMETRYAA\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#include<bumpFragment>\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 GEOMETRYAA\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(reflectionCoords,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\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\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"};
  95447. 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;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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}","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;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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};"};